diff --git a/.gitignore b/.gitignore
index af632bd076..3405f9731b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -13,6 +13,7 @@ target
*.class
+*.swp
# Mobile Tools for Java (J2ME)
.mtj.tmp/
diff --git a/README.md b/README.md
index 7b2b7e1b8c..3d821b7761 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,7 @@
# carbon-device-mgt

-
- Java7
-
- Java8
+
- Java8
WSO2 CONNECTED DEVICE MANAGEMENT COMPONENTS
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 0f23492eda..4a903cf6cc 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.annotations
- 3.0.46-SNAPSHOT
+ 3.0.217-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 220e24581a..7f1c19bc73 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
org.wso2.carbon.apimgt.application.extension.api
war
WSO2 Carbon - API Application Management API
@@ -197,6 +197,32 @@
${project.artifactId}
+
+ 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
+
+
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java
index 54d68e7baa..4aedb87877 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java
@@ -44,6 +44,9 @@ public class APIUtil {
private static final String DEFAULT_CDMF_API_TAG = "device_management";
private static final String DEFAULT_AGENT_API_TAG = "device_agent";
private static final String DEFAULT_CERT_API_TAG = "scep_management";
+ private static final String DEFAULT_APP_MGT_TAG = "application_management";
+ private static final String DEFAULT_APP_MGT_LCYCLE_MGT_TAG = "lifecycle_management";
+ private static final String DEFAULT_APP_MGT_SUB_MGT_TAG = "subscription_management";
public static final String PERMISSION_PROPERTY_NAME = "name";
public static String getAuthenticatedUser() {
@@ -108,6 +111,9 @@ public class APIUtil {
allowedApisTags.add(DEFAULT_CDMF_API_TAG);
allowedApisTags.add(DEFAULT_CERT_API_TAG);
allowedApisTags.add(DEFAULT_AGENT_API_TAG);
+ allowedApisTags.add(DEFAULT_APP_MGT_TAG);
+ allowedApisTags.add(DEFAULT_APP_MGT_LCYCLE_MGT_TAG);
+ allowedApisTags.add(DEFAULT_APP_MGT_SUB_MGT_TAG);
return allowedApisTags;
}
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 8cd5a42506..fdb9f1a016 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
org.wso2.carbon.apimgt.application.extension
bundle
WSO2 Carbon - API Application Management
@@ -119,6 +119,32 @@
+
+ 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
+
+
+
+
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 fbf325db15..8acc92772d 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.handlers
- 3.0.46-SNAPSHOT
+ 3.0.217-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,41 @@
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ src/test/resources/testng.xml
+
+
+
+
+ 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
+
+
+
+
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..f149868e76 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,16 +115,18 @@ 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 {
- DocumentBuilder docBuilder = factory.newDocumentBuilder();
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
+ DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new APIMCertificateMGTException("Error occurred while parsing file, while converting " +
@@ -126,48 +136,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 +188,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 842f0e6bfe..cf751f1595 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.integration.client
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
bundle
WSO2 Carbon - API Management Integration Client
WSO2 Carbon - API Management Integration Client
@@ -80,6 +80,32 @@
+
+ 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
+
+
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java
index 7878bcfffd..6341dc7a22 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/IntegrationClientServiceImpl.java
@@ -25,14 +25,32 @@ import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
public class IntegrationClientServiceImpl implements IntegrationClientService {
- private static StoreClient storeClient;
- private static PublisherClient publisherClient;
+ private static IntegrationClientServiceImpl instance;
+ private StoreClient storeClient;
+ private PublisherClient publisherClient;
+ private OAuthRequestInterceptor oAuthRequestInterceptor;
- public IntegrationClientServiceImpl() {
- RequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
+ private IntegrationClientServiceImpl() {
+ oAuthRequestInterceptor = new OAuthRequestInterceptor();
storeClient = new StoreClient(oAuthRequestInterceptor);
publisherClient = new PublisherClient(oAuthRequestInterceptor);
}
+
+ public static IntegrationClientServiceImpl getInstance() {
+ if (instance == null) {
+ synchronized (IntegrationClientService.class) {
+ if (instance == null) {
+ instance = new IntegrationClientServiceImpl();
+ }
+ }
+ }
+ return instance;
+ }
+
+ public void resetUserInfo(String userName, String tenantDomain) {
+ oAuthRequestInterceptor.removeToken(userName, tenantDomain);
+ }
+
@Override
public StoreClient getStoreClient() {
return storeClient;
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java
index d9afb2aa55..b4bc910686 100755
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/OAuthRequestInterceptor.java
@@ -40,6 +40,7 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
import java.util.HashMap;
import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
/**
* This is a request interceptor to add oauth token header.
@@ -55,7 +56,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000;
private DCRClient dcrClient;
private static OAuthApplication oAuthApplication;
- private static Map tenantUserTokenMap = new HashMap<>();
+ private static Map tenantUserTokenMap = new ConcurrentHashMap<>();
private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
/**
@@ -97,10 +98,14 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService()
.getJWTClient();
tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(),
- oAuthApplication.getClientSecret(), username,
- REQUIRED_SCOPE);
+ oAuthApplication.getClientSecret(), username,
+ REQUIRED_SCOPE);
tenantBasedAccessTokenInfo.setExpiresIn(
System.currentTimeMillis() + (tenantBasedAccessTokenInfo.getExpiresIn() * 1000));
+ if (tenantBasedAccessTokenInfo.getScopes() == null) {
+ throw new APIMClientOAuthException("Failed to retrieve scopes from access token");
+ }
+
if (tenantBasedAccessTokenInfo.getScopes().contains(APIM_SUBSCRIBE_SCOPE)) {
tenantUserTokenMap.put(username, tenantBasedAccessTokenInfo);
}
@@ -115,4 +120,11 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
}
}
+ public void removeToken(String username, String tenantDomain) {
+ if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+ username = username + "@" + tenantDomain;
+ }
+ tenantUserTokenMap.remove(username);
+ }
+
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java
index 8655a4d6a2..58f39f1a5b 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/configs/APIMConfigReader.java
@@ -79,6 +79,7 @@ public class APIMConfigReader {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java
index 48f92d5abd..359b4b621e 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/exception/APIMClientOAuthException.java
@@ -35,7 +35,7 @@ public class APIMClientOAuthException extends RuntimeException {
this.responseStatus = status;
}
- APIMClientOAuthException(String message) {
+ public APIMClientOAuthException(String message) {
super(message);
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java
index aaf178b718..4e09da489f 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/internal/APIIntegrationClientServiceComponent.java
@@ -49,7 +49,7 @@ public class APIIntegrationClientServiceComponent {
/* Initializing webapp publisher configuration */
APIMConfigReader.init();
BundleContext bundleContext = componentContext.getBundleContext();
- bundleContext.registerService(IntegrationClientService.class.getName(), new IntegrationClientServiceImpl(), null);
+ bundleContext.registerService(IntegrationClientService.class.getName(), IntegrationClientServiceImpl.getInstance(), null);
if (log.isDebugEnabled()) {
log.debug("apimgt client bundle has been successfully initialized");
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java
index 0ac7e4616f..a98571ef4f 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.integration.client/src/main/java/org/wso2/carbon/apimgt/integration/client/service/IntegrationClientService.java
@@ -26,6 +26,9 @@ import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
*/
public interface IntegrationClientService {
+
+ void resetUserInfo(String username, String tenantDomain);
+
/**
*
* @return API Store 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 31adc6fde5..d0c406c0ff 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.integration.generated.client
- 3.0.46-SNAPSHOT
+ 3.0.217-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 cee4587b91..7bd0d2c666 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.apimgt.webapp.publisher
- 3.0.46-SNAPSHOT
+ 3.0.217-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,29 +160,54 @@
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;
- *
+ *
+
+ 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
+
+
+
+
-
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java
index ca020bd83a..0c2334ae20 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIConfig.java
@@ -57,6 +57,7 @@ public class APIConfig {
private String tenantDomain;
private String[] tags;
private Set scopes;
+ private boolean isDefault = true;
@XmlElement(name = "Policy", required = true)
public String getPolicy() {
@@ -184,4 +185,13 @@ public class APIConfig {
public void setScopes(Set scopes) {
this.scopes = scopes;
}
+
+ @XmlElement(name = "isDefault")
+ public boolean isDefault() {
+ return isDefault;
+ }
+
+ public void setDefault(boolean aDefault) {
+ isDefault = aDefault;
+ }
}
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..4bb54d5ac1 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;
}
}
@@ -106,7 +108,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
api.setStatus(PUBLISHED_STATUS);
api.setResponseCaching("DISABLED");
api.setDestinationStatsEnabled("false");
- api.isDefaultVersion(true);
+ api.isDefaultVersion(config.isDefault());
List transport = new ArrayList<>();
transport.add("https");
transport.add("http");
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..cbb27d9f2a 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
@@ -55,6 +55,7 @@ public class APIPublisherUtil {
private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints";
private static final String AUTH_TYPE_NON_SECURED = "None";
+ private static final String PARAM_IS_DEFAULT = "isDefault";
public static String getServerBaseUrl() {
WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance();
@@ -143,6 +144,13 @@ public class APIPublisherUtil {
apiConfig.setSecured(false);
+ boolean isDefault = true;
+ String isDefaultParam = servletContext.getInitParameter(PARAM_IS_DEFAULT);
+ if (isDefaultParam != null && !isDefaultParam.isEmpty()) {
+ isDefault = Boolean.parseBoolean(isDefaultParam);
+ }
+ apiConfig.setDefault(isDefault);
+
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
@@ -276,7 +284,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/WebappPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
index 17e2edb9a8..5d9a948e59 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
@@ -35,6 +35,7 @@ public class WebappPublisherUtil {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
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 119693a8c8..059a9bc00c 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.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../../pom.xml
4.0.0
apimgt-extensions
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
pom
WSO2 Carbon - API Management Extensions Component
http://wso2.org
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/PlatformManagementAPI.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/PlatformManagementAPI.java
deleted file mode 100644
index 3a30c15e55..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/PlatformManagementAPI.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*
-* 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.application.mgt.api.services;
-
-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.SwaggerDefinition;
-import io.swagger.annotations.Tag;
-import org.apache.cxf.jaxrs.ext.multipart.Attachment;
-import org.apache.cxf.jaxrs.ext.multipart.Multipart;
-import org.wso2.carbon.apimgt.annotations.api.Scopes;
-import org.wso2.carbon.device.application.mgt.api.beans.ErrorResponse;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-
-import javax.validation.constraints.Size;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-/**
- * API for handling platform related operations in application management.
- */
-@SwaggerDefinition(
- info = @Info(
- version = "1.0.0",
- title = "Platform Management Service",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = "name", value = "PlatformManagementService"),
- @ExtensionProperty(name = "context", value = "/api/application-mgt/v1.0/platforms"),
- })
- }
- ),
- tags = {
- @Tag(name = "device_management, application_management", description = "Platform Management APIS "
- + "related with Application Management")
- }
-)
-@Scopes (
- scopes = {
- @org.wso2.carbon.apimgt.annotations.api.Scope(
- name = "Get platform details",
- description = "Get platform details",
- key = "perm:platform:get",
- permissions = {"/device-mgt/platform/get"}
- ),
- @org.wso2.carbon.apimgt.annotations.api.Scope(
- name = "Add a platform",
- description = "Add a platform",
- key = "perm:platform:add",
- permissions = {"/device-mgt/platform/add"}
- ),
- @org.wso2.carbon.apimgt.annotations.api.Scope(
- name = "Update a platform",
- description = "Update a platform",
- key = "perm:platform:update",
- permissions = {"/device-mgt/platform/update"}
- ),
- @org.wso2.carbon.apimgt.annotations.api.Scope(
- name = "Remove a platform",
- description = "Remove a platform",
- key = "perm:platform:remove",
- permissions = {"/device-mgt/platform/remove"}
- )
- }
-)
-@Api(value = "Platform Management", description = "This API carries all platform management related operations " +
- "such as get all the available platform for a tenant, etc.")
-@Path("/platforms")
-@Produces(MediaType.APPLICATION_JSON)
-public interface PlatformManagementAPI {
- String SCOPE = "scope";
-
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "get all platforms",
- notes = "This will get all platforms that is visible for tenants",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:get")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully got platforms list.",
- response = Platform.class,
- responseContainer = "List"),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform list.",
- response = ErrorResponse.class)
- })
- Response getPlatforms(
- @ApiParam(name = "status", allowableValues = "ENABLED, DISABLED, ALL", value =
- "Provide the status of platform for that tenant:\n"
- + "- ENABLED: The platforms that are currently enabled for the tenant\n"
- + "- DISABLED: The platforms that can be used by the tenant but disabled "
- + "to be used for tenant\n"
- + "- ALL: All the list of platforms that can be used by the tenant")
- @QueryParam("status")
- @Size(max = 45)
- String status,
- @ApiParam(name = "tag", defaultValue = "Tag value that we need to search the platform for")
- @QueryParam("tag") String tag
- );
-
- @GET
- @Path("/{identifier}")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "get platform",
- notes = "This will return the platform which is registered with {identifier}",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:get")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully got requested platform.",
- response = Platform.class),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform.",
- response = ErrorResponse.class)
- })
- Response getPlatform(
- @ApiParam(
- name = "identifier",
- required = true)
- @PathParam("identifier")
- @Size(max = 45)
- String identifier
- );
-
- @POST
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @ApiOperation(
- consumes = MediaType.MULTIPART_FORM_DATA,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "POST",
- value = "Add Platform",
- notes = "This will a platform for the tenant space",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:add")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully added the platform"),
- @ApiResponse(
- code = 400,
- message = "Bad Request. \n Invalid request parameters passed."),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform list.",
- response = ErrorResponse.class)
- })
- Response addPlatform(
- @Multipart(value = "Platform", type = "application/json") Platform platform,
- @Multipart(value = "icon", required = false) Attachment iconFile
- );
-
- @PUT
- @Path("/{identifier}")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "PUT",
- value = "Update Platform",
- notes = "This will update the platform configuration for the tenant space",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:update")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully updated the platform"),
- @ApiResponse(
- code = 400,
- message = "Bad Request. \n Invalid request parameters passed."),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform list.",
- response = ErrorResponse.class)
- })
- Response updatePlatform(
- @ApiParam(
- name = "platform",
- value = "The payload of the platform",
- required = true)
- Platform platform,
- @ApiParam(
- name = "identifier",
- required = true)
- @PathParam("identifier")
- @Size(max = 45)
- String identifier
- );
-
- @DELETE
- @Path("/{identifier}")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "DELETE",
- value = "Remove Platform",
- notes = "This will remove the relevant platform.",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:remove")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully deleted the platform"),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while deleting the platform.",
- response = ErrorResponse.class)
- })
- Response removePlatform(
- @ApiParam(
- name = "identifier",
- required = true)
- @PathParam("identifier")
- @Size(max = 45)
- String identifier
- );
-
- @PUT
- @Path("update-status/{identifier}")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "PUT",
- value = "Update Platform status",
- notes = "This will update the platform status for the tenant space",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:update")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully updated the platform."),
- @ApiResponse(
- code = 404,
- message = "Not found. \n Non-file based platform not found to update."),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform list.",
- response = ErrorResponse.class)
- })
- Response updatePlatformStatus(
- @ApiParam(
- name = "identifier",
- required = true)
- @PathParam("identifier")
- @Size(max = 45)
- String identifier,
- @ApiParam(name = "status", allowableValues = "ENABLED, DISABLED", value =
- "Provide the status of platform for that tenant:\n"
- + "- ENABLED: The platforms that are currently enabled for the tenant\n"
- + "- DISABLED: The platforms that currently disabled "
- + "to be used for tenant\n", required = true)
- @QueryParam("status")
- String status
- );
-
- @GET
- @Path("tags/{name}")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- @ApiOperation(
- consumes = MediaType.APPLICATION_JSON,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "get platform tags that starts with the given character sequence",
- notes = "This will get all platform tags that has the given character sequence ",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:add")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully retrieved platform tags.",
- response = Platform.class,
- responseContainer = "List"),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while getting the platform tags.",
- response = ErrorResponse.class)
- })
- Response getPlatformTags(
- @ApiParam(name = "name", value = "The initial part of the name of platform tags that we need to retrieve",
- required = true)
- @PathParam("name") @Size(min = 3) String name
- );
-
- @POST
- @Path("/{identifier}/icon")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.MULTIPART_FORM_DATA)
- @ApiOperation(
- consumes = MediaType.MULTIPART_FORM_DATA,
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "POST",
- value = "Update Platform icon",
- notes = "This will update the platform icon",
- tags = "Platform Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = SCOPE, value = "perm:platform:update")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully updated the platform icon"),
- @ApiResponse(
- code = 400,
- message = "Bad Request. \n Invalid request parameters passed."),
- @ApiResponse(
- code = 500,
- message = "Internal Server Error. \n Error occurred while updating the platform icon.",
- response = ErrorResponse.class)
- })
- Response updatePlatformIcon(
- @ApiParam(
- name = "identifier",
- required = true)
- @PathParam("identifier")
- @Size(max = 45)
- String identifier,
- @Multipart(value = "icon") Attachment iconFile
- );
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java
deleted file mode 100644
index 47743b4f72..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/ApplicationManagementAPIImpl.java
+++ /dev/null
@@ -1,593 +0,0 @@
-/*
- * 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.application.mgt.api.services.impl;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.cxf.jaxrs.ext.multipart.Attachment;
-import org.apache.cxf.jaxrs.ext.multipart.Multipart;
-import org.wso2.carbon.device.application.mgt.api.APIUtil;
-import org.wso2.carbon.device.application.mgt.api.FileStreamingOutput;
-import org.wso2.carbon.device.application.mgt.api.services.ApplicationManagementAPI;
-import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.ApplicationList;
-import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.Filter;
-import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
-import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
-import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
-import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
-import org.wso2.carbon.device.application.mgt.core.util.Constants;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import javax.validation.Valid;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-
-/**
- * Implementation of Application Management related APIs.
- */
-@Produces({"application/json"})
-@Path("/applications")
-public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
-
- private static final int DEFAULT_LIMIT = 20;
- private static Log log = LogFactory.getLog(ApplicationManagementAPIImpl.class);
-
- @GET
- @Consumes("application/json")
- public Response getApplications(@QueryParam("offset") int offset, @QueryParam("limit") int limit,
- @QueryParam("query") String searchQuery) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
-
- try {
- if (limit == 0) {
- limit = DEFAULT_LIMIT;
- }
- Filter filter = new Filter();
- filter.setOffset(offset);
- filter.setLimit(limit);
- filter.setSearchQuery(searchQuery);
-
- ApplicationList applications = applicationManager.getApplications(filter);
-
- for (Application application : applications.getApplications()) {
- ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(application.getUuid(),
- Constants.IMAGE_ARTIFACTS[0], 0);
- application.setIcon(imageArtifact);
- }
- return Response.status(Response.Status.OK).entity(applications).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while getting the application list";
- log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).build();
- } catch (ApplicationStorageManagementException e) {
- log.error("Error occurred while getting the image artifacts of the application", e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @GET
- @Consumes("application/json")
- @Path("/{uuid}")
- public Response getApplication(@PathParam("uuid") String uuid, @QueryParam("isWithImages") Boolean isWithImages) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- Application application = applicationManager.getApplication(uuid);
- if (application == null) {
- return Response.status(Response.Status.NOT_FOUND)
- .entity("Application with UUID " + uuid + " not found").build();
- }
-
- if (isWithImages != null && isWithImages) {
- ImageArtifact icon = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[0], 0);
- ImageArtifact banner = applicationStorageManager.getImageArtifact(uuid, Constants.IMAGE_ARTIFACTS[1],
- 0);
- int screenShotCount = application.getScreenShotCount();
- for (int count = 1; count < screenShotCount; count++) {
- ImageArtifact screenShot = applicationStorageManager.getImageArtifact(uuid, Constants
- .IMAGE_ARTIFACTS[2], count);
- application.addScreenShot(screenShot);
- }
- application.setIcon(icon);
- application.setBanner(banner);
- }
- return Response.status(Response.Status.OK).entity(application).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Error occurred while getting application with the uuid " + uuid, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ApplicationStorageManagementException e) {
- log.error("Error occurred while getting the image artifacts of the application with the uuid " + uuid, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @PUT
- @Consumes("application/json")
- @Path("/{uuid}/lifecycle")
- public Response changeLifecycleState(@PathParam("uuid") String applicationUUID,
- @QueryParam("state") String state) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
-
- if (!Arrays.asList(Constants.LIFE_CYCLES).contains(state)) {
- log.warn("Provided lifecycle state " + state + " is not valid. Please select one from"
- + Arrays.toString(Constants.LIFE_CYCLES));
- return Response.status(Response.Status.BAD_REQUEST)
- .entity("Provided lifecycle state " + state + " is not valid. Please select one from "
- + Arrays.toString(Constants.LIFE_CYCLES)).build();
- }
- try {
- applicationManager.changeLifecycle(applicationUUID, state);
- return Response.status(Response.Status.OK)
- .entity("Successfully changed the lifecycle state of the application: " + applicationUUID).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while changing the lifecycle of application: " + applicationUUID;
- log.error(msg, e);
- return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
- }
- }
-
- @GET
- @Path("/{uuid}/lifecycle")
- @Override
- public Response getNextLifeCycleStates(@PathParam("uuid") String applicationUUID) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- try {
- if (applicationManager.getApplication(applicationUUID) == null) {
- if (log.isDebugEnabled()) {
- log.debug("Application with the UUID '" + applicationUUID + "' is not found.");
- }
- return Response.status(Response.Status.NOT_FOUND).entity("Application with the UUID '" +
- applicationUUID + "' is not found.").build();
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Application with UUID '" + applicationUUID + "' is found. Request received for getting "
- + "next life-cycle states for the particular application.");
- }
- return Response.status(Response.Status.OK).entity(applicationManager.getLifeCycleStates(applicationUUID))
- .build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Application Management Exception while trying to get next states for the applications with "
- + "the application ID", e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @POST
- @Consumes("application/json")
- public Response createApplication(@Valid Application application) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- try {
- application = applicationManager.createApplication(application);
- return Response.status(Response.Status.OK).entity(application).build();
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while creating the application";
- log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).build();
- }
- }
-
- @Override
- @POST
- @Path("/upload-image-artifacts/{uuid}")
- public Response uploadApplicationArtifacts(@PathParam("uuid") String applicationUUID,
- @Multipart("icon") Attachment iconFile, @Multipart("banner") Attachment bannerFile,
- @Multipart("screenshot") List attachmentList) {
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- InputStream iconFileStream;
- InputStream bannerFileStream;
- List attachments = new ArrayList<>();
-
- if (iconFile != null) {
- iconFileStream = iconFile.getDataHandler().getInputStream();
- } else {
- throw new ApplicationManagementException(
- "Icon file is not uploaded for the application " + applicationUUID);
- }
- if (bannerFile != null) {
- bannerFileStream = bannerFile.getDataHandler().getInputStream();
- } else {
- throw new ApplicationManagementException(
- "Banner file is not uploaded for the application " + applicationUUID);
- }
- if (attachmentList != null && !attachmentList.isEmpty()) {
- for (Attachment screenshot : attachmentList) {
- attachments.add(screenshot.getDataHandler().getInputStream());
- }
- } else {
- throw new ApplicationManagementException(
- "Screen-shot are not uploaded for the application " + applicationUUID);
- }
- applicationStorageManager
- .uploadImageArtifacts(applicationUUID, iconFileStream, bannerFileStream, attachments);
- return Response.status(Response.Status.OK)
- .entity("Successfully uploaded artifacts for the application " + applicationUUID).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while creating the application";
- log.error(msg, e);
- return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
- } catch (IOException e) {
- log.error("Exception while trying to read icon, banner files for the application " + applicationUUID);
- return APIUtil.getResponse(new ApplicationManagementException(
- "Exception while trying to read icon, " + "banner files for the application " +
- applicationUUID, e), Response.Status.BAD_REQUEST);
- } catch (ResourceManagementException e) {
- log.error("Error occurred while uploading the image artifacts of the application with the uuid "
- + applicationUUID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @PUT
- @Path("/upload-image-artifacts/{uuid}")
- public Response updateApplicationArtifacts(@PathParam("uuid") String applicationUUID,
- @Multipart("icon") Attachment iconFile, @Multipart("banner") Attachment bannerFile,
- @Multipart("screenshot") List attachmentList) {
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- InputStream iconFileStream = null;
- InputStream bannerFileStream = null;
- List attachments = new ArrayList<>();
-
- if (iconFile != null) {
- iconFileStream = iconFile.getDataHandler().getInputStream();
- }
- if (bannerFile != null) {
- bannerFileStream = bannerFile.getDataHandler().getInputStream();
- }
- if (attachmentList != null) {
- for (Attachment screenshot : attachmentList) {
- attachments.add(screenshot.getDataHandler().getInputStream());
- }
- }
- applicationStorageManager
- .uploadImageArtifacts(applicationUUID, iconFileStream, bannerFileStream, attachments);
- return Response.status(Response.Status.OK)
- .entity("Successfully updated artifacts for the application " + applicationUUID).build();
- } catch (IOException e) {
- log.error("Exception while trying to read icon, banner files for the application " + applicationUUID);
- return APIUtil.getResponse(new ApplicationManagementException(
- "Exception while trying to read icon, banner files for the application " +
- applicationUUID, e), Response.Status.BAD_REQUEST);
- } catch (ResourceManagementException e) {
- log.error("Error occurred while uploading the image artifacts of the application with the uuid "
- + applicationUUID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @PUT
- @Consumes("application/json")
- public Response editApplication(@Valid Application application) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- try {
- application = applicationManager.editApplication(application);
- } catch (NotFoundException e) {
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while creating the application";
- log.error(msg, e);
- return APIUtil.getResponse(e, Response.Status.BAD_REQUEST);
- }
- return Response.status(Response.Status.OK).entity(application).build();
- }
-
- @DELETE
- @Path("/{appuuid}")
- public Response deleteApplication(@PathParam("appuuid") String uuid) {
- ApplicationManager applicationManager = APIUtil.getApplicationManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- try {
- applicationReleaseManager.deleteApplicationReleases(uuid);
- applicationStorageManager.deleteApplicationArtifacts(uuid);
- applicationManager.deleteApplication(uuid);
- String responseMsg = "Successfully deleted the application: " + uuid;
- return Response.status(Response.Status.OK).entity(responseMsg).build();
- } catch (NotFoundException e) {
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- } catch (ApplicationManagementException e) {
- String msg = "Error occurred while deleting the application: " + uuid;
- log.error(msg, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ApplicationStorageManagementException e) {
- log.error("Error occurred while deleteing the image artifacts of the application with the uuid " + uuid, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @POST
- @Path("/release/{uuid}")
- public Response createApplicationRelease(@PathParam("uuid") String applicationUUID,
- @Multipart("applicationRelease") ApplicationRelease applicationRelease,
- @Multipart("binaryFile") Attachment binaryFile) {
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- applicationRelease = applicationReleaseManager.createRelease(applicationUUID, applicationRelease);
-
- if (binaryFile != null) {
- applicationStorageManager.uploadReleaseArtifacts(applicationUUID, applicationRelease.getVersionName(),
- binaryFile.getDataHandler().getInputStream());
- }
- return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
- } catch (ApplicationManagementException e) {
- log.error("Error while creating an application release for the application with UUID " + applicationUUID,
- e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (IOException e) {
- String errorMessage =
- "Error while uploading binary file for the application release of the application with UUID "
- + applicationUUID;
- log.error(errorMessage, e);
- return APIUtil.getResponse(new ApplicationManagementException(errorMessage, e),
- Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ResourceManagementException e) {
- log.error("Error occurred while uploading the releases artifacts of the application with the uuid "
- + applicationUUID + " for the release " + applicationRelease.getVersionName(), e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @PUT
- @Path("/release/{uuid}")
- public Response updateApplicationRelease(@PathParam("uuid") String applicationUUID, @Multipart
- ("applicationRelease") ApplicationRelease applicationRelease, @Multipart("binaryFile") Attachment
- binaryFile) {
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- if (applicationRelease != null) {
- applicationRelease = applicationReleaseManager.updateRelease(applicationUUID, applicationRelease);
- }
- if (binaryFile != null) {
- String version = applicationRelease == null ? null : applicationRelease.getVersionName();
-
- if (version == null) {
- return Response.status(Response.Status.BAD_REQUEST).entity("Version cannot be null. Version is a "
- + "mandatory parameter to update the release artifacts").build();
- }
- applicationStorageManager
- .uploadReleaseArtifacts(applicationUUID, version, binaryFile.getDataHandler().getInputStream());
- }
- return Response.status(Response.Status.OK).entity(applicationRelease).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Error while updating the application release of the application with UUID " + applicationUUID);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (IOException e) {
- log.error("Error while updating the release artifacts of the application with UUID " + applicationUUID);
- return APIUtil.getResponse(new ApplicationManagementException(
- "Error while updating the release artifacts of the application with UUID "
- + applicationUUID), Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ResourceManagementException e) {
- log.error("Error occurred while updating the releases artifacts of the application with the uuid "
- + applicationUUID + " for the release " + applicationRelease.getVersionName(), e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @GET
- @Produces(MediaType.APPLICATION_OCTET_STREAM)
- @Path("/release-artifacts/{uuid}/{version}")
- public Response getApplicationReleaseArtifacts(@PathParam("uuid") String applicationUUID,
- @PathParam("version") String version) {
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- InputStream binaryFile = applicationStorageManager.getReleasedArtifacts(applicationUUID, version);
- FileStreamingOutput fileStreamingOutput = new FileStreamingOutput(binaryFile);
- Response.ResponseBuilder response = Response.status(Response.Status.OK).entity(fileStreamingOutput);
- response.header("Content-Disposition", "attachment; filename=\"" + version + "\"");
- return response.build();
- } catch (ApplicationStorageManagementException e) {
- log.error("Error while retrieving the binary file of the application release for the application UUID " +
- applicationUUID + " and version " + version, e);
- if (e.getMessage().contains("Binary file does not exist")) {
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- } else {
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
- }
-
- @Override
- @Path("/release/{uuid}")
- @GET
- public Response getApplicationReleases(@PathParam("uuid") String applicationUUID,
- @QueryParam("version") String version) {
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- try {
- if (version == null || version.isEmpty()) {
- List applicationReleases = applicationReleaseManager.getReleases(applicationUUID);
- return Response.status(Response.Status.OK).entity(applicationReleases).build();
- } else {
- ApplicationRelease applicationRelease = applicationReleaseManager.getRelease(applicationUUID, version);
- return Response.status(Response.Status.OK).entity(applicationRelease).build();
- }
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Error while getting all the application releases for the application with the UUID "
- + applicationUUID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @DELETE
- @Path("/release/{uuid}")
- public Response deleteApplicationRelease(@PathParam("uuid") String applicationUUID,
- @QueryParam("version") String version) {
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- if (version != null && !version.isEmpty()) {
- applicationStorageManager.deleteApplicationReleaseArtifacts(applicationUUID, version);
- applicationReleaseManager.deleteApplicationRelease(applicationUUID, version);
- return Response.status(Response.Status.OK)
- .entity("Successfully deleted Application release with " + "version " + version
- + " for the application with UUID " + applicationUUID).build();
- } else {
- applicationStorageManager.deleteAllApplicationReleaseArtifacts(applicationUUID);
- applicationReleaseManager.deleteApplicationReleases(applicationUUID);
- return Response.status(Response.Status.OK)
- .entity("Successfully deleted Application releases for the " + "application with UUID "
- + applicationUUID).build();
- }
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Error while deleting application release with the application UUID " + applicationUUID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ApplicationStorageManagementException e) {
- log.error("Error occurred while deleting the releases artifacts of the application with the uuid "
- + applicationUUID + " for the release " + version, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @GET
- @Path("/image-artifacts/{uuid}")
- @Produces(MediaType.APPLICATION_JSON)
- public Response getApplicationImageArtifacts(@PathParam("uuid") String applicationUUID,
- @QueryParam("name") String name, @QueryParam("count") int count) {
- if (name == null || name.isEmpty()) {
- return Response.status(Response.Status.BAD_REQUEST).entity("Name should not be null. Name is mandatory to"
- + " retrieve the particular image artifact of the release").build();
- }
- ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
- try {
- ImageArtifact imageArtifact = applicationStorageManager.getImageArtifact(applicationUUID, name, count);
- Response.ResponseBuilder response = Response.status(Response.Status.OK).entity(imageArtifact);
- return response.build();
- } catch (ApplicationStorageManagementException e) {
- log.error("Application Storage Management Exception while getting the image artifact " + name + " of "
- + "the application with UUID " + applicationUUID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @PUT
- @Consumes("application/json")
- @Path("/{uuid}/{version}/{channel}")
- public Response updateDefaultVersion(@PathParam("uuid") String applicationUUID, @PathParam("version") String
- version, @PathParam("channel") String channel, @QueryParam("isDefault") boolean isDefault) {
- ApplicationReleaseManager applicationReleaseManager = APIUtil.getApplicationReleaseManager();
- try {
- applicationReleaseManager.changeDefaultRelease(applicationUUID, version, isDefault, channel);
- return Response.status(Response.Status.OK)
- .entity("Successfully changed the default version for the " + "release channel " + channel
- + " for the application UUID " + applicationUUID).build();
- } catch (NotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).build();
- } catch (ApplicationManagementException e) {
- log.error("Application Release Management Exception while changing the default release for the release "
- + "channel " + channel + " for the application with UUID " + applicationUUID + " for the version "
- + version);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @POST
- @Path("/category")
- public Response createCategory(@Valid Category category) {
- if (category == null) {
- return Response.status(Response.Status.BAD_REQUEST).entity("Category is null. cannot create the "
- + "category").build();
- }
- try {
- Category createdCategory = APIUtil.getCategoryManager().createCategory(category);
- return Response.status(Response.Status.CREATED).entity(createdCategory).build();
- } catch (ApplicationManagementException e) {
- log.error("Application Management Exception while trying to create the application category", e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @GET
- @Path("/category")
- public Response getCategories() {
- List categories;
- try {
- categories = APIUtil.getCategoryManager().getCategories();
- return Response.status(Response.Status.OK).entity(categories).build();
- } catch (ApplicationManagementException e) {
- log.error("Application Management Exception while trying to get application categories", e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @Override
- @DELETE
- @Path("/category/{name}")
- public Response deleteCategory(@PathParam("name") String name) {
- if (name == null || name.isEmpty()) {
- return Response.status(Response.Status.BAD_REQUEST).entity("Name cannot be null or empty.").build();
- }
- try {
- APIUtil.getCategoryManager().deleteCategory(name);
- return Response.status(Response.Status.OK).entity("Successfully deleted the category.").build();
- } catch (ApplicationManagementException e) {
- log.error("Application Management Exception while trying to delete category", e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/LifecycleManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/LifecycleManagementAPIImpl.java
deleted file mode 100644
index 985c0b7bb8..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/LifecycleManagementAPIImpl.java
+++ /dev/null
@@ -1,85 +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.application.mgt.api.services.impl;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.device.application.mgt.api.APIUtil;
-import org.wso2.carbon.device.application.mgt.api.services.LifecycleManagementAPI;
-import org.wso2.carbon.device.application.mgt.common.LifecycleState;
-import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
-
-import java.util.ArrayList;
-import java.util.List;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.core.Response;
-
-/**
- * Lifecycle Management related jax-rs APIs.
- */
-@Path("/lifecycles")
-public class LifecycleManagementAPIImpl implements LifecycleManagementAPI {
-
- private static Log log = LogFactory.getLog(LifecycleManagementAPIImpl.class);
-
- @GET
- public Response getLifecycleStates() {
- LifecycleStateManager lifecycleStateManager = APIUtil.getLifecycleStateManager();
- List lifecycleStates = new ArrayList<>();
- try {
- lifecycleStates = lifecycleStateManager.getLifecycleStates();
- } catch (LifecycleManagementException e) {
- String msg = "Error occurred while retrieving lifecycle states.";
- log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).build();
- }
- return Response.status(Response.Status.OK).entity(lifecycleStates).build();
- }
-
- @POST
- public Response addLifecycleState(LifecycleState state) {
- LifecycleStateManager lifecycleStateManager = APIUtil.getLifecycleStateManager();
- try {
- lifecycleStateManager.addLifecycleState(state);
- } catch (LifecycleManagementException e) {
- String msg = "Error occurred while adding lifecycle state.";
- log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).build();
- }
- return Response.status(Response.Status.OK).entity("Lifecycle state added successfully.").build();
- }
-
- @DELETE
- @Path("/{identifier}")
- public Response deleteLifecycleState(@PathParam("identifier") String identifier) {
- LifecycleStateManager lifecycleStateManager = APIUtil.getLifecycleStateManager();
- try {
- lifecycleStateManager.deleteLifecycleState(identifier);
- } catch (LifecycleManagementException e) {
- String msg = "Error occurred while deleting lifecycle state.";
- log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).build();
- }
- return Response.status(Response.Status.OK).entity("Lifecycle state deleted successfully.").build();
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/PlatformManagementAPIImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/PlatformManagementAPIImpl.java
deleted file mode 100644
index 32984446e0..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/src/main/java/org/wso2/carbon/device/application/mgt/api/services/impl/PlatformManagementAPIImpl.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
-* 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.application.mgt.api.services.impl;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.cxf.jaxrs.ext.multipart.Attachment;
-import org.apache.cxf.jaxrs.ext.multipart.Multipart;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.device.application.mgt.api.APIUtil;
-import org.wso2.carbon.device.application.mgt.api.services.PlatformManagementAPI;
-import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
-import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import javax.validation.constraints.Size;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Response;
-
-/**
- * Implementation of PlatformManagement APIs.
- */
-@Path("/platforms")
-public class PlatformManagementAPIImpl implements PlatformManagementAPI {
-
- private static final String ALL_STATUS = "ALL";
- private static final String ENABLED_STATUS = "ENABLED";
- private static final String DISABLED_STATUS = "DISABLED";
-
- private static Log log = LogFactory.getLog(PlatformManagementAPIImpl.class);
-
- @GET
- @Override
- public Response getPlatforms(@QueryParam("status") String status, @QueryParam("tag") String tag) {
- int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- PlatformStorageManager platformStorageManager = APIUtil.getPlatformStorageManager();
-
- if (log.isDebugEnabled()) {
- log.debug("API request received for getting the platforms with the status " + status);
- }
- try {
- List platforms = APIUtil.getPlatformManager().getPlatforms(tenantID);
- List results;
- List filteredPlatforms = new ArrayList<>();
- if (status != null) {
- if (status.contentEquals(ALL_STATUS)) {
- results = platforms;
- } else if (status.contentEquals(ENABLED_STATUS)) {
- results = new ArrayList<>();
- for (Platform platform : platforms) {
- if (platform.isEnabled()) {
- results.add(platform);
- }
- }
- } else if (status.contentEquals(DISABLED_STATUS)) {
- results = new ArrayList<>();
- for (Platform platform : platforms) {
- if (!platform.isEnabled()) {
- results.add(platform);
- }
- }
- } else {
- results = platforms;
- }
- } else {
- results = platforms;
- }
- if (results != null) {
- for (Platform platform : results) {
- if (tag == null || tag.isEmpty() || (platform.getTags() != null && platform.getTags()
- .contains(tag))) {
- platform.setIcon(platformStorageManager.getIcon(platform.getIdentifier()));
- filteredPlatforms.add(platform);
- }
- }
- if (log.isDebugEnabled()) {
- log.debug("Number of platforms with the status " + status + " : " + results.size());
- }
- }
- return Response.status(Response.Status.OK).entity(filteredPlatforms).build();
- } catch (PlatformManagementException e) {
- log.error("Error while getting the platforms for tenant - " + tenantID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (PlatformStorageManagementException e) {
- log.error("Error while getting platform icons for the tenant : " + tenantID, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @GET
- @Override
- @Path("/{identifier}")
- public Response getPlatform(@PathParam("identifier") String id) {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- try {
- Platform platform = APIUtil.getPlatformManager().getPlatform(tenantId, id);
-
- if (platform == null) {
- return Response.status(Response.Status.NOT_FOUND).entity("Platform not found").build();
- }
- ImageArtifact icon = APIUtil.getPlatformStorageManager().getIcon(id);
- if (icon != null) {
- platform.setIcon(icon);
- }
- return Response.status(Response.Status.OK).entity(platform).build();
- } catch (PlatformManagementDAOException e) {
- log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
- + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (PlatformManagementException e) {
- log.error("Error while trying the get the platform with the identifier : " + id + " for the tenant :"
- + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- } catch (PlatformStorageManagementException e) {
- log.error("Platform Storage Management Exception while trying to get the icon for the platform : " + id
- + " for the tenant : " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- }
- }
-
- @POST
- @Override
- public Response addPlatform(@Multipart("platform") Platform platform, @Multipart("icon")Attachment icon) {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- try {
- if (platform != null) {
- if (platform.validate()) {
- APIUtil.getPlatformManager().register(tenantId, platform);
-
- if (icon != null) {
- InputStream iconFileStream = icon.getDataHandler().getInputStream();
- APIUtil.getPlatformStorageManager().uploadIcon(platform.getIdentifier(), iconFileStream);
- }
- return Response.status(Response.Status.CREATED).build();
- } else {
- return APIUtil
- .getResponse("Invalid payload! Platform 'identifier' and 'name' are mandatory fields!",
- Response.Status.BAD_REQUEST);
- }
- } else {
- return APIUtil.getResponse("Invalid payload! Platform needs to be passed as payload!",
- Response.Status.BAD_REQUEST);
- }
- } catch (PlatformManagementException e) {
- log.error("Platform Management Exception while trying to add the platform with identifier : " + platform
- .getIdentifier() + " for the tenant : " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (IOException e) {
- log.error("IO Exception while trying to save platform icon for the platform : " + platform.getIdentifier(),
- e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (ResourceManagementException e) {
- log.error("Storage Exception while trying to save platform icon for the platform : " + platform
- .getIdentifier(), e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @PUT
- @Path("/{identifier}")
- @Override
- public Response updatePlatform(Platform platform, @PathParam("identifier") @Size(max = 45) String id) {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- try {
- APIUtil.getPlatformManager().update(tenantId, id, platform);
- return Response.status(Response.Status.OK).build();
- } catch (PlatformManagementException e) {
- log.error("Error while updating the platform - " + id + " for tenant domain - " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @DELETE
- @Path("/{identifier}")
- @Override
- public Response removePlatform(@PathParam("identifier") @Size(max = 45) String id) {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- try {
- APIUtil.getPlatformStorageManager().deleteIcon(id);
- APIUtil.getPlatformManager().unregister(tenantId, id, false);
- return Response.status(Response.Status.OK).build();
- } catch (PlatformManagementException e) {
- log.error(
- "Platform Management Exception while trying to un-register the platform with the identifier : " + id
- + " for the tenant : " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (PlatformStorageManagementException e) {
- log.error("Platform Storage Management Exception while trying to delete the icon of the platform with "
- + "identifier for the tenant :" + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @PUT
- @Path("update-status/{identifier}")
- @Override
- public Response updatePlatformStatus(@PathParam("identifier") @Size(max = 45) String id, @QueryParam("status")
- String status) {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- try {
- APIUtil.getPlatformManager().updatePlatformStatus(tenantId, id, status);
- return Response.status(Response.Status.OK).build();
- } catch (PlatformManagementDAOException e) {
- log.error("Platform Management Database Exception while trying to update the status of the platform with "
- + "the identifier : " + id + " for the tenant : " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (PlatformManagementException e) {
- log.error("Platform Management Exception while trying to update the status of the platform with the "
- + "identifier : " + id + " for the tenant : " + tenantId, e);
- return APIUtil.getResponse(e, Response.Status.NOT_FOUND);
- }
- }
-
- @GET
- @Path("tags/{name}")
- @Override
- public Response getPlatformTags(@PathParam("name") String name) {
- if (name == null || name.isEmpty() || name.length() < 3) {
- return APIUtil.getResponse("In order to get platform tags, it is required to pass the first 3 "
- + "characters of the platform tag name", Response.Status.INTERNAL_SERVER_ERROR);
- }
- try {
- List platformTags = APIUtil.getPlatformManager().getPlatformTags(name);
- return Response.status(Response.Status.OK).entity(platformTags).build();
- } catch (PlatformManagementException e) {
- log.error("Platform Management Exception while trying to get the platform tags with starting character "
- + "sequence " + name, e);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-
- @POST
- @Path("{identifier}/icon")
- @Override
- public Response updatePlatformIcon(@PathParam("identifier") String identifier, @Multipart("icon") Attachment
- icon) {
- try {
- if (icon != null) {
- InputStream iconFileStream = icon.getDataHandler().getInputStream();
- APIUtil.getPlatformStorageManager().uploadIcon(identifier, iconFileStream);
- return Response.status(Response.Status.OK)
- .entity("Icon file is successfully updated for the platform :" + identifier).build();
- } else {
- return Response.status(Response.Status.BAD_REQUEST).entity("Icon file is not provided to update")
- .build();
- }
- } catch (ResourceManagementException e) {
- log.error("Resource Management exception while trying to update the icon for the platform " + identifier);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- } catch (IOException e) {
- log.error("IO exception while trying to update the icon for the platform " + identifier);
- return APIUtil.getResponse(e, Response.Status.INTERNAL_SERVER_ERROR);
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.authhandler/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.authhandler/pom.xml
index 7dfdd93df4..a963743d1a 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.authhandler/pom.xml
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.authhandler/pom.xml
@@ -24,11 +24,11 @@
org.wso2.carbon.devicemgt
application-mgt
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
org.wso2.carbon.device.application.mgt.authhandler
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
war
WSO2 Carbon - Application Management Authentication Handler API
Proxy Service for Authentication Handling in WSO2 App Manager.
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml
index 4493c59c69..da6c8bc20f 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/pom.xml
@@ -21,13 +21,13 @@
org.wso2.carbon.devicemgt
application-mgt
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.device.application.mgt.common
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
bundle
WSO2 Carbon - Application Management Common
WSO2 Carbon - Application Management Common
@@ -56,6 +56,8 @@
org.apache.commons.logging,
javax.xml.*,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
+ org.wso2.carbon.device.mgt.core.dto.*;version="${carbon.device.mgt.version}",
+ org.wso2.carbon.device.mgt.core.dao.*;version="${carbon.device.mgt.version}",
org.w3c.dom,
org.json,
org.xml.sax,
@@ -108,6 +110,10 @@
com.google.code.gson
gson
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.device.mgt.core
+
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Application.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Application.java
index 427bceee25..590633c250 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Application.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Application.java
@@ -20,11 +20,8 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
-
-import java.util.ArrayList;
-import java.util.Date;
+import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.util.List;
-import java.util.Map;
/**
* Application represents the an Application in Application Store.
@@ -34,184 +31,60 @@ public class Application {
@Exclude
private int id;
- private String uuid;
-
private String name;
- private String shortDescription;
+ private String appCategory;
- private String description;
+ private String type;
- private String videoName;
+ private int isFree;
- private List tags;
+ private String paymentCurrency;
- private Platform platform;
-
- private List comments;
-
- private Category category;
-
- private Map properties;
-
- private Date createdAt;
-
- private Date modifiedAt;
-
- private Payment payment;
-
- private Lifecycle currentLifecycle;
-
- private List releases;
-
- private Visibility visibility;
-
- private int screenShotCount;
+ private List tags;
private User user;
- private ImageArtifact icon;
+ private List unrestrictedRoles;
- private ImageArtifact banner;
+ private int isRestricted;
- private List screenShots = new ArrayList<>();
+ private List applicationReleases;
+
+// private ApplicationRelease releaseVersion;
+
+ private DeviceType devicetype;
public int getId() {
return id;
}
- public List getReleases() {
- return releases;
- }
-
- public void setReleases(List releases) {
- this.releases = releases;
- }
-
- public List getComments() {
- return comments;
- }
-
- public void setComments(List comments) {
- this.comments = comments;
- }
-
- public Payment getPayment() {
- return payment;
- }
-
- public void setPayment(Payment payment) {
- this.payment = payment;
- }
-
- public Lifecycle getCurrentLifecycle() {
- return currentLifecycle;
- }
-
- public void setCurrentLifecycle(Lifecycle currentLifecycle) {
- this.currentLifecycle = currentLifecycle;
- }
-
public void setId(int id) {
this.id = id;
}
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
public String getName() {
return name;
}
- public void setName(String name) {
- this.name = name;
+ public void setName(String name) { this.name = name; }
+
+ public String getAppCategory() {
+ return appCategory;
}
- public String getShortDescription() {
- return shortDescription;
+ public void setAppCategory(String appCategory) {
+ this.appCategory = appCategory;
}
- public void setShortDescription(String shortDescription) {
- this.shortDescription = shortDescription;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getVideoName() {
- return videoName;
- }
-
- public void setVideoName(String videoName) {
- this.videoName = videoName;
- }
-
- public List getTags() {
+ public List getTags() {
return tags;
}
- public void setTags(List tags) {
+ public void setTags(List tags) {
this.tags = tags;
}
- public Platform getPlatform() {
- return platform;
- }
-
- public void setPlatform(Platform platform) {
- this.platform = platform;
- }
-
- public Category getCategory() {
- return category;
- }
-
- public void setCategory(Category category) {
- this.category = category;
- }
-
- public Map getProperties() {
- return properties;
- }
-
- public void setProperties(Map properties) {
- this.properties = properties;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
-
- public Date getModifiedAt() {
- return modifiedAt;
- }
-
- public void setModifiedAt(Date modifiedAt) {
- this.modifiedAt = modifiedAt;
- }
-
- public Visibility getVisibility() {
- return visibility;
- }
-
- public void setVisibility(Visibility visibility) {
- this.visibility = visibility;
- }
-
public User getUser() {
return user;
}
@@ -220,33 +93,87 @@ public class Application {
this.user = user;
}
- public void setScreenShotCount(int screenShotCount) {
- this.screenShotCount = screenShotCount;
+ public String uuidOfLatestRelease;
+
+ public ImageArtifact iconOfLatestRelease;
+
+ public List getUnrestrictedRoles() {
+ return unrestrictedRoles;
}
- public int getScreenShotCount() {
- return screenShotCount;
+ public void setUnrestrictedRoles(List unrestrictedRoles) {
+ this.unrestrictedRoles = unrestrictedRoles;
}
- public void setIcon(ImageArtifact icon) {
- this.icon = icon;
+// public ApplicationRelease getReleaseVersion() {
+// return releaseVersion;
+// }
+//
+// public void setReleaseVersion(ApplicationRelease releaseVersion) {
+// this.releaseVersion = releaseVersion;
+// }
+
+ public String getType() {
+ return type;
}
- public void setBanner(ImageArtifact banner) {
- this.banner = banner;
+ public void setType(String type) {
+ this.type = type;
}
- public void addScreenShot(ImageArtifact screenShot) {
- this.screenShots.add(screenShot);
+ public int getIsFree() {
+ return isFree;
}
- @Override
- public String toString() {
- String app = "UUID : " + uuid + "\tName : " + name + "\tShort Description : "
- + shortDescription;
- if (currentLifecycle != null) {
- app += "\tLifecycle State : " + currentLifecycle.getLifecycleState();
- }
- return app;
+ public void setIsFree(int isFree) {
+ this.isFree = isFree;
+ }
+
+ public String getPaymentCurrency() {
+ return paymentCurrency;
+ }
+
+ public void setPaymentCurrency(String paymentCurrency) {
+ this.paymentCurrency = paymentCurrency;
+ }
+
+ public int getIsRestricted() {
+ return isRestricted;
+ }
+
+ public void setIsRestricted(int isRestricted) {
+ this.isRestricted = isRestricted;
+ }
+
+ public DeviceType getDevicetype() {
+ return devicetype;
+ }
+
+ public void setDevicetype(DeviceType devicetype) {
+ this.devicetype = devicetype;
+ }
+
+ public String getUuidOfLatestRelease() {
+ return uuidOfLatestRelease;
+ }
+
+ public void setUuidOfLatestRelease(String uuidOfLatestRelease) {
+ this.uuidOfLatestRelease = uuidOfLatestRelease;
+ }
+
+ public ImageArtifact getIconOfLatestRelease() {
+ return iconOfLatestRelease;
+ }
+
+ public void setIconOfLatestRelease(ImageArtifact iconOfLatestRelease) {
+ this.iconOfLatestRelease = iconOfLatestRelease;
+ }
+
+ public List getApplicationReleases() {
+ return applicationReleases;
+ }
+
+ public void setApplicationReleases(List applicationReleases) {
+ this.applicationReleases = applicationReleases;
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java
index 48215fb121..61ddb449da 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/ApplicationRelease.java
@@ -20,38 +20,65 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
-import java.util.Date;
-import java.util.Map;
+import java.sql.Timestamp;
+import java.util.ArrayList;
+import java.util.List;
/**
* This class holds the details when releasing an Application to application store.
*/
public class ApplicationRelease {
- private enum Channel {
- PRODUCTION, ALPHA, BETA
- }
-
@Exclude
private int id;
- private int versionId;
+ private String version;
- private String versionName;
+ private String tenantId;
- private String resource;
+ private String uuid;
- private Channel releaseChannel;
+ private String appStoredLoc;
- private String releaseDetails;
+ private String bannerLoc;
- private Date createdAt;
+ private String screenshotLoc1;
- private Application application;
+ private String screenshotLoc2;
- private Map properties;
+ private String screenshotLoc3;
- private boolean isDefault;
+ private String applicationCreator;
+
+ private String releaseType;
+
+ private Double price;
+
+ private Timestamp createdAt;
+
+ private String publishedBy;
+
+ private Timestamp publishedAt;
+
+ private String modifiedBy;
+
+ private Timestamp modifiedAt;
+
+ private String iconLoc;
+
+ private String currentState;
+
+ private String previousState;
+
+ private String stateModifiedBy;
+
+ private Timestamp stateModifiedAt;
+
+ private String appHashValue;
+
+ private int isSharedWithAllTenants;
+
+ private String metaData;
private int noOfRatedUsers;
@@ -73,75 +100,199 @@ public class ApplicationRelease {
this.stars = stars;
}
- public int getId() {
- return id;
- }
-
public void setId(int id) {
this.id = id;
}
- public String getVersionName() {
- return versionName;
+ public void setVersion(String version) {
+ this.version = version;
}
- public void setVersionName(String versionName) {
- this.versionName = versionName;
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
}
- public String getResource() {
- return resource;
+ public String getUuid() {
+ return uuid;
}
- public void setResource(String resource) {
- this.resource = resource;
+ public void setUuid(String uuid) {
+ this.uuid = uuid;
}
- public Channel getReleaseChannel() {
- return releaseChannel;
+ public String getReleaseType() {
+ return releaseType;
}
- public void setReleaseChannel(String releaseChannel) {
- this.releaseChannel = Channel.valueOf(releaseChannel);
+ public void setReleaseType(String releaseType) {
+ this.releaseType = releaseType;
}
- public String getReleaseDetails() {
- return releaseDetails;
+ public void setAppHashValue(String appHashValue) {
+ this.appHashValue = appHashValue;
}
- public void setReleaseDetails(String releaseDetails) {
- this.releaseDetails = releaseDetails;
+ public void setIsSharedWithAllTenants(int isSharedWithAllTenants) { this.isSharedWithAllTenants = isSharedWithAllTenants; }
+
+ public void setMetaData(String metaData) {
+ this.metaData = metaData;
}
- public Date getCreatedAt() {
+ public int getId() { return id; }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public Double getPrice() {
+ return price;
+ }
+
+ public void setPrice(Double price) {
+ this.price = price;
+ }
+
+ public String getCurrentState() {
+ return currentState;
+ }
+
+ public void setCurrentState(String currentState) {
+ this.currentState = currentState;
+ }
+
+ public String getPreviousState() {
+ return previousState;
+ }
+
+ public void setPreviousState(String previousState) {
+ this.previousState = previousState;
+ }
+
+ public String getStateModifiedBy() {
+ return stateModifiedBy;
+ }
+
+ public void setStateModifiedBy(String stateModifiedBy) {
+ this.stateModifiedBy = stateModifiedBy;
+ }
+
+ public Timestamp getStateModifiedAt() {
+ return stateModifiedAt;
+ }
+
+ public void setStateModifiedAt(Timestamp stateModifiedAt) {
+ this.stateModifiedAt = stateModifiedAt;
+ }
+
+ public String getAppHashValue() {
+ return appHashValue;
+ }
+
+ public int getIsSharedWithAllTenants() {
+ return isSharedWithAllTenants;
+ }
+
+ public String getMetaData() {
+ return metaData;
+ }
+
+ public String getAppStoredLoc() {
+ return appStoredLoc;
+ }
+
+ public void setAppStoredLoc(String appStoredLoc) {
+ this.appStoredLoc = appStoredLoc;
+ }
+
+ public String getBannerLoc() {
+ return bannerLoc;
+ }
+
+ public void setBannerLoc(String bannerLoc) {
+ this.bannerLoc = bannerLoc;
+ }
+
+ public String getScreenshotLoc1() {
+ return screenshotLoc1;
+ }
+
+ public void setScreenshotLoc1(String screenshotLoc1) {
+ this.screenshotLoc1 = screenshotLoc1;
+ }
+
+ public String getScreenshotLoc2() {
+ return screenshotLoc2;
+ }
+
+ public void setScreenshotLoc2(String screenshotLoc2) {
+ this.screenshotLoc2 = screenshotLoc2;
+ }
+
+ public String getScreenshotLoc3() {
+ return screenshotLoc3;
+ }
+
+ public void setScreenshotLoc3(String screenshotLoc3) {
+ this.screenshotLoc3 = screenshotLoc3;
+ }
+
+ public String getApplicationCreator() {
+ return applicationCreator;
+ }
+
+ public void setApplicationCreator(String applicationCreator) {
+ this.applicationCreator = applicationCreator;
+ }
+
+ public Timestamp getCreatedAt() {
return createdAt;
}
- public void setCreatedAt(Date createdAt) {
+ public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
- public Application getApplication() {
- return application;
+ public String getPublishedBy() {
+ return publishedBy;
}
- public void setApplication(Application application) {
- this.application = application;
+ public void setPublishedBy(String publishedBy) {
+ this.publishedBy = publishedBy;
}
- public Map getProperties() {
- return properties;
+ public Timestamp getPublishedAt() {
+ return publishedAt;
}
- public void setProperties(Map properties) {
- this.properties = properties;
+ public void setPublishedAt(Timestamp publishedAt) {
+ this.publishedAt = publishedAt;
}
- public boolean isDefault() {
- return isDefault;
+ public String getModifiedBy() {
+ return modifiedBy;
}
- public void setDefault(boolean aDefault) {
- isDefault = aDefault;
+ public void setModifiedBy(String modifiedBy) {
+ this.modifiedBy = modifiedBy;
+ }
+
+ public Timestamp getModifiedAt() {
+ return modifiedAt;
+ }
+
+ public void setModifiedAt(Timestamp modifiedAt) {
+ this.modifiedAt = modifiedAt;
+ }
+
+ public String getIconLoc() {
+ return iconLoc;
+ }
+
+ public void setIconLoc(String iconLoc) {
+ this.iconLoc = iconLoc;
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Lifecycle.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Lifecycle.java
index bf365e8488..4e071787b2 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Lifecycle.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Lifecycle.java
@@ -18,39 +18,120 @@
package org.wso2.carbon.device.application.mgt.common;
import java.util.Date;
+import java.util.List;
/**
* Represents an lifecycle of an {@link Application}.
*/
public class Lifecycle {
- private LifecycleState lifecycleState;
+ private int id;
- private Date lifecycleStateModifiedAt;
+ private Date createdAt;
- private String getLifecycleStateModifiedBy;
+ private String createdBy;
- public LifecycleState getLifecycleState() {
- return lifecycleState;
+ private int isApproved;
+
+ private String approvedBy;
+
+ private Date approvedAt;
+
+ private int isPublished;
+
+ private String publishedBy;
+
+ private Date publishedAt;
+
+ private int isRetired;
+
+ private List lifecycleStateTransition;
+
+ public int getId() {
+ return id;
}
- public void setLifecycleState(LifecycleState lifecycleState) {
- this.lifecycleState = lifecycleState;
+ public void setId(int id) {
+ this.id = id;
}
- public Date getLifecycleStateModifiedAt() {
- return lifecycleStateModifiedAt;
+ public Date getCreatedAt() {
+ return createdAt;
}
- public void setLifecycleStateModifiedAt(Date lifecycleStateModifiedAt) {
- this.lifecycleStateModifiedAt = lifecycleStateModifiedAt;
+ public void setCreatedAt(Date createdAt) {
+ this.createdAt = createdAt;
}
- public String getGetLifecycleStateModifiedBy() {
- return getLifecycleStateModifiedBy;
+ public String getCreatedBy() {
+ return createdBy;
}
- public void setGetLifecycleStateModifiedBy(String getLifecycleStateModifiedBy) {
- this.getLifecycleStateModifiedBy = getLifecycleStateModifiedBy;
+ public void setCreatedBy(String createdBy) {
+ this.createdBy = createdBy;
+ }
+
+ public int getIsApproved() {
+ return isApproved;
+ }
+
+ public void setIsApproved(int isApproved) {
+ this.isApproved = isApproved;
+ }
+
+ public String getApprovedBy() {
+ return approvedBy;
+ }
+
+ public void setApprovedBy(String approvedBy) {
+ this.approvedBy = approvedBy;
+ }
+
+ public Date getApprovedAt() {
+ return approvedAt;
+ }
+
+ public void setApprovedAt(Date approvedAt) {
+ this.approvedAt = approvedAt;
+ }
+
+ public int getIsPublished() {
+ return isPublished;
+ }
+
+ public void setIsPublished(int isPublished) {
+ this.isPublished = isPublished;
+ }
+
+ public String getPublishedBy() {
+ return publishedBy;
+ }
+
+ public void setPublishedBy(String publishedBy) {
+ this.publishedBy = publishedBy;
+ }
+
+ public Date getPublishedAt() {
+ return publishedAt;
+ }
+
+ public void setPublishedAt(Date publishedAt) {
+ this.publishedAt = publishedAt;
+ }
+
+ public int getIsRetired() {
+ return isRetired;
+ }
+
+ public void setIsRetired(int isRetired) {
+ this.isRetired = isRetired;
+ }
+
+ public List getLifecycleStateTransition() {
+ return lifecycleStateTransition;
+ }
+
+ public void setLifecycleStateTransition(List lifecycleStateTransition) {
+ this.lifecycleStateTransition = lifecycleStateTransition;
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java
index 337ca3bbe1..e62de0b0d9 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/LifecycleState.java
@@ -18,18 +18,25 @@
*/
package org.wso2.carbon.device.application.mgt.common;
-/**
- * Represents a state in {@link Lifecycle}.
- */
+import java.sql.Timestamp;
+
public class LifecycleState {
private int id;
- private String name;
+ private String currentState;
- private String identifier;
+ private String previousState;
- private String description;
+ private String updatedBy;
+
+ private Timestamp updatedAt;
+
+ private int tenantId;
+
+ private int releaseId;
+
+ private int appId;
public int getId() {
return id;
@@ -39,27 +46,60 @@ public class LifecycleState {
this.id = id;
}
- public String getName() {
- return name;
+ public String getCurrentState() {
+ return currentState;
}
- public void setName(String name) {
- this.name = name;
+ public void setCurrentState(String currentState) {
+ this.currentState = currentState;
}
- public String getIdentifier() {
- return identifier;
+ public String getPreviousState() {
+ return previousState;
}
- public void setIdentifier(String identifier) {
- this.identifier = identifier;
+ public void setPreviousState(String previousState) {
+ this.previousState = previousState;
}
- public String getDescription() {
- return description;
+ public String getUpdatedBy() {
+ return updatedBy;
}
- public void setDescription(String description) {
- this.description = description;
+ public void setUpdatedBy(String updatedBy) {
+ this.updatedBy = updatedBy;
}
+
+ public Timestamp getUpdatedAt() {
+ return updatedAt;
+ }
+
+ public void setUpdatedAt(Timestamp updatedAt) {
+ this.updatedAt = updatedAt;
+ }
+
+ public int getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(int tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public int getReleaseId() {
+ return releaseId;
+ }
+
+ public void setReleaseId(int releaseId) {
+ this.releaseId = releaseId;
+ }
+
+ public int getAppId() {
+ return appId;
+ }
+
+ public void setAppId(int appId) {
+ this.appId = appId;
+ }
+
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Platform.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Platform.java
deleted file mode 100644
index cf85852df0..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Platform.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * 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.application.mgt.common;
-
-import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents the platform of an {@link Application}.
- */
-public class Platform {
-
- /**
- * Unique id reference that is used in the database.
- */
- @Exclude
- private int id;
-
- /**
- * The name of the platform. It can contain spaces,etc.
- */
- private String name;
-
- private String description;
-
- /**
- * Unique human readable identifier used for the platform.
- */
- private String identifier;
-
- private String iconName;
-
- private boolean fileBased;
-
- private boolean shared;
-
- private List tags;
-
- private List properties;
-
- private boolean enabled;
-
- private boolean defaultTenantMapping;
-
- private ImageArtifact icon;
-
- public Platform(Platform platform) {
- this.id = platform.getId();
- this.name = platform.getName();
- this.description = platform.getDescription();
- this.identifier = platform.getIdentifier();
- this.iconName = platform.getIconName();
- this.fileBased = platform.isFileBased();
- this.shared = platform.isShared();
- this.enabled = platform.isEnabled();
- this.defaultTenantMapping = platform.isDefaultTenantMapping();
- if (platform.getProperties() != null) {
- this.properties = new ArrayList<>();
- for (Property property : platform.getProperties()) {
- this.properties.add(new Property(property));
- }
- }
- if (platform.getTags() != null) {
- this.tags = new ArrayList<>();
- for (String tag : platform.getTags()) {
- this.tags.add(tag);
- }
- }
- }
-
- public Platform() {
-
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getIdentifier() {
- return identifier;
- }
-
- public void setIdentifier(String identifier) {
- this.identifier = identifier;
- }
-
- public String getIconName() {
- return iconName;
- }
-
- public void setIconName(String iconName) {
- this.iconName = iconName;
- }
-
- public List getProperties() {
- return properties;
- }
-
- public void setProperties(List properties) {
- this.properties = properties;
- }
-
- public List getTags() {
- return tags;
- }
-
- public void setTags(List tags) {
- this.tags = tags;
- }
-
- public boolean isFileBased() {
- return fileBased;
- }
-
- public void setFileBased(boolean fileBased) {
- this.fileBased = fileBased;
- }
-
- public boolean isShared() {
- return shared;
- }
-
- public void setShared(boolean shared) {
- this.shared = shared;
- }
-
- public boolean isEnabled() {
- return enabled;
- }
-
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- public boolean isDefaultTenantMapping() {
- return defaultTenantMapping;
- }
-
- public void setDefaultTenantMapping(boolean defaultTenantMapping) {
- this.defaultTenantMapping = defaultTenantMapping;
- }
-
- public boolean validate() {
- return !(name == null || identifier == null);
- }
-
- public void setIcon(ImageArtifact icon) {
- this.icon = icon;
- }
-
- /**
- * Represents a property of a {@link Platform}.
- */
- public static class Property implements Cloneable {
-
- private String name;
- private boolean optional;
- private String defaultValue;
-
- public Property(Property property) {
- this.name = property.getName();
- this.optional = property.isOptional();
- this.defaultValue = property.getDefaultValue();
- }
-
- public Property() {
-
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public boolean isOptional() {
- return optional;
- }
-
- public void setOptional(boolean optional) {
- this.optional = optional;
- }
-
- public String getDefaultValue() {
- return defaultValue;
- }
-
- public void setDefaultValue(String defaultValue) {
- this.defaultValue = defaultValue;
- }
-
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Tag.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Tag.java
new file mode 100644
index 0000000000..a3815b6f9c
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/Tag.java
@@ -0,0 +1,72 @@
+/*
+ *
+ * Copyright (c) ${date}, 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.application.mgt.common;
+
+
+import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
+
+import java.util.Date;
+
+/**
+ * Application represents the an Application in Application Store.
+ */
+public class Tag {
+
+ @Exclude
+ private int id;
+
+ private String tenantId;
+
+ private String tagName;
+
+ private Application application;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public String getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(String tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTagName() {
+ return tagName;
+ }
+
+ public void setTagName(String tagName) {
+ this.tagName = tagName;
+ }
+
+ public Application getApplication() {
+ return application;
+ }
+
+ public void setApplication(Application application) {
+ this.application = application;
+ }
+}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/UnrestrictedRole.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/UnrestrictedRole.java
new file mode 100644
index 0000000000..5171648ece
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/UnrestrictedRole.java
@@ -0,0 +1,60 @@
+/*
+ *
+ * Copyright (c) ${date}, 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.application.mgt.common;
+
+
+import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
+
+/**
+ * Application represents the an Application in Application Store.
+ */
+public class UnrestrictedRole {
+
+ @Exclude
+ private int id;
+
+ private int tenantId;
+
+ private String role;
+
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
+ public int getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(int tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getRole() {
+ return role;
+ }
+
+ public void setRole(String role) {
+ this.role = role;
+ }
+}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/PlatformManagementException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/PlatformManagementException.java
deleted file mode 100644
index de76af02e0..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/exception/PlatformManagementException.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
-* 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.application.mgt.common.exception;
-
-/**
- * Exception caused during the platform management.
- */
-public class PlatformManagementException extends ApplicationManagementException {
-
- public PlatformManagementException(String message, Throwable ex) {
- super(message, ex);
- }
-
- public PlatformManagementException(String message) {
- super(message);
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java
index 7fd542e1d7..6994ae608f 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationManager.java
@@ -18,11 +18,9 @@
*/
package org.wso2.carbon.device.application.mgt.common.services;
-import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.ApplicationList;
-import org.wso2.carbon.device.application.mgt.common.Filter;
-import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
+import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
+import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import java.util.List;
@@ -62,6 +60,15 @@ public interface ApplicationManager {
*/
ApplicationList getApplications(Filter filter) throws ApplicationManagementException;
+ /**
+ * To get the applications based on the search filter.
+ * @param appId id of the application
+ * @return Application release which is published and release of the Application(appId).
+ * @throws ApplicationManagementException Application Management Exception
+ */
+ String getUuidOfLatestRelease(int appId) throws ApplicationManagementException;
+
+
/**
* To change the lifecycle of the Application.
*
@@ -85,9 +92,48 @@ public interface ApplicationManager {
/**
* To get Application with the given UUID.
*
- * @param uuid UUID of the Application
+ * @param appType type of the Application
+ * @param appName name of the Application
* @return the Application identified by the UUID
* @throws ApplicationManagementException Application Management Exception.
*/
- Application getApplication(String uuid) throws ApplicationManagementException;
+ Application getApplication(String appType, String appName) throws ApplicationManagementException;
+
+ /**
+ * To get Application with the given UUID.
+ *
+ * @param applicationId Id of the Application
+ * @return the Application identified by the application id
+ * @throws ApplicationManagementException Application Management Exception.
+ */
+ Application getApplicationById(int applicationId) throws ApplicationManagementException;
+
+
+ /**
+ * To get Application with the given UUID.
+ *
+ * @param appId ID of the Application
+ * @return the boolean value, whether application exist or not
+ * @throws ApplicationManagementException Application Management Exception.
+ */
+ Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException;
+
+ /**
+ * To get Application with the given UUID.
+ *
+ * @return the boolean value, whether user has assigned unrestricted roles to access the application
+ * * @throws ApplicationManagementException Application Management Exception.
+ */
+ Boolean isUserAllowable(List unrestrictedRoles, String userName) throws ApplicationManagementException;
+
+ /**
+ * To get all the releases of a particular Application.
+ *
+ * @param applicationId ID of the Application to get all the releases.
+ * @return the List of the Application releases related with the particular Application.
+ * @throws ApplicationManagementException Application Management Exception.
+ */
+ List getReleases(int applicationId) throws ApplicationManagementException;
+
+
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationReleaseManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationReleaseManager.java
index 2f5231d671..9f181dacf6 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationReleaseManager.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationReleaseManager.java
@@ -33,11 +33,11 @@ public interface ApplicationReleaseManager {
/**
* To create an application release for an Application.
*
- * @param appicationUuid UUID of the Application
+ * @param applicationId ID of the Application
* @param applicationRelease ApplicatonRelease that need to be be created.
* @return the unique id of the application release, if the application release succeeded else -1
*/
- ApplicationRelease createRelease(String appicationUuid, ApplicationRelease applicationRelease)
+ ApplicationRelease createRelease(int applicationId, ApplicationRelease applicationRelease)
throws ApplicationManagementException;
/**
@@ -45,19 +45,29 @@ public interface ApplicationReleaseManager {
*
* @param applicationUuid UUID of the Application.
* @param version Version of the ApplicationRelease that need to be retrieved.
+ * @param releaseType Release type of the app release. (e.g: alpha, beta, default, released)
* @return ApplicationRelease related with particular Application UUID and version.
* @throws ApplicationManagementException ApplicationManagementException
*/
- ApplicationRelease getRelease(String applicationUuid, String version) throws ApplicationManagementException;
+ ApplicationRelease getRelease(String applicationUuid, String version, String releaseType) throws ApplicationManagementException;
+
+ /**
+ * To get the application release of the Application/
+ *
+ * @param applicationUuid UUID of the Application.
+ * @return ApplicationRelease related with particular Application UUID and version.
+ * @throws ApplicationManagementException ApplicationManagementException
+ */
+ ApplicationRelease getReleaseByUuid(String applicationUuid) throws ApplicationManagementException;
/**
* To get all the releases of a particular Application.
*
- * @param applicationUuid UUID of the Application to get all the releases.
+ * @param applicationId ID of the Application to get all the releases.
* @return the List of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception.
*/
- List getReleases(String applicationUuid) throws ApplicationManagementException;
+ List getReleases(int applicationId) throws ApplicationManagementException;
/**
* To make a particular application release as the default / not default-one
@@ -74,12 +84,12 @@ public interface ApplicationReleaseManager {
/**
* To update with a new release for an Application.
*
- * @param applicationUuid UUID of the Application
+ * @param appId ID of the Application
* @param applicationRelease ApplicationRelease
* @return Updated Application Release.
* @throws ApplicationManagementException Application Management Exception.
*/
- ApplicationRelease updateRelease(String applicationUuid, ApplicationRelease applicationRelease)
+ ApplicationRelease updateRelease(int appId, ApplicationRelease applicationRelease)
throws ApplicationManagementException;
/**
@@ -87,9 +97,10 @@ public interface ApplicationReleaseManager {
*
* @param applicationUuid UUID of the Application, in which the ApplicationRelease need to be deleted.
* @param version Version of the ApplicationRelease that need to be deleted.
+ * @param releaseType Release type of the application.
* @throws ApplicationManagementException Application Management Exception.
*/
- void deleteApplicationRelease(String applicationUuid, String version) throws ApplicationManagementException;
+ void deleteApplicationRelease(String applicationUuid, String version, String releaseType) throws ApplicationManagementException;
/**
* To delete all the application releases related with the the particular application.
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java
index e6f60f6bf5..7745836875 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/ApplicationStorageManager.java
@@ -19,7 +19,9 @@
package org.wso2.carbon.device.application.mgt.common.services;
+import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
+import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
@@ -33,23 +35,47 @@ public interface ApplicationStorageManager {
/**
* To upload image artifacts related with an Application.
*
- * @param applicationUUID UUID of the application
+ * @param applicationRelease ApplicationRelease Object
* @param iconFile Icon File input stream
* @param bannerFile Banner File input stream
* @throws ResourceManagementException Resource Management Exception.
*/
- void uploadImageArtifacts(String applicationUUID, InputStream iconFile, InputStream bannerFile,
- List screenshots) throws ResourceManagementException;
+ ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease,
+ InputStream iconFile, InputStream bannerFile, List screenshots) throws ResourceManagementException;
+
+ /**
+ * To upload image artifacts related with an Application.
+ *
+ * @param applicationId ID of the application
+ * @param uuid Unique Identifier of the application
+ * @param iconFile Icon File input stream
+ * @param bannerFile Banner File input stream
+ * @param screenshots Input Streams of screenshots
+ * @throws ResourceManagementException Resource Management Exception.
+ */
+ ApplicationRelease updateImageArtifacts(int applicationId, String uuid, InputStream iconFile,
+ InputStream bannerFile, List screenshots)
+ throws ResourceManagementException, ApplicationManagementException;
/**
* To upload release artifacts for an Application.
*
- * @param applicationUUID UUID of the application related with the release.
- * @param versionName Name of version of the Applcation Release.
+ * @param applicationRelease Application Release Object.
* @param binaryFile Binary File for the release.
* @throws ResourceManagementException Resource Management Exception.
*/
- void uploadReleaseArtifacts(String applicationUUID, String versionName, InputStream binaryFile)
+ ApplicationRelease uploadReleaseArtifacts(ApplicationRelease applicationRelease, InputStream binaryFile)
+ throws ResourceManagementException;
+
+ /**
+ * To upload release artifacts for an Application.
+ *
+ * @param applicationId Id of the application.
+ * @param applicationUuid UUID of the application related with the release.
+ * @param binaryFile Binary File for the release.
+ * @throws ResourceManagementException Resource Management Exception.
+ */
+ ApplicationRelease updateReleaseArtifacts(int applicationId, String applicationUuid, InputStream binaryFile)
throws ResourceManagementException;
/**
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CategoryManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CategoryManager.java
deleted file mode 100644
index 4bc3d66289..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/CategoryManager.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.application.mgt.common.services;
-
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
-
-import java.util.List;
-
-/**
- * CategoryManager is responsible for handling add, delete, update opertaions related with {@link Category}
- */
-public interface CategoryManager {
-
- /**
- * To create an application category.
- *
- * @param category Category that need to be created.
- * @return the created Category.
- * @throws ApplicationManagementException Application Management Exception
- */
- Category createCategory(Category category) throws ApplicationManagementException;
-
- /**
- * To get all the current categories.
- *
- * @return list of Application categories.
- * @throws ApplicationManagementException Application Management Exception.
- */
- List getCategories() throws ApplicationManagementException;
-
- /**
- * To get the category with the given name.
- *
- * @param name Name of the category to retrieve.
- * @return the category with the given name.
- * @throws ApplicationManagementException Application Management Exception.
- */
- Category getCategory(String name) throws ApplicationManagementException;
-
- /**
- * To delete the category with the given name.
- *
- * @param name Name of the category to be deleted.
- * @throws ApplicationManagementException Application Management Exception.
- */
- void deleteCategory(String name) throws ApplicationManagementException;
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/LifecycleStateManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/LifecycleStateManager.java
index 82238a716a..0e2e8a5c54 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/LifecycleStateManager.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/LifecycleStateManager.java
@@ -28,9 +28,9 @@ import java.util.List;
*/
public interface LifecycleStateManager {
- List getLifecycleStates() throws LifecycleManagementException;
+ List getLifecycleStates(int appReleaseId) throws LifecycleManagementException;
void addLifecycleState(LifecycleState state) throws LifecycleManagementException;
- void deleteLifecycleState(String identifier) throws LifecycleManagementException;
+ void deleteLifecycleState(int identifier) throws LifecycleManagementException;
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformManager.java
deleted file mode 100644
index ab7babb5b0..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformManager.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * 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.application.mgt.common.services;
-
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-
-import java.util.List;
-
-/**
- * Platform manager is responsible for handling platforms, which will be used to as a registry of platforms.
- * And will be able to provide the platforms related information to other classes which requires.
- */
-public interface PlatformManager {
-
- /**
- * To initialize the shared platforms for the tenant during the tenant initialization time.
- *
- * @param tenantId ID of the tenant
- * @throws PlatformManagementException Platform Management Exception
- */
- void initialize(int tenantId) throws PlatformManagementException;
-
- /**
- * To get platforms of the specific tenant.
- *
- * @param tenantId ID of the tenant
- * @return List of platforms
- * @throws PlatformManagementException Platform Management Exception
- */
- List getPlatforms(int tenantId) throws PlatformManagementException;
-
- /**
- * To get platform with the given platform identifier and tenant ID.
- *
- * @param tenantId ID of the tenant
- * @param platformIdentifier Unique identifier of the platform.
- * @return the Specific platform with the platform identifier and tenant
- * @throws PlatformManagementException Platform Management Exception
- */
- Platform getPlatform(int tenantId, String platformIdentifier) throws PlatformManagementException;
-
- /**
- * To register a platform under particular tenant.
- *
- * @param tenantId ID of the tenant.
- * @param platform Platform to be registered
- * @throws PlatformManagementException Platform Management Exception
- */
- void register(int tenantId, Platform platform) throws PlatformManagementException;
-
- /**
- * To update a platform.
- *
- * @param tenantId ID of the tenant
- * @param oldPlatformIdentifier Old platform Identifier
- * @param platform Platform to be updated
- * @throws PlatformManagementException Platform Management Exception
- */
- void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws PlatformManagementException;
-
- /**
- * To un-register the platform.
- *
- * @param tenantId ID of the tenant.
- * @param platformIdentifier ID of the platform
- * @param isFileBased To indicate whether a file based or not.
- * @throws PlatformManagementException Platform Management Exception.
- */
- void unregister(int tenantId, String platformIdentifier, boolean isFileBased) throws PlatformManagementException;
-
- /**
- * To add mapping to platform identifiers with the tenant ID.
- *
- * @param tenantId ID of the tenant
- * @param platformIdentifiers Platform Identifiers
- * @throws PlatformManagementException Platform Management Exception
- */
- void addMapping(int tenantId, List platformIdentifiers) throws PlatformManagementException;
-
- /**
- * To add mapping to a platform for a tenant.
- *
- * @param tenantId ID of the tenant.
- * @param platformIdentifier ID of the platform, the mapping should be added.
- * @throws PlatformManagementException Platform Management Exception.
- */
- void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
-
- /**
- * To remove a mapping of a platform to a tenant.
- *
- * @param tenantId ID of the tenant.
- * @param platformIdentifier ID of the platform.
- * @throws PlatformManagementException Platform Management Exception.
- */
- void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException;
-
- /**
- * To update the platform status(ENABLED / DISABLED).
- *
- * @param tenantId Id of the tenant
- * @param platformIdentifier ID of the platform
- * @param status Status to be updated.
- * @throws PlatformManagementException Platform Management Exception.
- */
- void updatePlatformStatus(int tenantId, String platformIdentifier, String status)
- throws PlatformManagementException;
-
- /**
- * To remove platforms that belongs to particular tenant.
- *
- * @param tenantId ID of the tenant.
- * @throws PlatformManagementException Platform Management Exception.
- */
- void removePlatforms(int tenantId) throws PlatformManagementException;
-
- /**
- * To get the platform tags.
- *
- * @param name Starting character sequence of the platform name.
- * @return list of the platform tags that start with the character sequence.
- * @throws PlatformManagementException PlatformManagement Exception
- */
- List getPlatformTags(String name) throws PlatformManagementException;
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformStorageManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformStorageManager.java
deleted file mode 100644
index 3777086cc5..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/PlatformStorageManager.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.application.mgt.common.services;
-
-import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
-
-import java.io.InputStream;
-
-/**
- * This class manages all the storage related requirements of Platform.
- */
-public interface PlatformStorageManager {
- /**
- * To upload image artifacts related with an Application.
- *
- * @param platformIdentifier Identifier of the platform
- * @param iconFile Icon File input stream
- * @throws ResourceManagementException Resource Management Exception.
- */
- void uploadIcon(String platformIdentifier, InputStream iconFile) throws ResourceManagementException;
-
- /**
- * To get the icon for a particular platform.
- *
- * @param platformIdentifier Identifier of the platform.
- * @return the icon for the given platform.
- * @throws PlatformStorageManagementException Platform Storage Management Exception.
- */
- ImageArtifact getIcon(String platformIdentifier) throws PlatformStorageManagementException;
-
- /**
- * To delete the icon of a particular platform
- *
- * @param platformIdentifier Identifier of the platform to which delete icon.
- * @throws PlatformStorageManagementException PlatformStorageManagement Exception.
- */
- void deleteIcon(String platformIdentifier) throws PlatformStorageManagementException;
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/VisibilityManager.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/UnrestrictedRoleManager.java
similarity index 87%
rename from components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/VisibilityManager.java
rename to components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/UnrestrictedRoleManager.java
index 7a760854a4..93b7b3a0c9 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/VisibilityManager.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.common/src/main/java/org/wso2/carbon/device/application/mgt/common/services/UnrestrictedRoleManager.java
@@ -18,15 +18,18 @@
package org.wso2.carbon.device.application.mgt.common.services;
+import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
import org.wso2.carbon.device.application.mgt.common.Visibility;
import org.wso2.carbon.device.application.mgt.common.exception.VisibilityManagementException;
+import java.util.List;
+
/**
* This interface manages all the operations related with Application Visibility.
* This will be invoking the necessary backend calls for the data bases layer
* and provide the functional implementation.
*/
-public interface VisibilityManager {
+public interface UnrestrictedRoleManager {
/**
* Add (if there is no visibility configuration for the application) or
@@ -42,9 +45,10 @@ public interface VisibilityManager {
* Returns the Visibility configuration of the provided applicationUUID.
*
* @param applicationID The ID of the application
+ * @param tenantId tenant Id
* @return Visibility configuration
*/
- Visibility get(int applicationID) throws VisibilityManagementException;
+ List getUnrestrictedRoles(int applicationID, int tenantId) throws VisibilityManagementException;
/**
* Remove the visibility configuration mapping for the provided application.
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml
index b1a17af986..31014dc167 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/pom.xml
@@ -21,13 +21,13 @@
org.wso2.carbon.devicemgt
application-mgt
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
org.wso2.carbon.device.application.mgt.core
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
bundle
WSO2 Carbon - Application Management Core
WSO2 Carbon - Application Management Core
@@ -78,7 +78,10 @@
org.wso2.carbon,
org.apache.commons.io,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
- org.wso2.carbon.base
+ org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}",
+ org.wso2.carbon.base,
+ org.wso2.carbon.device.mgt.core.dto.*;version="${carbon.device.mgt.version}",
+ org.wso2.carbon.device.mgt.core.dao.*;version="${carbon.device.mgt.version}"
!org.wso2.carbon.device.application.mgt.core.internal.*,
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java
index 1e4874dd6f..b34d178dea 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationDAO.java
@@ -18,12 +18,9 @@
*/
package org.wso2.carbon.device.application.mgt.core.dao;
-import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.ApplicationList;
-import org.wso2.carbon.device.application.mgt.common.Filter;
-import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
+import org.wso2.carbon.device.application.mgt.common.*;
+import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-
import java.util.List;
/**
@@ -38,7 +35,25 @@ public interface ApplicationDAO {
* @return Created Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- Application createApplication(Application application) throws ApplicationManagementDAOException;
+ int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException;
+
+ /**
+ * To add tags for a particular application.
+ *
+ * @param tags tags that need to be added for a application.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
+ void addTags(List tags, int applicationId, int tenantId) throws ApplicationManagementDAOException;
+
+ /**
+ * To check application existence.
+ *
+ * @param appName appName that need to identify application.
+ * @param type type that need to identify application.
+ * @param tenantId tenantId that need to identify application.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
+ int isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException;
/**
* To get the applications that satisfy the given criteria.
@@ -50,26 +65,54 @@ public interface ApplicationDAO {
*/
ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException;
+ /**
+ * To get the UUID of latest app release that satisfy the given criteria.
+ *
+ * @param appId application id
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
+ String getUuidOfLatestRelease(int appId) throws ApplicationManagementDAOException;
+
/**
* To get the application with the given uuid
*
- * @param uuid UUID of the application to be retrieved.
+ * @param appName name of the application to be retrieved.
* @param tenantId ID of the tenant.
- * @param userName Name of the user.
+ * @param appType Type of the application.
* @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- Application getApplication(String uuid, int tenantId, String userName) throws ApplicationManagementDAOException;
+ Application getApplication(String appName, String appType, int tenantId) throws ApplicationManagementDAOException;
+
+ /**
+ * To get the application with the given uuid
+ *
+ * @param applicationId Id of the application to be retrieved.
+ * @param tenantId ID of the tenant.
+ * @return the application
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
+ Application getApplicationById(int applicationId, int tenantId) throws ApplicationManagementDAOException;
+
+ /**
+ * To get the application with the given uuid
+ *
+ * @param appId ID of the application
+ * @return the boolean value
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
+ Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementDAOException;
/**
* To get the application id of the application specified by the UUID
*
- * @param uuid UUID of the application.
+ * @param appName name of the application.
+ * @param appType type of the application.
* @param tenantId ID of the tenant.
* @return ID of the Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- int getApplicationId(String uuid, int tenantId) throws ApplicationManagementDAOException;
+ int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException;
/**
* To edit the given application.
@@ -79,16 +122,16 @@ public interface ApplicationDAO {
* @return Updated Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException;
+ Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException,
+ ApplicationManagementException;
/**
- * To delete the application identified by the UUID
+ * To delete the application
*
- * @param uuid UUID of the application.
- * @param tenantId ID of tenant which the Application belongs to.
+ * @param appId ID of the application.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- void deleteApplication(String uuid, int tenantId) throws ApplicationManagementDAOException;
+ void deleteApplication(int appId) throws ApplicationManagementDAOException;
/**
* To get the application count that satisfies gives search query.
@@ -99,13 +142,6 @@ public interface ApplicationDAO {
*/
int getApplicationCount(Filter filter) throws ApplicationManagementDAOException;
- /**
- * To delete the properties of a application.
- *
- * @param applicationId ID of the application to delete the properties.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void deleteProperties(int applicationId) throws ApplicationManagementDAOException;
/**
* To delete the tags of a application.
@@ -114,47 +150,5 @@ public interface ApplicationDAO {
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
void deleteTags(int applicationId) throws ApplicationManagementDAOException;
-
- /**
- * To change the lifecycle state of the application.
- *
- * @param applicationUUID UUID of the application.
- * @param lifecycleIdentifier New lifecycle state.
- * @param username Name of the user.
- * @param tenantId ID of the tenant.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String username, int tenantId)
- throws ApplicationManagementDAOException;
-
- /**
- * To get the next possible lifecycle states for the application.
- *
- * @param applicationUUID UUID of the application.
- * @param tenantId ID of the tenant.
- * @return Next possible lifecycle states.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- List getNextLifeCycleStates(String applicationUUID, int tenantId)
- throws ApplicationManagementDAOException;
-
- /**
- * To update the screen-shot count of a application.
- *
- * @param applicationUUID UUID of the application.
- * @param tenantId ID of the tenant.
- * @param count New count of the screen-shots.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void updateScreenShotCount(String applicationUUID, int tenantId, int count)
- throws ApplicationManagementDAOException;
-
- /**
- * To check whether atleast one application exist under category.
- *
- * @param categoryName Name of the category.
- * @return true if atleast one application exist under the given category, otherwise false.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- boolean isApplicationExist(String categoryName) throws ApplicationManagementDAOException;
}
+
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java
index 2fce310266..a77e238dd5 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/ApplicationReleaseDAO.java
@@ -35,27 +35,34 @@ public interface ApplicationReleaseDAO {
* @return Unique ID of the relevant release.
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws
+ ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException;
/**
* To get a release details with the particular version.
- * @param applicationUuid UUID of the application to get the release.
+ * @param applicationName name of the application to get the release.
* @param versionName Name of the version
+ * @param applicationType Type of the application release
+ * @param releaseType type of the release
+ * @param tenantId tenantId of the application
+
* @return ApplicationRelease for the particular version of the given application
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- ApplicationRelease getRelease(String applicationUuid, String versionName, int tenantId) throws
+ ApplicationRelease getRelease(String applicationName,String applicationType, String versionName,
+ String releaseType, int tenantId) throws
ApplicationManagementDAOException;
/**
* To get all the releases of a particular application.
*
- * @param applicationUUID Application UUID
+ * @param applicationName Name of the Application
+ * @param applicationType Type of the Application
+ * @param tenantId tenant id of the application
* @return list of the application releases
* @throws ApplicationManagementDAOException Application Management DAO Exception.
*/
- List getApplicationReleases(String applicationUUID, int tenantId) throws
+ List getApplicationReleases(String applicationName, String applicationType, int tenantId) throws
ApplicationManagementDAOException;
/**
@@ -66,6 +73,15 @@ public interface ApplicationReleaseDAO {
*/
ApplicationRelease updateRelease(ApplicationRelease applicationRelease) throws ApplicationManagementDAOException;
+ /**
+ * To update an Application release.
+ * @param id id of the ApplicationRelease that need to be updated.
+ * @param stars given stars for the application.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception
+ */
+ void updateStars(int id, int stars) throws ApplicationManagementDAOException;
+
+
/**
* To delete a particular release.
*
@@ -75,23 +91,4 @@ public interface ApplicationReleaseDAO {
*/
void deleteRelease(int id, String version) throws ApplicationManagementDAOException;
- /**
- * To delete the propertied of a particular Application Release.
- *
- * @param id ID of the ApplicationRelease in which properties need to be deleted.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void deleteReleaseProperties(int id) throws ApplicationManagementDAOException;
-
- /**
- * To change the default version of a particular release channel.
- * @param uuid UUID of the application
- * @param version Version of the application
- * @param isDefault true if the request is to make the application as default one unless false
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void changeReleaseDefault(String uuid, String version, boolean isDefault, String releaseChannel, int tenantId)
- throws ApplicationManagementDAOException;
-
-
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CategoryDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CategoryDAO.java
deleted file mode 100644
index d003552af3..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/CategoryDAO.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * 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.application.mgt.core.dao;
-
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-
-import java.util.List;
-
-/**
- * This is responsible for Application Category related DAO operations.
- */
-public interface CategoryDAO {
-
- /**
- * To add a new category.
- *
- * @param category Category that need to be added.
- * @return Newly added category.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- Category addCategory(Category category) throws ApplicationManagementDAOException;
-
- /**
- * To get the existing categories.
- *
- * @return Existing categories.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- List getCategories() throws ApplicationManagementDAOException;
-
- /**
- * To get the category with the given name.
- *
- * @param name Name of the Application category.
- * @return Application Category.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- Category getCategory(String name) throws ApplicationManagementDAOException;
-
- /**
- * To delete a particular category.
- *
- * @param name Name of the category that need to be deleted.
- * @throws ApplicationManagementDAOException Application Management DAO Exception.
- */
- void deleteCategory(String name) throws ApplicationManagementDAOException;
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/LifecycleStateDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/LifecycleStateDAO.java
index b408621582..bc5ca76903 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/LifecycleStateDAO.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/LifecycleStateDAO.java
@@ -20,7 +20,7 @@ package org.wso2.carbon.device.application.mgt.core.dao;
import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
+import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.util.List;
@@ -29,12 +29,12 @@ import java.util.List;
*/
public interface LifecycleStateDAO {
- LifecycleState getLifeCycleStateByIdentifier(String identifier) throws ApplicationManagementDAOException;
+ LifecycleState getLatestLifeCycleStateByReleaseID(int identifier) throws ApplicationManagementDAOException;
- List getLifecycleStates() throws DAOException;
+ List getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException;
- void addLifecycleState(LifecycleState state) throws DAOException;
+ void addLifecycleState(LifecycleState state) throws LifeCycleManagementDAOException;
- void deleteLifecycleState(String identifier) throws DAOException;
+ void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException;
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/PlatformDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/PlatformDAO.java
deleted file mode 100644
index 05baa7fe6d..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/PlatformDAO.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.application.mgt.core.dao;
-
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
-
-import java.util.List;
-
-/**
- * PlatformDAO defines set of DAO operations that are needed for Platform Management.
- */
-public interface PlatformDAO {
-
- int register(int tenantId, Platform platform) throws PlatformManagementDAOException;
-
- void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws PlatformManagementDAOException;
-
- void unregister(int tenantId, String platformIdentifier, boolean isFileBased) throws PlatformManagementDAOException;
-
- void addMapping(int tenantId, List platformIdentifiers) throws PlatformManagementDAOException;
-
- void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
-
- void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException;
-
- List getPlatforms(int tenantId) throws PlatformManagementDAOException;
-
- Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException;
-
- Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException;
-
- void removePlatforms(int tenantId) throws PlatformManagementDAOException;
-
- int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId) throws PlatformManagementDAOException;
-
- Platform getTenantOwnedPlatform(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
-
- int getMultiTenantPlatforms(String identifier) throws PlatformManagementDAOException;
-
- List getPlatformTags(String name) throws PlatformManagementDAOException;
-
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/VisibilityDAO.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/VisibilityDAO.java
index c1c6a1fd30..5ad5ceecec 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/VisibilityDAO.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/VisibilityDAO.java
@@ -18,7 +18,7 @@
*/
package org.wso2.carbon.device.application.mgt.core.dao;
-import org.wso2.carbon.device.application.mgt.common.Visibility;
+import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
import org.wso2.carbon.device.application.mgt.core.exception.VisibilityManagementDAOException;
import java.util.List;
@@ -30,13 +30,18 @@ import java.util.List;
*/
public interface VisibilityDAO {
- int getVisibilityID(Visibility.Type visibilityType) throws VisibilityManagementDAOException;
+ /**
+ * To add unrestricted roles for a particular application.
+ *
+ * @param unrestrictedRoles unrestrictedRoles that could available the application.
+ * @throws VisibilityManagementDAOException Visiblity Management DAO Exception.
+ */
+ void addUnrestrictedRoles(List unrestrictedRoles, int applicationId, int tenantId) throws
+ VisibilityManagementDAOException;
- void add(int applicationID, int visibilityTypeID, List allowedList)
- throws VisibilityManagementDAOException;
+ List getUnrestrictedRoles(int applicationId, int tenantId) throws VisibilityManagementDAOException;
- void delete(int applicationId) throws VisibilityManagementDAOException;
-
- Visibility get(int applicationID) throws VisibilityManagementDAOException;
+ void deleteUnrestrictedRoles(List unrestrictedRoles, int applicationId, int tenantId) throws
+ VisibilityManagementDAOException;
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java
index 2e37423458..287f9b12f8 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/ApplicationManagementDAOFactory.java
@@ -34,16 +34,12 @@ import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManageme
import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
-import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.device.mgt.core.dao.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
-import javax.sql.DataSource;
import java.sql.SQLException;
-import static org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil.resolveDataSource;
-
/**
* This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so
* that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of
@@ -53,30 +49,12 @@ import static org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil.resolveData
public class ApplicationManagementDAOFactory {
private static String databaseEngine;
- private static DataSource dataSource;
private static final Log log = LogFactory.getLog(ApplicationManagementDAOFactory.class);
public static void init(String datasourceName) {
ConnectionManagerUtil.resolveDataSource(datasourceName);
databaseEngine = ConnectionManagerUtil.getDatabaseType();
}
- 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 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 ApplicationDAO getApplicationDAO() {
if (databaseEngine != null) {
@@ -131,7 +109,6 @@ public class ApplicationManagementDAOFactory {
/**
* To get the instance of VisibilityDAOImplementation of the particular database engine.
- *
* @return specific VisibilityDAOImplementation
*/
public static VisibilityDAO getVisibilityDAO() {
@@ -149,7 +126,6 @@ public class ApplicationManagementDAOFactory {
/**
* To get the instance of SubscriptionDAOImplementation of the particular database engine.
- *
* @return GenericSubscriptionDAOImpl
*/
public static SubscriptionDAO getSubscriptionDAO() {
@@ -168,37 +144,31 @@ public class ApplicationManagementDAOFactory {
/**
* To get the instance of DeviceTypeDAOImpl of the particular database engine.
- *
* @return DeviceTypeDAOImpl
*/
public static DeviceTypeDAO getDeviceTypeDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new DeviceTypeDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
+ case Constants.DataBaseTypes.DB_TYPE_H2:
+ case Constants.DataBaseTypes.DB_TYPE_MYSQL:
+ case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
+ return new DeviceTypeDAOImpl();
+ default:
+ throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
}
- /**
- * To get the instance of LifecycleDAOImplementation of the particular database engine.
- *
- * @return GenericLifecycleDAOImpl
- */
- public static LifecycleStateDAO getLifecycleDAO() {
+ public static CommentDAO getCommentDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new GenericLifecycleStateImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
+ case Constants.DataBaseTypes.DB_TYPE_H2:
+ case Constants.DataBaseTypes.DB_TYPE_MYSQL:
+ case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
+ return new CommentDAOImpl();
+ default:
+ throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
}
}
throw new IllegalStateException("Database engine has not initialized properly.");
@@ -235,21 +205,4 @@ public class ApplicationManagementDAOFactory {
"Error while creating application-mgt database in the " + "startup ", e);
}
}
-
- public static CommentDAO getCommentDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new CommentDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
}
-
-
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java
deleted file mode 100644
index 8c63e99cc0..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/DAOFactory.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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.application.mgt.core.dao.common;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.device.application.mgt.common.exception.UnsupportedDatabaseEngineException;
-import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
-import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.CategoryDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.SubscriptionDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.application.GenericApplicationDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.GenericApplicationReleaseDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.application.release.OracleApplicationDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.category.GenericCategoryDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.lifecyclestate.GenericLifecycleStateImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.GenericPlatformDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.platform.OracleMsSQLPlatformDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.subscription.GenericSubscriptionDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.visibility.GenericVisibilityDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.util.ApplicationMgtDatabaseCreator;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-import org.wso2.carbon.device.application.mgt.core.util.Constants;
-import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
-
-import java.sql.SQLException;
-
-/**
- * This class intends to act as the primary entity that hides all DAO instantiation related complexities and logic so
- * that the business objection handling layer doesn't need to be aware of the same providing seamless plug-ability of
- * different data sources, connection acquisition mechanisms as well as different forms of DAO implementations to the
- * high-level implementations that require Application management related metadata persistence.
- */
-public class DAOFactory {
-
- private static String databaseEngine;
- private static final Log log = LogFactory.getLog(DAOFactory.class);
-
- public static void init(String datasourceName) {
- ConnectionManagerUtil.resolveDataSource(datasourceName);
- databaseEngine = ConnectionManagerUtil.getDatabaseType();
- }
-
- public static ApplicationDAO getApplicationDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new GenericApplicationDAOImpl();
- case Constants.DataBaseTypes.DB_TYPE_ORACLE:
- return new OracleApplicationDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- public static PlatformDAO getPlatformDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new GenericPlatformDAOImpl();
- case Constants.DataBaseTypes.DB_TYPE_MSSQL:
- case Constants.DataBaseTypes.DB_TYPE_ORACLE:
- return new OracleMsSQLPlatformDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- public static LifecycleStateDAO getLifecycleStateDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- case Constants.DataBaseTypes.DB_TYPE_ORACLE:
- return new GenericLifecycleStateImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- /**
- * To get the instance of ApplicationReleaseDAOImplementation of the particular database engine.
- *
- * @return specific ApplicationReleaseDAOImplementation
- */
- public static ApplicationReleaseDAO getApplicationReleaseDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- case Constants.DataBaseTypes.DB_TYPE_ORACLE:
- return new GenericApplicationReleaseDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- /**
- * To get the instance of VisibilityDAOImplementation of the particular database engine.
- *
- * @return specific VisibilityDAOImplementation
- */
- public static VisibilityDAO getVisibilityDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- return new GenericVisibilityDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- /**
- * To get the instance of SubscriptionDAOImplementation of the particular database engine.
- * @return GenericSubscriptionDAOImpl
- */
- public static SubscriptionDAO getSubscriptionDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
- return new GenericSubscriptionDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- /**
- * To get the instance of CategoryDAOImplementation of the particular database engine.
- * @return {@link org.wso2.carbon.device.application.mgt.core.dao.impl.category.GenericCategoryDAOImpl}
- */
- public static CategoryDAO getCategoryDAO() {
- if (databaseEngine != null) {
- switch (databaseEngine) {
- case Constants.DataBaseTypes.DB_TYPE_H2:
- case Constants.DataBaseTypes.DB_TYPE_MYSQL:
- return new GenericCategoryDAOImpl();
- default:
- throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
- }
- }
- throw new IllegalStateException("Database engine has not initialized properly.");
- }
-
- /**
- * This method initializes the databases by creating the database.
- *
- * @throws ApplicationManagementDAOException Exceptions thrown during the creation of the tables
- */
- public static void initDatabases() throws ApplicationManagementDAOException {
- String dataSourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
- String validationQuery = "SELECT * from APPM_PLATFORM";
- try {
- if (System.getProperty("setup") == null) {
- if (log.isDebugEnabled()) {
- log.debug("Application Management Database schema initialization check was skipped since "
- + "\'setup\' variable was not given during startup");
- }
- } else {
- DatabaseCreator databaseCreator = new ApplicationMgtDatabaseCreator(dataSourceName);
- if (!databaseCreator.isDatabaseStructureCreated(validationQuery)) {
- databaseCreator.createRegistryDatabase();
- log.info("Application Management tables are created in the database");
- } else {
- log.info("Application Management Database structure already exists. Not creating the database.");
- }
- }
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "Error while creating application-mgt database during the " + "startup ", e);
- } catch (Exception e) {
- throw new ApplicationManagementDAOException(
- "Error while creating application-mgt database in the " + "startup ", e);
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java
index 1513951128..f5c5bd33d2 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/common/Util.java
@@ -21,12 +21,8 @@ package org.wso2.carbon.device.application.mgt.core.dao.common;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
+import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.User;
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.Lifecycle;
-import org.wso2.carbon.device.application.mgt.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.common.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException;
@@ -37,9 +33,7 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
/**
* This class is responsible for handling the utils of the Application Management DAO.
@@ -52,60 +46,106 @@ public class Util {
* To create application object from the result set retrieved from the Database.
*
* @param rs ResultSet
- * @param rsProperties Properties resultset.
- * @param rsTags Tags resultset
+ * @return List of Applications that is retrieved from the Database.
+ * @throws SQLException SQL Exception
+ * @throws JSONException JSONException.
+ */
+ public static List loadApplications(ResultSet rs) throws SQLException, JSONException {
+
+ List applications = new ArrayList<>();
+ Application application = null ;
+ int applicatioId = -1;
+
+ while (rs.next()){
+ if (applicatioId != rs.getInt("APP_ID")){
+
+ if( application != null){
+ applications.add(application);
+ }
+ applicatioId = rs.getInt("APP_ID");
+ application = new Application();
+ application.setId(applicatioId);
+ application.setName(rs.getString("APP_NAME"));
+ application.setType(rs.getString("APP_TYPE"));
+ application.setAppCategory(rs.getString("APP_CATEGORY"));
+ application.setIsFree(rs.getInt("IS_FREE"));
+ application.setIsRestricted(rs.getInt("RESTRICTED"));
+
+ List tags = new ArrayList<>();
+ Tag tag = new Tag();
+ tag.setTagName(rs.getString("APP_TAG"));
+ tags.add(tag);
+ application.setTags(tags);
+
+ List unrestrictedRoles = new ArrayList<>();
+ UnrestrictedRole unrestrictedRole = new UnrestrictedRole();
+ unrestrictedRole.setRole(rs.getString("ROLE"));
+ unrestrictedRoles.add(unrestrictedRole);
+ application.setUnrestrictedRoles(unrestrictedRoles);
+ }else{
+ Tag tag = new Tag();
+ tag.setTagName(rs.getString("APP_TAG"));
+ UnrestrictedRole unrestrictedRole = new UnrestrictedRole();
+ unrestrictedRole.setRole(rs.getString("ROLE"));
+ if (application != null && application.getTags().contains(tag)){
+ application.getTags().add(tag);
+ }
+ if (application != null && application.getUnrestrictedRoles().contains(unrestrictedRole)){
+ application.getUnrestrictedRoles().add(unrestrictedRole);
+ }
+
+ }
+ if(rs.last()){
+ applications.add(application);
+ }
+ }
+
+ return applications;
+
+ }
+
+
+ /**
+ * To create application object from the result set retrieved from the Database.
+ *
+ * @param rs ResultSet
* @return Application that is retrieved from the Database.
* @throws SQLException SQL Exception
* @throws JSONException JSONException.
*/
- public static Application loadApplication(ResultSet rs, ResultSet rsProperties, ResultSet rsTags)
- throws SQLException, JSONException {
- Application application = new Application();
- application.setId(rs.getInt("ID"));
- application.setName(rs.getString("NAME"));
- application.setUuid(rs.getString("UUID"));
- application.setShortDescription(rs.getString("SHORT_DESCRIPTION"));
- application.setDescription(rs.getString("DESCRIPTION"));
- application.setScreenShotCount(rs.getInt("SCREEN_SHOT_COUNT"));
- application.setVideoName(rs.getString("VIDEO_NAME"));
- application.setCreatedAt(rs.getDate("CREATED_AT"));
- application.setModifiedAt(rs.getDate("MODIFIED_AT"));
- application.setUser(new User(rs.getString("CREATED_BY"), rs.getInt("TENANT_ID")));
+ public static Application loadApplication(ResultSet rs) throws SQLException, JSONException {
- Platform platform = new Platform();
- platform.setName(rs.getString("APL_NAME"));
- platform.setIdentifier(rs.getString("APL_IDENTIFIER"));
- application.setPlatform(platform);
+ Application application = null;
+ int applicatioId = -1;
+ int iteration = 0;
- Map properties = new HashMap<>();
- while (rsProperties.next()) {
- properties.put(rsProperties.getString("PROP_KEY"), rsProperties.getString("PROP_VAL"));
+ while (rs.next()){
+ if (iteration == 0){
+ application = new Application();
+ applicatioId = rs.getInt("APP_ID");
+ application.setId(applicatioId);
+ application.setName(rs.getString("APP_NAME"));
+ application.setType(rs.getString("APP_TYPE"));
+ application.setAppCategory(rs.getString("APP_CATEGORY"));
+ application.setIsFree(rs.getInt("IS_FREE"));
+ application.setIsRestricted(rs.getInt("RESTRICTED"));
+ }
+
+ Tag tag = new Tag();
+ tag.setTagName(rs.getString("APP_TAG"));
+ UnrestrictedRole unrestrictedRole = new UnrestrictedRole();
+ unrestrictedRole.setRole(rs.getString("ROLE"));
+ if (application.getTags().contains(tag)){
+ application.getTags().add(tag);
+ }
+ if (application.getUnrestrictedRoles().contains(unrestrictedRole)){
+ application.getUnrestrictedRoles().add(unrestrictedRole);
+ }
+ iteration++;
}
- application.setProperties(properties);
-
- List tags = new ArrayList<>();
- while ((rsTags.next())) {
- tags.add(rsTags.getString("NAME"));
- }
- application.setTags(tags);
-
- Category category = new Category();
- category.setId(rs.getInt("CAT_ID"));
- category.setName(rs.getString("CAT_NAME"));
- application.setCategory(category);
-
- LifecycleState lifecycleState = new LifecycleState();
- lifecycleState.setId(rs.getInt("LIFECYCLE_STATE_ID"));
- lifecycleState.setName(rs.getString("LS_NAME"));
- lifecycleState.setIdentifier(rs.getString("LS_IDENTIFIER"));
- lifecycleState.setDescription(rs.getString("LS_DESCRIPTION"));
-
- Lifecycle lifecycle = new Lifecycle();
- lifecycle.setLifecycleState(lifecycleState);
- application.setCurrentLifecycle(lifecycle);
return application;
- }
+ }
/**
* Cleans up the statement and resultset after executing the query
*
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java
index 1ce1444d2f..e3c6bf748a 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/GenericApplicationDAOImpl.java
@@ -21,27 +21,16 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
-import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.ApplicationList;
-import org.wso2.carbon.device.application.mgt.common.Filter;
-import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
-import org.wso2.carbon.device.application.mgt.common.Pagination;
+import org.wso2.carbon.device.application.mgt.common.*;
+import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-import java.sql.Connection;
-import java.sql.Date;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Iterator;
+import java.sql.*;
import java.util.List;
-import java.util.Map;
/**
* This handles ApplicationDAO related operations.
@@ -50,54 +39,41 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
private static final Log log = LogFactory.getLog(GenericApplicationDAOImpl.class);
- public Application createApplication(Application application) throws ApplicationManagementDAOException {
+ @Override
+ public int createApplication(Application application, int deviceId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an application");
log.debug("Application Details : ");
- log.debug("UUID : " + application.getUuid() + " Name : " + application.getName() + " User name : "
- + application.getUser().getUserName());
+ log.debug("App Name : " + application.getName() + " App Type : "
+ + application.getType() + " User Name : " + application.getUser().getUserName());
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
- String sql = "";
- String generatedColumns[] = {"ID"};
- boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
int index = 0;
+ int applicationId = -1;
try {
conn = this.getDBConnection();
- sql += "INSERT INTO APPM_APPLICATION (UUID, NAME, SHORT_DESCRIPTION, DESCRIPTION, "
- + "VIDEO_NAME, SCREEN_SHOT_COUNT, CREATED_BY, CREATED_AT, MODIFIED_AT, "
- + "APPLICATION_CATEGORY_ID, PLATFORM_ID, TENANT_ID, LIFECYCLE_STATE_ID, "
- + "LIFECYCLE_STATE_MODIFIED_AT, LIFECYCLE_STATE_MODIFIED_BY) VALUES "
- + "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
-
- stmt = conn.prepareStatement(sql, generatedColumns);
- stmt.setString(++index, application.getUuid());
+ stmt = conn.prepareStatement("INSERT INTO AP_APP (NAME, TYPE, APP_CATEGORY, "
+ + "IS_FREE, PAYMENT_CURRENCY, RESTRICTED, TENANT_ID) VALUES "
+ + "(?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
stmt.setString(++index, application.getName());
- stmt.setString(++index, application.getShortDescription());
- stmt.setString(++index, application.getDescription());
- stmt.setString(++index, application.getVideoName());
- stmt.setInt(++index, application.getScreenShotCount());
- stmt.setString(++index, application.getUser().getUserName());
- stmt.setDate(++index, new Date(application.getCreatedAt().getTime()));
- stmt.setDate(++index, new Date(application.getModifiedAt().getTime()));
- stmt.setInt(++index, application.getCategory().getId());
- stmt.setInt(++index, application.getPlatform().getId());
+ stmt.setString(++index, application.getType());
+ stmt.setString(++index, application.getAppCategory());
+ stmt.setInt(++index, application.getIsFree());
+ stmt.setString(++index, application.getPaymentCurrency());
+ stmt.setInt(++index, application.getIsRestricted());
stmt.setInt(++index, application.getUser().getTenantId());
- stmt.setInt(++index, application.getCurrentLifecycle().getLifecycleState().getId());
- stmt.setDate(++index, new Date(application.getCurrentLifecycle().getLifecycleStateModifiedAt().getTime()));
- stmt.setString(++index, application.getCurrentLifecycle().getGetLifecycleStateModifiedBy());
stmt.executeUpdate();
rs = stmt.getGeneratedKeys();
if (rs.next()) {
- application.setId(rs.getInt(1));
+ applicationId = rs.getInt(1);
}
- insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported);
- return application;
+ return applicationId;
+
} catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection when application creation", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding the application", e);
} finally {
@@ -105,99 +81,97 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
}
+ @Override
+ public void addTags(List tags, int applicationId, int tenantId) throws ApplicationManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Request received in DAO Layer to add tags");
+ }
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ int index = 0;
+ String sql = "INSERT INTO AP_APP_TAG (TAG, TENANT_ID, AP_APP_ID) VALUES (?, ?, ?)";
+ try{
+ conn = this.getDBConnection();
+ conn.setAutoCommit(false);
+ stmt = conn.prepareStatement(sql);
+ for (Tag tag : tags) {
+ stmt.setString(++index, tag.getTagName());
+ stmt.setInt(++index, tenantId);
+ stmt.setInt(++index, applicationId);
+ stmt.addBatch();
+ }
+ stmt.executeBatch();
+
+ }catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection when adding tags", e);
+ }catch (SQLException e) {
+ throw new ApplicationManagementDAOException("Error occurred while adding tags", e);
+ } finally {
+ Util.cleanupResources(stmt, rs);
+ }
+ }
+
+ @Override
+ public int isExistApplication(String appName, String type, int tenantId) throws ApplicationManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Request received in DAO Layer to verify whether the registering app is registered or not");
+ }
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ int isExist = 0;
+ int index = 0;
+ String sql = "SELECT * FROM AP_APP WHERE NAME = ? AND TYPE = ? TENANT_ID = ?";
+ try{
+ conn = this.getDBConnection();
+ conn.setAutoCommit(false);
+ stmt = conn.prepareStatement(sql);
+ stmt.setString(++index , appName);
+ stmt.setString(++index , type);
+ stmt.setInt(++index, tenantId);
+ rs = stmt.executeQuery();
+ if (rs.next()) {
+ isExist = 1;
+ }
+
+ return isExist;
+
+ }catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection when verifying application existence", e);
+ }catch (SQLException e) {
+ throw new ApplicationManagementDAOException("Error occurred while adding unrestricted roles", e);
+ } finally {
+ Util.cleanupResources(stmt, rs);
+ }
+ }
@Override
public ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting application data from the database");
- log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset()));
+ log.debug(String.format("Filter: limit=%s, offset=%s", filter.getLimit(), filter.getOffset()));
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
- String sql = "";
ApplicationList applicationList = new ApplicationList();
- List applications = new ArrayList<>();
Pagination pagination = new Pagination();
+ int index = 0;
+ String sql = "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY"
+ + " AS APP_CATEGORY, AP_APP.IS_FREE, AP_APP.RESTRICTED, AP_APP_TAG.TAG AS APP_TAG, AP_UNRESTRICTED_ROLES.ROLE "
+ + "AS APP_UNRESTRICTED_ROLES FROM ((AP_APP LEFT JOIN AP_APP_TAG ON AP_APP.ID = AP_APP_TAG.AP_APP_ID) "
+ + "LEFT JOIN AP_UNRESTRICTED_ROLES ON AP_APP.ID = AP_UNRESTRICTED_ROLES.AP_APP_ID) "
+ + "WHERE AP_APP.TENANT_ID = ?";
+
if (filter == null) {
throw new ApplicationManagementDAOException("Filter need to be instantiated");
- } else {
- pagination.setLimit(filter.getLimit());
- pagination.setOffset(filter.getOffset());
}
- try {
- conn = this.getDBConnection();
- stmt = this.generateGetApplicationsStatement(filter, conn, tenantId);
- rs = stmt.executeQuery();
-
- int length = 0;
-
- while (rs.next()) {
- //Getting properties
- sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, rs.getInt("ID"));
- ResultSet rsProperties = stmt.executeQuery();
-
- //Getting tags
- sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, rs.getInt("ID"));
- ResultSet rsTags = stmt.executeQuery();
-
- applications.add(Util.loadApplication(rs, rsProperties, rsTags));
- Util.cleanupResources(null, rsProperties);
- Util.cleanupResources(null, rsTags);
- length++;
- }
-
- pagination.setSize(length);
- pagination.setCount(this.getApplicationCount(filter));
- applicationList.setApplications(applications);
- applicationList.setPagination(pagination);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("Error occurred while getting application list for the tenant"
- + " " + tenantId + ". While executing " + sql, e);
- } catch (JSONException e) {
- throw new ApplicationManagementDAOException("Error occurred while parsing JSON, while getting application"
- + " list for the tenant " + tenantId, e);
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection while "
- + "getting application list for the tenant " + tenantId, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- return applicationList;
- }
-
- /**
- * This method is used to generate the statement that is used to get the applications with the given filter.
- *
- * @param filter Filter to filter out the applications.
- * @param conn Database Connection.
- * @param tenantId ID of the tenant to retrieve the applications.
- * @return the statement for getting applications that are belong to a particular filter.
- * @throws SQLException SQL Exception
- */
- protected PreparedStatement generateGetApplicationsStatement(Filter filter, Connection conn,
- int tenantId) throws SQLException {
- int index = 0;
- String sql = "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_ID, "
- + "CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, "
- + "LS.DESCRIPTION AS LS_DESCRIPTION FROM APPM_APPLICATION APP INNER JOIN APPM_PLATFORM APL "
- + "ON APP.PLATFORM_ID = APL.ID INNER JOIN APPM_APPLICATION_CATEGORY CAT "
- + "ON APP.APPLICATION_CATEGORY_ID = CAT.ID INNER JOIN APPM_LIFECYCLE_STATE LS "
- + "ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE APP.TENANT_ID = ? ";
-
- String userName = filter.getUserName();
- if (!userName.equals("ALL")) {
- sql += " AND APP.CREATED_BY = ? ";
- }
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
- sql += "AND LOWER (APP.NAME) ";
+ sql += " AND LOWER (AP_APP.NAME) ";
if (filter.isFullMatch()) {
sql += "= ?";
} else {
@@ -205,33 +179,88 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
}
- sql += "LIMIT ? OFFSET ?";
+ sql += " LIMIT ? OFFSET ? ORDER BY DESC APP_ID";
- PreparedStatement stmt = conn.prepareStatement(sql);
- stmt.setInt(++index, tenantId);
+ pagination.setLimit(filter.getLimit());
+ pagination.setOffset(filter.getOffset());
- if (!userName.equals("ALL")) {
- stmt.setString(++index, userName);
- }
- if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
- if (filter.isFullMatch()) {
- stmt.setString(++index, filter.getSearchQuery().toLowerCase());
- } else {
- stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%");
+ try {
+ conn = this.getDBConnection();
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(++index, tenantId);
+
+ if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
+ if (filter.isFullMatch()) {
+ stmt.setString(++index, filter.getSearchQuery().toLowerCase());
+ } else {
+ stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%");
+ }
}
+
+ stmt.setInt(++index, filter.getLimit());
+ stmt.setInt(++index, filter.getOffset());
+ rs = stmt.executeQuery();
+ applicationList.setApplications(Util.loadApplications(rs));
+ pagination.setSize(filter.getOffset());
+ pagination.setCount(this.getApplicationCount(filter));
+ applicationList.setPagination(pagination);
+
+ } catch (SQLException e) {
+ throw new ApplicationManagementDAOException("Error occurred while getting application list for the tenant"
+ + " " + tenantId + ". While executing " + sql, e);
+ }
+ catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection while "
+ + "getting application list for the tenant " + tenantId, e);
+ } catch (JSONException e) {
+ throw new ApplicationManagementDAOException("Error occurred while parsing JSON ", e);
+ } finally {
+ Util.cleanupResources(stmt, rs);
+ }
+ return applicationList;
+ }
+
+ @Override
+ public String getUuidOfLatestRelease(int appId) throws ApplicationManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Getting UUID from the latest app release");
}
- stmt.setInt(++index, filter.getLimit());
- stmt.setInt(++index, filter.getOffset());
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ String sql = "";
+ int index = 0;
+ String uuId = null;
+ try {
+ conn = this.getDBConnection();
+ sql += "SELECT APP_RELEASE.UUID AS UUID FROM AP_APP_RELEASE AS APP_RELEASE, AP_APP_LIFECYCLE_STATE "
+ + "AS LIFECYCLE WHERE APP_RELEASE.AP_APP_ID=? AND APP_RELEASE.ID = LIFECYCLE.AP_APP_RELEASE_ID "
+ + "AND LIFECYCLE.CURRENT_STATE = ? order by APP_RELEASE.ID DESC;";
- return stmt;
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(++index, appId);
+ stmt.setString(++index, "PUBLISHED");
+ rs = stmt.executeQuery();
+ if (rs.next()) {
+ uuId = rs.getString("UUID");
+ }
+ return uuId;
+ } catch (SQLException e) {
+ throw new ApplicationManagementDAOException("Error occurred while getting uuid of latest app release", e);
+ } catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection for "
+ + "getting app release id", e);
+ } finally {
+ Util.cleanupResources(stmt, rs);
+ }
}
@Override
public int getApplicationCount(Filter filter) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) {
log.debug("Getting application count from the database");
- log.debug(String.format("Filter: limit=%s, offset=%", filter.getLimit(), filter.getOffset()));
+ log.debug(String.format("Filter: limit=%s, offset=%s", filter.getLimit(), filter.getOffset()));
}
Connection conn;
@@ -246,13 +275,10 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
try {
conn = this.getDBConnection();
- sql += "SELECT COUNT(APP.ID) AS APP_COUNT ";
- sql += "FROM APPM_APPLICATION AS APP ";
- sql += "INNER JOIN APPM_PLATFORM AS APL ON APP.PLATFORM_ID = APL.ID ";
- sql += "INNER JOIN APPM_APPLICATION_CATEGORY AS CAT ON APP.APPLICATION_CATEGORY_ID = CAT.ID ";
+ sql += "SELECT count(APP.ID) AS APP_COUNT FROM AP_APP AS APP WHERE TENANT_ID = ?";
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
- sql += "WHERE LOWER (APP.NAME) LIKE ? ";
+ sql += " AND LOWER (APP.NAME) LIKE ? ";
}
sql += ";";
@@ -276,67 +302,38 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
@Override
- public Application getApplication(String uuid, int tenantId, String userName) throws
+ public Application getApplication(String appName, String appType, int tenantId) throws
ApplicationManagementDAOException {
- if (log.isDebugEnabled()) {
- log.debug("Getting application with the UUID(" + uuid + ") from the database");
+ if (log.isDebugEnabled()){
+ log.debug("Getting application with the type(" + appType + " and Name " + appName +
+ " ) from the database");
}
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
- String sql = "";
- Application application = null;
try {
-
conn = this.getDBConnection();
- sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_ID, "
- + "CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, "
- + "LS.DESCRIPTION AS LS_DESCRIPTION "
- + "FROM APPM_APPLICATION APP "
- + "INNER JOIN APPM_PLATFORM APL "
- + "ON APP.PLATFORM_ID = APL.ID "
- + "INNER JOIN APPM_APPLICATION_CATEGORY CAT "
- + "ON APP.APPLICATION_CATEGORY_ID = CAT.ID "
- + "INNER JOIN APPM_LIFECYCLE_STATE LS "
- + " ON APP.LIFECYCLE_STATE_ID = LS.ID "
- + "WHERE UUID = ? AND APP.TENANT_ID = ? ";
+ String sql = "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY "
+ + "AS APP_CATEGORY, AP_APP.IS_FREE, AP_APP_TAG.TAG, AP_UNRESTRICTED_ROLES.ROLE AS RELESE_ID FROM "
+ + "AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLES WHERE AP_APP.NAME=? AND AP_APP.TYPE= ? "
+ + "AND AP_APP.TENANT_ID=?;";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, uuid);
- stmt.setInt(2, tenantId);
-
- if (!userName.equals("ALL")) {
- sql += "AND APP.CREATED_BY = ?";
- stmt.setString(3, userName);
- }
+ stmt.setString(1, appName);
+ stmt.setString(2, appType);
+ stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (log.isDebugEnabled()) {
- log.debug("Successfully retrieved basic details of the application with the UUID " + uuid);
+ log.debug("Successfully retrieved basic details of the application with the type "
+ + appType +"and app name "+ appName);
}
- if (rs.next()) {
- //Getting properties
- sql = "SELECT * FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID=?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, rs.getInt("ID"));
- ResultSet rsProperties = stmt.executeQuery();
+ return Util.loadApplication(rs);
- //Getting tags
- sql = "SELECT * FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID=?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, rs.getInt("ID"));
- ResultSet rsTags = stmt.executeQuery();
-
- application = Util.loadApplication(rs, rsProperties, rsTags);
- Util.cleanupResources(null, rsProperties);
- Util.cleanupResources(null, rsTags);
- }
- return application;
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
- "Error occurred while getting application details with UUID " + uuid + " While executing query "
- + sql, e);
+ "Error occurred while getting application details with app name " + appName + " While executing query ", e);
} catch (JSONException e) {
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) {
@@ -347,198 +344,136 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
@Override
- public void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String userName, int tenantId)
- throws ApplicationManagementDAOException {
- if (log.isDebugEnabled()) {
- log.debug("Change Life cycle status change " + lifecycleIdentifier + "request received to the DAO "
- + "level for the application with " + "the UUID '" + applicationUUID + "' from the user "
- + userName);
+ public Application getApplicationById(int applicationId, int tenantId) throws
+ ApplicationManagementDAOException {
+ if (log.isDebugEnabled()){
+ log.debug("Getting application with the id (" + applicationId + ") from the database");
}
- Connection conn;
- PreparedStatement stmt = null;
- try {
- conn = this.getDBConnection();
- String sql = "UPDATE APPM_APPLICATION SET "
- + "LIFECYCLE_STATE_ID = (SELECT ID FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?), "
- + "LIFECYCLE_STATE_MODIFIED_BY = ?, LIFECYCLE_STATE_MODIFIED_AT = ? WHERE UUID = ? AND TENANT_ID "
- + "= ?";
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, lifecycleIdentifier);
- stmt.setString(2, userName);
- stmt.setDate(3, new Date(System.currentTimeMillis()));
- stmt.setString(4, applicationUUID);
- stmt.setInt(5, tenantId);
- stmt.executeUpdate();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "Error occurred while changing lifecycle of application: " + applicationUUID + " to: "
- + lifecycleIdentifier + " state.", e);
- } finally {
- Util.cleanupResources(stmt, null);
- }
- }
-
- @Override
- public List getNextLifeCycleStates(String applicationUUID, int tenantId)
- throws ApplicationManagementDAOException {
- Connection connection;
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
-
- String sql = "SELECT STATE.NAME, TRANSITION.DESCRIPTION, TRANSITION.PERMISSION FROM ( SELECT * FROM "
- + "APPM_LIFECYCLE_STATE ) STATE RIGHT JOIN (SELECT * FROM APPM_LC_STATE_TRANSITION WHERE "
- + "INITIAL_STATE = (SELECT LIFECYCLE_STATE_ID FROM APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?)) "
- + "TRANSITION ON TRANSITION.NEXT_STATE = STATE.ID";
-
- try {
- connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(sql);
- preparedStatement.setString(1, applicationUUID);
- preparedStatement.setInt(2, tenantId);
- resultSet = preparedStatement.executeQuery();
-
- List lifecycleStateTransitions = new ArrayList<>();
-
- while (resultSet.next()) {
- LifecycleStateTransition lifecycleStateTransition = new LifecycleStateTransition();
- lifecycleStateTransition.setDescription(resultSet.getString(2));
- lifecycleStateTransition.setNextState(resultSet.getString(1));
- lifecycleStateTransition.setPermission(resultSet.getString(3));
- lifecycleStateTransitions.add(lifecycleStateTransition);
- }
- return lifecycleStateTransitions;
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error while getting the DBConnection for getting the life "
- + "cycle states for the application with the UUID : " + applicationUUID, e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "'.", e);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- @Override
- public void updateScreenShotCount(String applicationUUID, int tenantId, int count)
- throws ApplicationManagementDAOException {
- Connection connection;
- PreparedStatement statement = null;
- String sql = "UPDATE APPM_APPLICATION SET SCREEN_SHOT_COUNT = ? where UUID = ? and TENANT_ID = ?";
-
- try {
- connection = this.getDBConnection();
- statement = connection.prepareStatement(sql);
- statement.setInt(1, count);
- statement.setString(2, applicationUUID);
- statement.setInt(3, tenantId);
- statement.executeUpdate();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Database connection while trying to update the screen-shot "
- + "count for the application with UUID " + applicationUUID + " for the tenant " + tenantId);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "' .", e);
- } finally {
- Util.cleanupResources(statement, null);
- }
-
- }
-
- @Override
- public boolean isApplicationExist(String categoryName) throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
- String sql = "SELECT * FROM APPM_APPLICATION WHERE APPLICATION_CATEGORY_ID = (SELECT ID FROM "
- + "APPM_APPLICATION_CATEGORY WHERE NAME = ?)";
try {
conn = this.getDBConnection();
+ String sql = "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY \n"
+ + "AS APP_CATEGORY, AP_APP.IS_FREE, AP_APP_TAG.TAG, AP_UNRESTRICTED_ROLES.ROLE AS RELESE_ID FROM \n"
+ + "AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLES WHERE AP_APP.ID=? AND AP_APP.TENANT_ID=?;";
+
stmt = conn.prepareStatement(sql);
- stmt.setString(1, categoryName);
+ stmt.setInt(1, applicationId);
+ stmt.setInt(2, tenantId);
rs = stmt.executeQuery();
- return rs.next();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException(
- "Database Connection Exception while trying to check the " + "applications for teh category "
- + categoryName, e);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Successfully retrieved basic details of the application with the id "
+ + applicationId);
+ }
+
+ return Util.loadApplication(rs);
+
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
- "SQL Exception while trying to get the application related with categories, while executing " + sql,
- e);
+ "Error occurred while getting application details with app id " + applicationId + " While executing query ", e);
+ } catch (JSONException e) {
+ throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
+ } catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
- public Application editApplication(Application application, int tenantId) throws ApplicationManagementDAOException {
+ public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementDAOException {
+ if (log.isDebugEnabled()){
+ log.debug("Getting application with the application ID(" + appId + " ) from the database");
+ }
Connection conn;
PreparedStatement stmt = null;
- String sql = "";
- boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
+ ResultSet rs = null;
+ Boolean isAppExist = false;
+ try {
+ conn = this.getDBConnection();
+ String sql = "SELECT AP_APP.ID AS APP_ID, AP_APP.NAME AS APP_NAME, AP_APP.TYPE AS APP_TYPE, AP_APP.APP_CATEGORY "
+ + "AS APP_CATEGORY, AP_APP.IS_FREE, AP_APP_TAG.TAG, AP_UNRESTRICTED_ROLES.ROLE AS RELESE_ID FROM "
+ + "AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLES WHERE AP_APP.ID=?;";
+
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, appId);
+ rs = stmt.executeQuery();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Successfully retrieved basic details of the application with the application ID " + appId);
+ }
+
+ if (rs.next()){
+ isAppExist = true;
+ }
+
+ return isAppExist;
+
+ } catch (SQLException e) {
+ throw new ApplicationManagementDAOException(
+ "Error occurred while getting application details with app ID " + appId + " While executing query ", e);
+ }
+ catch (DBConnectionException e) {
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
+ } finally {
+ Util.cleanupResources(stmt, rs);
+ }
+ }
+
+ @Override
+ public Application editApplication(Application application, int tenantId) throws ApplicationManagementException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ Application existingApplication = this.getApplication(application.getName(), application.getType(), tenantId);
+
+ if (existingApplication == null){
+ throw new ApplicationManagementException("There doesn't have an application for updating");
+ }
try {
conn = this.getDBConnection();
int index = 0;
- sql += "UPDATE APPM_APPLICATION SET NAME = COALESCE (?, NAME), SHORT_DESCRIPTION = COALESCE "
- + "(?, SHORT_DESCRIPTION), DESCRIPTION = COALESCE (?, DESCRIPTION), SCREEN_SHOT_COUNT = "
- + "COALESCE (?, SCREEN_SHOT_COUNT), VIDEO_NAME = COALESCE (?, VIDEO_NAME), MODIFIED_AT = COALESCE "
- + "(?, MODIFIED_AT), ";
+ String sql = "UPDATE AP_APP SET ";
- if (application.getPayment() != null) {
- sql += " IS_FREE = COALESCE (?, IS_FREE), ";
- if (application.getPayment().getPaymentCurrency() != null) {
- sql += "PAYMENT_CURRENCY = COALESCE (?, PAYMENT_CURRENCY), ";
- }
- sql += "PAYMENT_PRICE = COALESCE (?, PAYMENT_PRICE), ";
+
+ if (application.getName() != null && !application.getName().equals(existingApplication.getName())) {
+ sql += "NAME = ?, ";
}
- if (application.getCategory() != null && application.getCategory().getId() != 0) {
- sql += "APPLICATION_CATEGORY_ID = COALESCE (?, APPLICATION_CATEGORY_ID), ";
+ if (application.getType() != null && !application.getType().equals(existingApplication.getType())){
+ sql += "TYPE = ?, ";
}
- if (application.getPlatform() != null && application.getPlatform().getId() != 0) {
- sql += "PLATFORM_ID = COALESCE (?, PLATFORM_ID), ";
+ if (application.getAppCategory() != null && !application.getAppCategory().equals(existingApplication.getAppCategory())){
+ sql += "APP_CATEGORY = ?, ";
+ }
+ if (application.getIsRestricted() != existingApplication.getIsRestricted()){
+ sql += "RESTRICTED = ? ";
+ }
+ if (application.getIsFree() != existingApplication.getIsFree()){
+ sql += "IS_FREE = ? ";
}
- sql += "TENANT_ID = COALESCE (?, TENANT_ID) WHERE UUID = ?";
+ sql += "WHERE ID = ?";
stmt = conn.prepareStatement(sql);
- stmt.setString(++index, application.getName());
- stmt.setString(++index, application.getShortDescription());
- stmt.setString(++index, application.getDescription());
- stmt.setInt(++index, application.getScreenShotCount());
- stmt.setString(++index, application.getVideoName());
- stmt.setDate(++index, new Date(application.getModifiedAt().getTime()));
- if (application.getPayment() != null) {
- stmt.setBoolean(++index, application.getPayment().isFreeApp());
- if (application.getPayment().getPaymentCurrency() != null) {
- stmt.setString(++index, application.getPayment().getPaymentCurrency());
- }
- stmt.setFloat(++index, application.getPayment().getPaymentPrice());
+ if (application.getName() != null && !application.getName().equals(existingApplication.getName())) {
+ stmt.setString(++index, application.getName());
+ }
+ if (application.getType() != null && !application.getType().equals(existingApplication.getType())){
+ stmt.setString(++index, application.getType());
+ }
+ if (application.getAppCategory() != null && !application.getAppCategory().equals(existingApplication.getAppCategory())){
+ stmt.setString(++index, application.getAppCategory());
+ }
+ if (application.getIsRestricted() != existingApplication.getIsRestricted()){
+ stmt.setInt(++index, application.getIsRestricted());
+ }
+ if (application.getIsFree() != existingApplication.getIsFree()){
+ stmt.setInt(++index, application.getIsFree());
}
- if (application.getCategory() != null && application.getCategory().getId() != 0) {
- stmt.setInt(++index, application.getCategory().getId());
- }
- if (application.getPlatform() != null && application.getPlatform().getId() != 0) {
- stmt.setInt(++index, application.getPlatform().getId());
- }
- stmt.setInt(++index, tenantId);
- stmt.setString(++index, application.getUuid());
+ stmt.setInt(++index, application.getId());
stmt.executeUpdate();
-
- application.setId(getApplicationId(application.getUuid(), tenantId));
-
- sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, application.getId());
- stmt.executeUpdate();
-
- // delete existing properties and add new ones. if no properties are set, existing ones will be deleted.
- sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, application.getId());
- stmt.executeUpdate();
-
- insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported);
return application;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
@@ -549,90 +484,21 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
}
- /**
- * To insert application properties and Tags
- *
- * @param application Application in which the properties and tags need to be inserted
- */
- private void insertApplicationTagsAndProperties(Application application, PreparedStatement stmt, Connection
- conn, boolean isBatchExecutionSupported) throws SQLException {
- String sql;
- if (application.getTags() != null && application.getTags().size() > 0) {
- sql = "INSERT INTO APPM_APPLICATION_TAG (NAME, APPLICATION_ID) VALUES (?, ?); ";
- stmt = conn.prepareStatement(sql);
- for (String tag : application.getTags()) {
- stmt.setString(1, tag);
- stmt.setInt(2, application.getId());
-
- if (isBatchExecutionSupported) {
- stmt.addBatch();
- } else {
- stmt.execute();
- }
- }
- if (isBatchExecutionSupported) {
- stmt.executeBatch();
- }
- }
-
- if (application.getProperties() != null && application.getProperties().size() > 0) {
- sql = "INSERT INTO APPM_APPLICATION_PROPERTY (PROP_KEY, PROP_VAL, APPLICATION_ID) VALUES (?, ?, ?); ";
- stmt = conn.prepareStatement(sql);
- Iterator it = application.getProperties().entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry property = (Map.Entry) it.next();
- stmt.setString(1, property.getKey());
- stmt.setString(2, property.getValue());
- stmt.setInt(3, application.getId());
- if (isBatchExecutionSupported) {
- stmt.addBatch();
- } else {
- stmt.execute();
- }
- }
- if (isBatchExecutionSupported) {
- stmt.executeBatch();
- }
- }
- }
-
@Override
- public void deleteApplication(String uuid, int tenantId) throws ApplicationManagementDAOException {
+ public void deleteApplication(int appId) throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = this.getDBConnection();
- String sql = "DELETE FROM APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?";
+ String sql = "DELETE FROM AP_APP WHERE ID = ? ";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, uuid);
- stmt.setInt(2, tenantId);
+ stmt.setInt(1, appId);
stmt.executeUpdate();
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
- throw new ApplicationManagementDAOException("Error occurred while deleting the application: " + uuid, e);
- } finally {
- Util.cleanupResources(stmt, null);
- }
- }
-
- @Override
- public void deleteProperties(int applicationId) throws ApplicationManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- try {
- conn = this.getDBConnection();
- String sql = "DELETE FROM APPM_APPLICATION_PROPERTY WHERE APPLICATION_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, applicationId);
- stmt.executeUpdate();
-
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "Error occurred while deleting properties of application: " + applicationId, e);
+ throw new ApplicationManagementDAOException("Error occurred while deleting the application: " , e);
} finally {
Util.cleanupResources(stmt, null);
}
@@ -644,7 +510,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
PreparedStatement stmt = null;
try {
conn = this.getDBConnection();
- String sql = "DELETE FROM APPM_APPLICATION_TAG WHERE APPLICATION_ID = ?";
+ String sql = "DELETE FROM AP_APP_TAG WHERE ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, applicationId);
stmt.executeUpdate();
@@ -660,7 +526,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
@Override
- public int getApplicationId(String uuid, int tenantId) throws ApplicationManagementDAOException {
+ public int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
@@ -668,10 +534,11 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
int id = -1;
try {
conn = this.getDBConnection();
- sql = "SELECT ID FROM APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?";
+ sql = "SELECT ID FROM AP_APP WHERE NAME = ? AND TYPE = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, uuid);
- stmt.setInt(2, tenantId);
+ stmt.setString(1, appName);
+ stmt.setString(2, appType);
+ stmt.setInt(3, tenantId);
rs = stmt.executeQuery();
if (rs.next()) {
id = rs.getInt(1);
@@ -685,5 +552,4 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
}
return id;
}
-
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java
index fb9f371a50..7055674897 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/GenericApplicationReleaseDAOImpl.java
@@ -22,219 +22,279 @@ package org.wso2.carbon.device.application.mgt.core.dao.impl.application.release
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationReleaseDAO;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.sql.Connection;
-import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
/**
* GenericApplicationReleaseDAOImpl holds the implementation of ApplicationRelease related DAO operations.
*/
public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO {
+ /**
+ * To insert the Application Release Details.
+ *
+ * @param appId Id of the application
+ * @param applicationRelease Application Release the properties of which that need to be inserted.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
@Override
- public ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws
+ public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
ResultSet resultSet = null;
- if (applicationRelease.isDefault()) {
+ String sql = "INSERT INTO AP_APP_RELEASE (VERSION,TENANT_ID,UUID,RELEASE_TYPE,APP_PRICE,STORED_LOCATION, "
+ + "BANNER_LOCATION, SC_1_LOCATION,SC_2_LOCATION,SC_3_LOCATION, APP_HASH_VALUE,SHARED_WITH_ALL_TENANTS, "
+ + "APP_META_INFO,CREATED_BY,AP_APP_ID) VALUES "
+ + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
- }
- String sql = "insert into APPM_APPLICATION_RELEASE(VERSION_NAME, RELEASE_RESOURCE, RELEASE_CHANNEL ,"
- + "RELEASE_DETAILS, CREATED_AT, APPM_APPLICATION_ID, IS_DEFAULT) values (?, ?, ?, ?, ?, ?, ?)";
int index = 0;
String generatedColumns[] = {"ID"};
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns);
- statement.setString(++index, applicationRelease.getVersionName());
- statement.setString(++index, applicationRelease.getResource());
- statement.setString(++index, String.valueOf(applicationRelease.getReleaseChannel()));
- statement.setString(++index, applicationRelease.getReleaseDetails());
- statement.setDate(++index, new Date(applicationRelease.getCreatedAt().getTime()));
- statement.setInt(++index, applicationRelease.getApplication().getId());
- statement.setBoolean(++index, applicationRelease.isDefault());
+ statement.setString(++index, applicationRelease.getVersion());
+ statement.setString(++index, applicationRelease.getTenantId());
+ statement.setString(++index, applicationRelease.getUuid());
+ statement.setString(++index, String.valueOf(applicationRelease.getReleaseType()));
+ statement.setDouble(++index, applicationRelease.getPrice());
+ statement.setString(++index, applicationRelease.getAppStoredLoc());
+ statement.setString(++index, applicationRelease.getScreenshotLoc1());
+ statement.setString(++index, applicationRelease.getScreenshotLoc2());
+ statement.setString(++index, applicationRelease.getScreenshotLoc3());
+ statement.setString(++index, applicationRelease.getAppHashValue());
+ statement.setInt(++index, applicationRelease.getIsSharedWithAllTenants());
+ statement.setString(++index, applicationRelease.getMetaData());
+ statement.setString(++index, applicationRelease.getApplicationCreator());
+ statement.setInt(++index, appId);
statement.executeUpdate();
resultSet = statement.getGeneratedKeys();
if (resultSet.next()) {
applicationRelease.setId(resultSet.getInt(1));
}
- insertApplicationReleaseProperties(connection, applicationRelease);
return applicationRelease;
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
- "SQL Exception while trying to release an application (UUID : " + applicationRelease
- .getApplication().getUuid() + "), by executing the query " + sql, e);
+ "SQL Exception while trying to release an application by executing the query " + sql, e);
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException(
- "Database Connection Exception while trying to release the " + "applcation with UUID "
- + applicationRelease.getApplication().getUuid(), e);
+ "Database Connection Exception while trying to release a new version" , e);
} finally {
Util.cleanupResources(statement, resultSet);
}
}
+ /**
+ * To get release details of a specific application.
+ *
+ * @param applicationName Name of the application.
+ * @param applicationType Type of the application.
+ * @param versionName version name of the application.
+ * @param releaseType type of the application release.
+ * @param tenantId Tenant Id
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
@Override
- public ApplicationRelease getRelease(String applicationUuid, String versionName, int tenantId)
- throws ApplicationManagementDAOException {
+ public ApplicationRelease getRelease(String applicationName, String applicationType, String versionName,
+ String releaseType, int tenantId) throws ApplicationManagementDAOException {
+
Connection connection;
PreparedStatement statement = null;
ResultSet resultSet = null;
- String sql = "SELECT * FROM APPM_APPLICATION_RELEASE WHERE VERSION_NAME = ? AND APPM_APPLICATION_ID = "
- + "(SELECT ID FROM APPM_APPLICATION WHERE UUID = ? and TENANT_ID = ?)";
ApplicationRelease applicationRelease = null;
- ResultSet rsProperties = null;
+ String sql = "SELECT AR.ID AS RELESE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE, AR.APP_PRICE,"
+ + " AR.STORED_LOCATION, AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, "
+ + "AR.SC_2_LOCATION AS SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS HASH_VALUE, "
+ + "AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO, AR.CREATED_BY, AR.CREATED_AT, AR.PUBLISHED_BY, "
+ + "AR.PUBLISHED_AT, AR.STARS, AL.CURRENT_STATE, AL.PREVIOUSE_STATE, AL.UPDATED_BY, AL.UPDATED_AT FROM "
+ + "AP_APP_RELEASE AS AR, AP_APP_LIFECYCLE_STATE AS AL "
+ + "WHERE AR.AP_APP_ID=(SELECT ID FROM AP_APP WHERE NAME=? AND TYPE=? AND TENANT_ID=?)"
+ + " AND AR.VERSION=? AND AR.RELEASE_TYPE=? AND AL.AP_APP_RELEASE_ID=AR.ID "
+ + "AND AL.TENANT_ID=AR.TENANT_ID ORDER BY AL.UPDATED_AT DESC;";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
- statement.setString(1, versionName);
- statement.setString(2, applicationUuid);
+ statement.setString(1, applicationName);
+ statement.setString(2, applicationType);
statement.setInt(3, tenantId);
+ statement.setString(4, versionName);
+ statement.setString(5, releaseType);
resultSet = statement.executeQuery();
if (resultSet.next()) {
applicationRelease = new ApplicationRelease();
- applicationRelease.setVersionName(versionName);
- applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT"));
- applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT"));
- applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL"));
- applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS"));
- applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE"));
-
- sql = "SELECT * FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID=?";
- statement = connection.prepareStatement(sql);
- statement.setInt(1, resultSet.getInt("ID"));
- rsProperties = statement.executeQuery();
-
- Map properties = new HashMap<>();
- while (rsProperties.next()) {
- properties.put(rsProperties.getString("PROP_KEY"),
- rsProperties.getString("PROP_VAL"));
- }
- applicationRelease.setProperties(properties);
+ applicationRelease.setId(resultSet.getInt("RELEASE_ID"));
+ applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
+ applicationRelease.setUuid(resultSet.getString("UUID"));
+ applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
+ applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
+ applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION"));
+ applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION"));
+ applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1"));
+ applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2"));
+ applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3"));
+ applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
+ applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
+ applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
+ applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
+ applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
+ applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
+ applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
+ applicationRelease.setStars(resultSet.getInt("STARS"));
+ applicationRelease.setCurrentState(resultSet.getString("CURRENT_STATE"));
+ applicationRelease.setPreviousState(resultSet.getString("PREVIOUSE_STATE"));
+ applicationRelease.setStateModifiedBy(resultSet.getString("UPDATED_BY"));
+ applicationRelease.setStateModifiedAt(resultSet.getTimestamp("UPDATED_AT"));
}
return applicationRelease;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the "
- + "release details of the application with UUID " + applicationUuid + " and version " +
+ + "release details of the application with " + applicationName + " and version " +
versionName, e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error while getting release details of the application " +
- applicationUuid + " and version " + versionName + " , while executing the query " + sql, e);
+ applicationName + " and version " + versionName + " , while executing the query " + sql, e);
} finally {
Util.cleanupResources(statement, resultSet);
- Util.cleanupResources(null, rsProperties);
}
}
+ /**
+ * To insert the application release properties.
+ *
+ * @param applicationName Name of the application.
+ * @param applicationType Type of the application.
+ * @param tenantId Tenant Id
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
@Override
- public List getApplicationReleases(String applicationUUID, int tenantId)
+ public List getApplicationReleases(String applicationName, String applicationType, int tenantId)
throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
ResultSet resultSet = null;
- String sql = "SELECT * FROM APPM_APPLICATION_RELEASE WHERE APPM_APPLICATION_ID = (SELECT ID FROM "
- + "APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?)";
List applicationReleases = new ArrayList<>();
- ResultSet rsProperties = null;
+ String sql = "SELECT AR.ID AS RELESE_ID, AR.VERSION AS RELEASE_VERSION, AR.UUID, AR.RELEASE_TYPE, AR.APP_PRICE,"
+ + " AR.STORED_LOCATION, AR.BANNER_LOCATION, AR.SC_1_LOCATION AS SCREEN_SHOT_1, AR.SC_2_LOCATION AS "
+ + "SCREEN_SHOT_2, AR.SC_3_LOCATION AS SCREEN_SHOT_3, AR.APP_HASH_VALUE AS HASH_VALUE, "
+ + "AR.SHARED_WITH_ALL_TENANTS AS SHARED, AR.APP_META_INFO, AR.CREATED_BY, AR.CREATED_AT, "
+ + "AR.PUBLISHED_BY, AR.PUBLISHED_AT, AR.STARS FROM AP_APP_RELEASE AS "
+ + "AR where AR.AP_APP_ID=(SELECT ID FROM AP_APP WHERE NAME = ? AND TYPE = ? "
+ + "AND TENANT_ID = ?) AND AR.TENANT_ID = ? ;";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
- statement.setString(1, applicationUUID);
- statement.setInt(2, tenantId);
+ statement.setString(1, applicationName);
+ statement.setString(2, applicationType);
+ statement.setInt(3, tenantId);
+ statement.setInt(4, tenantId);
resultSet = statement.executeQuery();
while (resultSet.next()) {
ApplicationRelease applicationRelease = new ApplicationRelease();
- applicationRelease.setVersionName(resultSet.getString("VERSION_NAME"));
- applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT"));
- applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT"));
- applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL"));
- applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS"));
- applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE"));
-
- sql = "SELECT * FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID= ?";
- statement = connection.prepareStatement(sql);
- statement.setInt(1, resultSet.getInt("ID"));
- rsProperties = statement.executeQuery();
-
- Map properties = new HashMap<>();
- while (rsProperties.next()) {
- properties.put(rsProperties.getString("PROP_KEY"), rsProperties.getString("PROP_VAL"));
- }
- applicationRelease.setProperties(properties);
+ applicationRelease.setId(resultSet.getInt("RELESE_ID"));
+ applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
+ applicationRelease.setUuid(resultSet.getString("UUID"));
+ applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
+ applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
+ applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION"));
+ applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION"));
+ applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1"));
+ applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2"));
+ applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3"));
+ applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
+ applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
+ applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
+ applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
+ applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
+ applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
+ applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
+ applicationRelease.setStars(resultSet.getInt("STARS"));
applicationReleases.add(applicationRelease);
+
}
return applicationReleases;
} catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the "
- + "release details of the application with UUID " + applicationUUID, e);
+ + "release details of the application with Name " + applicationName, e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
- "Error while getting all the release details of the " + "application " + applicationUUID
+ "Error while getting all the release details of the " + applicationName + " application"
+ ", while executing the query " + sql, e);
} finally {
Util.cleanupResources(statement, resultSet);
- Util.cleanupResources(null, rsProperties);
}
}
+ /**
+ * To Update starts of an application release.
+ *
+ * @param id Id of the application Release.
+ * @param stars given stars for the application release.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
@Override
- public ApplicationRelease updateRelease(ApplicationRelease applicationRelease)
- throws ApplicationManagementDAOException {
+ public void updateStars(int id, int stars) throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
- String sql = "UPDATE APPM_APPLICATION_RELEASE SET RELEASE_RESOURCE = IFNULL (?, RELEASE_RESOURCE)," +
- " RELEASE_CHANNEL = IFNULL (?, RELEASE_CHANNEL), RELEASE_DETAILS = IFNULL (?, RELEASE_DETAILS), " +
- "IS_DEFAULT = IFNULL (?, IS_DEFAULT) WHERE APPM_APPLICATION_ID = ? AND VERSION_NAME = ?";
+ String sql = "UPDATE AP_APP_RELEASE SET STARS = ? WHERE ID = ?;";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
- statement.setString(1, applicationRelease.getResource());
- statement.setString(2, String.valueOf(applicationRelease.getReleaseChannel()));
- statement.setString(3, applicationRelease.getReleaseDetails());
- statement.setBoolean(4, applicationRelease.isDefault());
- statement.setInt(5, applicationRelease.getApplication().getId());
- statement.setString(6, applicationRelease.getVersionName());
+ statement.setInt(1, stars);
+ statement.setInt(2, id);
statement.executeUpdate();
-
- sql = "DELETE FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID = ?";
- statement = connection.prepareStatement(sql);
- statement.setInt(1, applicationRelease.getId());
- statement.executeUpdate();
- insertApplicationReleaseProperties(connection, applicationRelease);
- return applicationRelease;
} catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Database connection exception while trying to update the "
- + "Application release for the application with UUID " + applicationRelease.getApplication()
- .getUuid() + " for the version " + applicationRelease.getVersionName(), e);
+ throw new ApplicationManagementDAOException(
+ "Database connection exception while trying to update the application release", e);
} catch (SQLException e) {
throw new ApplicationManagementDAOException(
- "SQL exception while updating the release, while executing the query " + sql, e);
+ "SQL exception while updating the release ,while executing the query " + sql, e);
} finally {
Util.cleanupResources(statement, null);
}
}
+// have to complete
+//Todo
+ /**
+ * To insert the application release properties.
+ *
+ * @param applicationRelease Application Release the properties of which that need to be inserted.
+ * @throws SQLException SQL Exception.
+ */
+ @Override
+ public ApplicationRelease updateRelease(ApplicationRelease applicationRelease)
+ throws ApplicationManagementDAOException {
+ return applicationRelease;
+ }
+
+//
+
+ /**
+ * To delete an application release.
+ *
+ * @param id Id of the application Release.
+ * @param version version name of the application release.
+ * @throws ApplicationManagementDAOException Application Management DAO Exception.
+ */
@Override
public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
Connection connection;
PreparedStatement statement = null;
- String sql = "DELETE FROM APPM_APPLICATION_RELEASE WHERE APPM_APPLICATION_ID = ? AND VERSION_NAME = ?";
+ String sql = "DELETE FROM AP_APP_RELEASE WHERE ID = ? AND VERSION = ?";
try {
connection = this.getDBConnection();
statement = connection.prepareStatement(sql);
@@ -253,116 +313,4 @@ public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements
}
}
- @Override
- public void deleteReleaseProperties(int id) throws ApplicationManagementDAOException {
- Connection connection;
- PreparedStatement statement = null;
- String sql = "DELETE FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID = ?";
- try {
- connection = this.getDBConnection();
- statement = connection.prepareStatement(sql);
- statement.setInt(1, id);
- statement.executeUpdate();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException(
- "Database connection exception while trying to delete the release properties ", e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "SQL exception while deleting the properties of application release with the id " + id, e);
- } finally {
- Util.cleanupResources(statement, null);
- }
- }
-
- @Override
- public void changeReleaseDefault(String uuid, String version, boolean isDefault, String releaseChannel,
- int tenantId) throws ApplicationManagementDAOException {
- Connection connection;
- PreparedStatement statement = null;
- String sql = "UPDATE APPM_APPLICATION_RELEASE SET IS_DEFAULT = ? AND RELEASE_CHANNEL = ? WHERE "
- + "APPM_APPLICATION_ID = (SELECT ID from APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?) "
- + "AND VERSION_NAME = ?";
-
- try {
- if (isDefault) {
- removeDefaultReleases(uuid, releaseChannel, tenantId);
- }
- connection = this.getDBConnection();
- statement = connection.prepareStatement(sql);
- statement.setBoolean(1, isDefault);
- statement.setString(2, releaseChannel.toUpperCase());
- statement.setString(3, uuid);
- statement.setInt(4, tenantId);
- statement.setString(5, version);
- statement.executeUpdate();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException(
- "Database Connection exception while try to change the " + "default release of the release channel "
- + releaseChannel + " for the application " + uuid, e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "SQL Exception while trying to change the default release of " + "the release channel "
- + releaseChannel + " for the application " + uuid, e);
- } finally {
- Util.cleanupResources(statement, null);
- }
- }
-
- /**
- * To insert the application release properties.
- *
- * @param connection Database Connection
- * @param applicationRelease Application Release the properties of which that need to be inserted.
- * @throws SQLException SQL Exception.
- */
- private void insertApplicationReleaseProperties(Connection connection, ApplicationRelease applicationRelease)
- throws SQLException {
- String sql;
- boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
-
- if (applicationRelease.getProperties() != null && applicationRelease.getProperties().size() != 0) {
- sql = "INSERT INTO APPM_RELEASE_PROPERTY (PROP_KEY, PROP_VALUE, APPLICATION_RELEASE_ID) VALUES (?,?,?)";
- PreparedStatement statement = connection.prepareStatement(sql);
- for (Object entry : applicationRelease.getProperties().entrySet()) {
- Map.Entry property = (Map.Entry) entry;
- statement.setString(1, property.getKey());
- statement.setString(2, property.getValue());
- statement.setInt(3, applicationRelease.getId());
- if (isBatchExecutionSupported) {
- statement.addBatch();
- } else {
- statement.execute();
- }
- }
- if (isBatchExecutionSupported) {
- statement.executeBatch();
- }
- }
- }
-
- /**
- * To make all the releases of particular release channel as non-default ones.
- *
- * @param uuid UUID of the Application.
- * @param releaseChannel ReleaseChannel for which we need to make all the releases as non-default ones.
- * @param tenantId ID of the tenant.
- * @throws DBConnectionException Database Connection Exception.
- * @throws SQLException SQL Exception.
- */
- private void removeDefaultReleases(String uuid, String releaseChannel, int tenantId)
- throws DBConnectionException, SQLException {
- PreparedStatement statement = null;
- try {
- Connection connection = this.getDBConnection();
- String sql = "UPDATE APPM_APPLICATION_RELEASE SET IS_DEFAULT = FALSE WHERE APPM_APPLICATION_ID = (SELECT "
- + "ID from APPM_APPLICATION WHERE UUID = ? AND TENANT_ID = ?) AND RELEASE_CHANNEL = ?";
- statement = connection.prepareStatement(sql);
- statement.setString(1, uuid);
- statement.setInt(2, tenantId);
- statement.setString(3, releaseChannel.toUpperCase());
- statement.executeUpdate();
- } finally {
- Util.cleanupResources(statement, null);
- }
- }
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/OracleApplicationDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/OracleApplicationDAOImpl.java
index b35a8219cb..2769c5a678 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/OracleApplicationDAOImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/application/release/OracleApplicationDAOImpl.java
@@ -31,46 +31,46 @@ import java.sql.SQLException;
*/
public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl {
- @Override
- protected PreparedStatement generateGetApplicationsStatement(Filter filter, Connection conn,
- int tenantId) throws SQLException {
- int index = 0;
- String sql = "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_ID, "
- + "CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, "
- + "LS.DESCRIPTION AS LS_DESCRIPTION " + "FROM APPM_APPLICATION APP " + "INNER JOIN APPM_PLATFORM APL "
- + "ON APP.PLATFORM_ID = APL.ID " + "INNER JOIN APPM_APPLICATION_CATEGORY CAT "
- + "ON APP.APPLICATION_CATEGORY_ID = CAT.ID " + "INNER JOIN APPM_LIFECYCLE_STATE LS "
- + "ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE APP.TENANT_ID = ? ";
-
- String userName = filter.getUserName();
- if (!userName.equals("ALL")) {
- sql += " AND APP.CREATED_BY = ? ";
- }
- if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
- sql += "AND LOWER (APP.NAME) ";
- if (filter.isFullMatch()) {
- sql += "= ?";
- } else {
- sql += "LIKE ?";
- }
- }
- sql += " ORDER BY APP.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
- PreparedStatement stmt = conn.prepareStatement(sql);
- stmt.setInt(++index, tenantId);
-
- if (!userName.equals("ALL")) {
- stmt.setString(++index, userName);
- }
- if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
- if (filter.isFullMatch()) {
- stmt.setString(++index, filter.getSearchQuery().toLowerCase());
- } else {
- stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%");
- }
- }
- stmt.setInt(++index, filter.getOffset());
- stmt.setInt(++index, filter.getLimit());
- return stmt;
- }
+// @Override
+// protected PreparedStatement generateGetApplicationsStatement(Filter filter, Connection conn,
+// int tenantId) throws SQLException {
+// int index = 0;
+// String sql = "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_ID, "
+// + "CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, "
+// + "LS.DESCRIPTION AS LS_DESCRIPTION " + "FROM APPM_APPLICATION APP " + "INNER JOIN APPM_PLATFORM APL "
+// + "ON APP.PLATFORM_ID = APL.ID " + "INNER JOIN APPM_APPLICATION_CATEGORY CAT "
+// + "ON APP.APPLICATION_CATEGORY_ID = CAT.ID " + "INNER JOIN APPM_LIFECYCLE_STATE LS "
+// + "ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE APP.TENANT_ID = ? ";
+//
+// String userName = filter.getUserName();
+// if (!userName.equals("ALL")) {
+// sql += " AND APP.CREATED_BY = ? ";
+// }
+// if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
+// sql += "AND LOWER (APP.NAME) ";
+// if (filter.isFullMatch()) {
+// sql += "= ?";
+// } else {
+// sql += "LIKE ?";
+// }
+// }
+// sql += " ORDER BY APP.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
+// PreparedStatement stmt = conn.prepareStatement(sql);
+// stmt.setInt(++index, tenantId);
+//
+// if (!userName.equals("ALL")) {
+// stmt.setString(++index, userName);
+// }
+// if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
+// if (filter.isFullMatch()) {
+// stmt.setString(++index, filter.getSearchQuery().toLowerCase());
+// } else {
+// stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%");
+// }
+// }
+// stmt.setInt(++index, filter.getOffset());
+// stmt.setInt(++index, filter.getLimit());
+// return stmt;
+// }
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/category/GenericCategoryDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/category/GenericCategoryDAOImpl.java
deleted file mode 100644
index 75b3766cb3..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/category/GenericCategoryDAOImpl.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * 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.application.mgt.core.dao.impl.category;
-
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
-import org.wso2.carbon.device.application.mgt.core.dao.CategoryDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This is the concrete implementation of {@link CategoryDAO}.
- */
-public class GenericCategoryDAOImpl extends AbstractDAOImpl implements CategoryDAO {
- @Override
- public Category addCategory(Category category) throws ApplicationManagementDAOException {
- Connection connection;
- PreparedStatement statement = null;
- String sql = "INSERT INTO APPM_APPLICATION_CATEGORY (NAME, DESCRIPTION) VALUES (?, ?)";
- String[] generatedColumns = { "ID" };
- ResultSet rs = null;
- try {
- connection = this.getDBConnection();
- statement = connection.prepareStatement(sql, generatedColumns);
- statement.setString(1, category.getName());
- statement.setString(2, category.getDescription());
- statement.executeUpdate();
- rs = statement.getGeneratedKeys();
- if (rs.next()) {
- category.setId(rs.getInt(1));
- }
- return category;
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException(
- "Database connection while trying to update the categroy " + category.getName(), e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("SQL exception while executing the query '" + sql + "' .", e);
- } finally {
- Util.cleanupResources(statement, rs);
- }
- }
-
- @Override
- public List getCategories() throws ApplicationManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "SELECT * FROM APPM_APPLICATION_CATEGORY";
- List categories = new ArrayList<>();
- try {
- conn = this.getDBConnection();
- stmt = conn.prepareStatement(sql);
- rs = stmt.executeQuery();
- while (rs.next()) {
- Category category = new Category();
- category.setId(rs.getInt("ID"));
- category.setName(rs.getString("NAME"));
- category.setDescription(rs.getString("DESCRIPTION"));
- categories.add(category);
- }
- return categories;
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Database Connection Exception while trying to get the "
- + "application categories", e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("SQL Exception while trying to get the application "
- + "categories, while executing " + sql, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
-
- }
-
- @Override
- public Category getCategory(String name) throws ApplicationManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "SELECT * FROM APPM_APPLICATION_CATEGORY WHERE NAME = ?";
- try {
- conn = this.getDBConnection();
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, name);
- rs = stmt.executeQuery();
- if (rs.next()) {
- Category category = new Category();
- category.setId(rs.getInt("ID"));
- category.setName(rs.getString("NAME"));
- category.setDescription(rs.getString("DESCRIPTION"));
- return category;
- }
- return null;
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Database Connection Exception while trying to get the "
- + "application categories", e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException("SQL Exception while trying to get the application "
- + "categories, while executing " + sql, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- }
-
- @Override
- public void deleteCategory(String name) throws ApplicationManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- String sql = "DELETE FROM APPM_APPLICATION_CATEGORY WHERE NAME = ?";
- try {
- conn = this.getDBConnection();
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, name);
- stmt.executeUpdate();
- } catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException(
- "Database Connection Exception while trying to delete the category " + name, e);
- } catch (SQLException e) {
- throw new ApplicationManagementDAOException(
- "SQL Exception while trying to delete the category " + name + " while executing the query " +
- sql, e);
- } finally {
- Util.cleanupResources(stmt, null);
- }
- }
-
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateImpl.java
index dcadb97a30..216a95a1e3 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/lifecyclestate/GenericLifecycleStateImpl.java
@@ -24,7 +24,7 @@ import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
+import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
@@ -39,61 +39,70 @@ import java.util.List;
public class GenericLifecycleStateImpl extends AbstractDAOImpl implements LifecycleStateDAO {
@Override
- public LifecycleState getLifeCycleStateByIdentifier(String identifier) throws ApplicationManagementDAOException {
+ public LifecycleState getLatestLifeCycleStateByReleaseID(int identifier) throws ApplicationManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
- String sql = "SELECT * FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ? ";
+ String sql = "SELECT ID, CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM "
+ + "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID=? ORDER BY UPDATED_AT DESC;";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, identifier);
+ stmt.setInt(1, identifier);
rs = stmt.executeQuery();
-
LifecycleState lifecycleState = null;
if (rs.next()) {
lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("ID"));
- lifecycleState.setName(rs.getString("NAME"));
- lifecycleState.setIdentifier(rs.getString("IDENTIFIER"));
- lifecycleState.setDescription(rs.getString("DESCRIPTION"));
+ lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
+ lifecycleState.setPreviousState(rs.getString("PREVIOUSE_STATE"));
+ lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
+ lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
}
return lifecycleState;
} catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while getting application List", e);
} catch (DBConnectionException e) {
- throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection.", e);
+ throw new ApplicationManagementDAOException("Error occurred while obtaining the DB connection to get latest"
+ + " lifecycle state for a specific application", e);
} finally {
Util.cleanupResources(stmt, rs);
}
}
@Override
- public List getLifecycleStates() throws DAOException {
+ public List getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException {
List lifecycleStates = new ArrayList<>();
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
+ int index = 0;
try {
conn = this.getDBConnection();
- String sql = "SELECT IDENTIFIER, NAME, DESCRIPTION FROM APPM_LIFECYCLE_STATE";
+ String sql = "SELECT ID, CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_AT, UPDATED_BY FROM "
+ + "AP_APP_LIFECYCLE_STATE WHERE AP_APP_RELEASE_ID = ? ORDER BY UPDATED_AT ASC;";
stmt = conn.prepareStatement(sql);
+ stmt.setInt(++index,appReleaseId);
rs = stmt.executeQuery();
while (rs.next()) {
LifecycleState lifecycleState = new LifecycleState();
- lifecycleState.setIdentifier(rs.getString("IDENTIFIER"));
- lifecycleState.setName(rs.getString("NAME"));
- lifecycleState.setDescription(rs.getString("DESCRIPTION"));
+ lifecycleState.setId(rs.getInt("ID"));
+ lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
+ lifecycleState.setPreviousState(rs.getString("PREVIOUSE_STATE"));
+ lifecycleState.setTenantId(rs.getInt("TENANT_ID"));
+ lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
+ lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
lifecycleStates.add(lifecycleState);
}
} catch (DBConnectionException e) {
- throw new DAOException("Error occurred while obtaining the DB connection.", e);
+ throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection when getting "
+ + "lifecycle states for an application", e);
} catch (SQLException e) {
- throw new DAOException("Error occurred while retrieving lifecycle states.", e);
+ throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e);
} finally {
Util.cleanupResources(stmt, rs);
}
@@ -101,44 +110,47 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
}
@Override
- public void addLifecycleState(LifecycleState state) throws DAOException {
+ public void addLifecycleState(LifecycleState state) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
- ResultSet rs = null;
try {
conn = this.getDBConnection();
- String sql = "INSERT INTO APPM_LIFECYCLE_STATE ('NAME', 'IDENTIFIER', 'DESCRIPTION') VALUES (?, ?, ?)";
+ String sql = "INSERT INTO AP_APP_LIFECYCLE_STATE (CURRENT_STATE, PREVIOUSE_STATE, TENANT_ID, UPDATED_BY, "
+ + "AP_APP_RELEASE_ID, AP_APP_ID) VALUES (?,?, ?, ?,?,?);";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, state.getName());
- stmt.setString(2, state.getIdentifier());
- stmt.setString(3, state.getDescription());
+ stmt.setString(1, state.getCurrentState());
+ stmt.setString(2, state.getPreviousState());
+ stmt.setInt(3, state.getTenantId());
+ stmt.setString(4, state.getUpdatedBy());
+ stmt.setInt(5, state.getReleaseId());
+ stmt.setInt(6, state.getAppId());
stmt.executeUpdate();
} catch (DBConnectionException e) {
- throw new DAOException("Error occurred while obtaining the DB connection.", e);
+ throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
- throw new DAOException("Error occurred while adding lifecycle: " + state.getIdentifier(), e);
+ throw new LifeCycleManagementDAOException("Error occurred while adding lifecycle: " + state.getCurrentState(), e);
} finally {
- Util.cleanupResources(stmt, rs);
+ Util.cleanupResources(stmt, null);
}
}
@Override
- public void deleteLifecycleState(String identifier) throws DAOException {
+ public void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = this.getDBConnection();
- String sql = "DELETE FROM APPM_LIFECYCLE_STATE WHERE IDENTIFIER = ?";
+ String sql = "DELETE FROM AP_APP_LIFECYCLE_STATE WHERE ID = ?";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, identifier);
+ stmt.setInt(1, identifier);
stmt.executeUpdate();
} catch (DBConnectionException e) {
- throw new DAOException("Error occurred while obtaining the DB connection.", e);
+ throw new LifeCycleManagementDAOException("Error occurred while obtaining the DB connection.", e);
} catch (SQLException e) {
- throw new DAOException("Error occurred while deleting lifecycle: " + identifier, e);
+ throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle: " + identifier, e);
} finally {
Util.cleanupResources(stmt, rs);
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java
deleted file mode 100644
index 892403abcc..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/GenericPlatformDAOImpl.java
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * 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.application.mgt.core.dao.impl.platform;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
-import org.wso2.carbon.device.application.mgt.core.dao.PlatformDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
-import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl;
-import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Generic Implementation for handling Platform management related database operations.
- */
-public class GenericPlatformDAOImpl extends AbstractDAOImpl implements PlatformDAO {
- private static Log log = LogFactory.getLog(GenericPlatformDAOImpl.class);
-
- @Override
- public int register(int tenantId, Platform platform) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- try {
- int platformId = getPlatformId(tenantId, platform.getIdentifier());
- if (platformId == -1) {
- Connection connection = this.getDBConnection();
- if (!platform.isFileBased()) {
- String insertToPlatform = "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, NAME, FILE_BASED, "
- + "DESCRIPTION, IS_SHARED, ICON_NAME, IS_DEFAULT_TENANT_MAPPING)" + " VALUES (?, ?, ?, ?, "
- + "?, ?, ?, ?)";
- preparedStatement = connection.prepareStatement(insertToPlatform);
- preparedStatement.setString(1, platform.getIdentifier());
- preparedStatement.setInt(2, tenantId);
- preparedStatement.setString(3, platform.getName());
- preparedStatement.setBoolean(4, false);
- preparedStatement.setString(5, platform.getDescription());
- preparedStatement.setBoolean(6, platform.isShared());
- preparedStatement.setString(7, platform.getIconName());
- preparedStatement.setBoolean(8, platform.isDefaultTenantMapping());
- preparedStatement.execute();
-
- platformId = getPlatformId(tenantId, platform.getIdentifier());
- String insertPlatformProps =
- "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL, "
- + "DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
-
- if (platform.getProperties() != null) {
- for (Platform.Property property : platform.getProperties()) {
- preparedStatement = connection.prepareStatement(insertPlatformProps);
- preparedStatement.setInt(1, platformId);
- preparedStatement.setString(2, property.getName());
- preparedStatement.setBoolean(3, property.isOptional());
- preparedStatement.setString(4, property.getDefaultValue());
- preparedStatement.execute();
- }
- }
- //Adding tags to the database.
- Boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
- String insertTags = "INSERT INTO APPM_PLATFORM_TAG (NAME, PLATFORM_ID) VALUES (?, ?)";
- preparedStatement = connection.prepareStatement(insertTags);
- if (platform.getTags() != null) {
- for (String tag : platform.getTags()) {
- preparedStatement.setString(1, tag);
- preparedStatement.setInt(2, platformId);
-
- if (isBatchExecutionSupported) {
- preparedStatement.addBatch();
- } else {
- preparedStatement.execute();
- }
- }
- if (isBatchExecutionSupported) {
- preparedStatement.executeBatch();
- }
- }
-
- } else {
- String insertToPlatform =
- "INSERT INTO APPM_PLATFORM (IDENTIFIER, TENANT_ID, FILE_BASED, IS_SHARED, "
- + "IS_DEFAULT_TENANT_MAPPING) VALUES (?, ?, ?, ?, ?)";
- preparedStatement = connection.prepareStatement(insertToPlatform);
- preparedStatement.setString(1, platform.getIdentifier());
- preparedStatement.setInt(2, tenantId);
- preparedStatement.setBoolean(3, true);
- preparedStatement.setBoolean(4, platform.isShared());
- preparedStatement.setBoolean(5, platform.isDefaultTenantMapping());
- preparedStatement.execute();
- }
- if (platformId == -1) {
- platformId = getPlatformId(tenantId, platform.getIdentifier());
- }
- return platformId;
- } else {
- if (!platform.isFileBased()) {
- throw new PlatformManagementDAOException(
- "Platform - " + platform.getIdentifier() + " is already registered for tenant - "
- + tenantId);
- } else {
- return platformId;
- }
- }
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Unable to obtain the connection while trying to register the platform - " + platform
- .getIdentifier() + " for tenant - " + tenantId, e);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- @Override
- public void update(int tenantId, String oldPlatformIdentifier, Platform platform)
- throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- try {
- int platformId = getPlatformId(tenantId, oldPlatformIdentifier);
- boolean isIdentifierNull = platform.getIdentifier() == null;
- boolean isNameNull = platform.getName() == null;
-
- if (platformId != -1) {
- Connection connection = this.getDBConnection();
- if (!platform.isFileBased()) {
- String insertToPlatform = "UPDATE APPM_PLATFORM SET DESCRIPTION=?, IS_SHARED=?, ICON_NAME=?, "
- + "IS_DEFAULT_TENANT_MAPPING=?";
- if (!isIdentifierNull) {
- insertToPlatform += ",IDENTIFIER = ? ";
- }
- if (!isNameNull) {
- insertToPlatform += ", NAME =?";
- }
- insertToPlatform += " WHERE ID = ?";
- preparedStatement = connection.prepareStatement(insertToPlatform);
- preparedStatement.setString(1, platform.getDescription());
- preparedStatement.setBoolean(2, platform.isShared());
- preparedStatement.setString(3, platform.getIconName());
- preparedStatement.setBoolean(4, platform.isDefaultTenantMapping());
-
- if (!isIdentifierNull && !isNameNull) {
- preparedStatement.setString(5, platform.getIdentifier());
- preparedStatement.setString(6, platform.getName());
- preparedStatement.setInt(7, platformId);
- } else if (isIdentifierNull && !isNameNull) {
- preparedStatement.setString(5, platform.getName());
- preparedStatement.setInt(6, platformId);
- } else if (!isIdentifierNull) {
- preparedStatement.setString(5, platform.getIdentifier());
- preparedStatement.setInt(6, platformId);
- } else {
- preparedStatement.setInt(5, platformId);
- }
- preparedStatement.execute();
-
- platformId = getPlatformId(tenantId, platform.getIdentifier());
- String deletePlatformProps = "DELETE FROM APPM_PLATFORM_PROPERTIES WHERE PLATFORM_ID=?";
- preparedStatement = connection.prepareStatement(deletePlatformProps);
- preparedStatement.setInt(1, platformId);
- preparedStatement.execute();
-
- String insertPlatformProps =
- "INSERT INTO APPM_PLATFORM_PROPERTIES (PLATFORM_ID, PROP_NAME, OPTIONAL,"
- + " DEFAULT_VALUE) VALUES ( ? , ?, ? , ?)";
-
- if (platform.getProperties() != null) {
- for (Platform.Property property : platform.getProperties()) {
- preparedStatement = connection.prepareStatement(insertPlatformProps);
- preparedStatement.setInt(1, platformId);
- preparedStatement.setString(2, property.getName());
- preparedStatement.setBoolean(3, property.isOptional());
- preparedStatement.setString(4, property.getDefaultValue());
- preparedStatement.execute();
- }
- }
- } else if (!isIdentifierNull) {
- String insertToPlatform = "UPDATE APPM_PLATFORM SET IDENTIFIER = ? WHERE ID = ?";
- preparedStatement = connection.prepareStatement(insertToPlatform);
- preparedStatement.setString(1, platform.getIdentifier());
- preparedStatement.setInt(2, platformId);
- preparedStatement.execute();
- }
- } else {
- throw new PlatformManagementDAOException(
- "Cannot find any platform that was registered with identifier - " + platform.getIdentifier()
- + " for tenant - " + tenantId);
- }
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error while executing the SQL query. ", e);
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Unable to obtain the connection while trying to register the platform - " + platform
- .getIdentifier() + " for tenant - " + tenantId, e);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- private int getPlatformId(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- String query = SQLQueries.queryToGetPlatformId;
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(query);
- preparedStatement.setInt(1, tenantId);
- preparedStatement.setString(2, platformIdentifier);
- preparedStatement.setString(3, platformIdentifier);
- resultSet = preparedStatement.executeQuery();
- if (resultSet.next()) {
- return resultSet.getInt("ID");
- }
- return -1;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Error when trying to obtaining the database connection.", e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error in executing the query - " + query, e);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- @Override
- public void unregister(int tenantId, String platformIdenfier, boolean isFileBased)
- throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- String deletePlatform = null;
- try {
- Platform platform = getPlatform(tenantId, platformIdenfier);
-
- if (platform != null) {
- if (isFileBased == platform.isFileBased()) {
- Connection connection = this.getDBConnection();
- deletePlatform = "DELETE FROM APPM_PLATFORM WHERE ID = ?";
- preparedStatement = connection.prepareStatement(deletePlatform);
- preparedStatement.setInt(1, platform.getId());
- preparedStatement.execute();
- } else {
- if (isFileBased) {
- throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
- + " is not a file based platform. Try to remove that using PlatformManagement APIs");
- } else {
- throw new PlatformManagementDAOException("Platform with identifier - " + platformIdenfier
- + " is a file based platform. Try to remove that by un-deploying the relevant file.");
- }
- }
- } else {
- throw new PlatformManagementDAOException(
- "Platform identifier - " + platformIdenfier + " is not registered for tenant - " + tenantId);
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Unable to obtain the connection while trying to register the platform - " + platformIdenfier
- + " for tenant - " + tenantId, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error while executing the SQL query : " + deletePlatform + " "
- + "while trying to un-register the platform with identifier " + platformIdenfier, e);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- public void addMapping(int tenantId, List platformIdentifiers) throws PlatformManagementDAOException {
- String insertMapping = "INSERT INTO APPM_PLATFORM_TENANT_MAPPING(TENANT_ID, PLATFORM_ID) VALUES (?, ?)";
- PreparedStatement preparedStatement = null;
- try {
- for (String platformIdentifier : platformIdentifiers) {
- if (getTenantPlatformMapping(tenantId, platformIdentifier) == -1) {
- int platformId = getPlatformId(tenantId, platformIdentifier);
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(insertMapping);
- preparedStatement.setInt(1, tenantId);
- preparedStatement.setInt(2, platformId);
- preparedStatement.execute();
- } else {
- log.error("Platform identifier - " + platformIdentifier + " is already assigned to tenant domain"
- + " - " + tenantId);
- }
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Error occurred when getting the connection for the database. ",
- e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + insertMapping,
- e);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- private int getTenantPlatformMapping(int tenantId, String platformIdentifier)
- throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- String getMapping = "SELECT MAPPING.ID as ID FROM (SELECT ID, PLATFORM_ID FROM APPM_PLATFORM_TENANT_MAPPING "
- + "WHERE TENANT_ID=?) MAPPING JOIN (SELECT ID FROM APPM_PLATFORM WHERE APPM_PLATFORM.IDENTIFIER=?) "
- + "PLATFORM ON MAPPING.PLATFORM_ID=PLATFORM.ID";
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(getMapping);
- preparedStatement.setInt(1, tenantId);
- preparedStatement.setString(2, platformIdentifier);
- resultSet = preparedStatement.executeQuery();
- if (resultSet.next()) {
- return resultSet.getInt("ID");
- }
- return -1;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Error occurred while obtaining the connection to get the existing " + "Tenant - Platform Mapping.",
- e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occured while executing the SQL query - " + getMapping, e);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- @Override
- public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException {
- String deleteMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE ID = ?";
- PreparedStatement preparedStatement = null;
- try {
- int mappingId = getTenantPlatformMapping(tenantId, platformIdentifier);
- if (mappingId != -1) {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(deleteMapping);
- preparedStatement.setInt(1, mappingId);
- preparedStatement.execute();
- } else {
- throw new PlatformManagementDAOException(
- "Platform - " + platformIdentifier + " is already unassigned for tenant - " + tenantId);
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Error occurred while unassigning the platform - " + platformIdentifier + " for tenant - "
- + tenantId);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occurred while executing the query - " + deleteMapping);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- @Override
- public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- int platformId = getPlatformId(MultitenantConstants.SUPER_TENANT_ID, platformIdentifier);
- String getMapping = "DELETE FROM APPM_PLATFORM_TENANT_MAPPING WHERE TENANT_ID != ? AND PLATFORM_ID=?";
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(getMapping);
- preparedStatement.setInt(1, MultitenantConstants.SUPER_TENANT_ID);
- preparedStatement.setInt(2, platformId);
- preparedStatement.execute();
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Error occurred while obtaining the connection to remove existing " + "Tenant - Platform Mapping"
- + " for the platform : " + platformIdentifier, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occurred while executing the SQL query - " + getMapping, e);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- @Override
- public List getPlatforms(int tenantId) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
-
- if (log.isDebugEnabled()) {
- log.debug("GetPlaforms request received for the tenant ID " + tenantId);
- }
- String selectQuery = SQLQueries.queryToGetPlatforms;
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(selectQuery);
- preparedStatement.setInt(1, tenantId);
- preparedStatement.setInt(2, tenantId);
- resultSet = preparedStatement.executeQuery();
- List platforms = new ArrayList<>();
- if (log.isDebugEnabled()) {
- log.debug("Platform retrieved for the tenant Id " + tenantId);
- }
- while (resultSet.next()) {
- int mappingID = resultSet.getInt(1);
- String identifier = resultSet.getString(2);
- Platform platform = getPlatform(tenantId, identifier);
- if (mappingID != 0) {
- platform.setEnabled(true);
- } else {
- platform.setEnabled(false);
- }
- platforms.add(platform);
- if (log.isDebugEnabled()) {
- log.debug("Platform Identifier - " + identifier + " isEnabled - " + platform.isEnabled());
- }
- }
- if (log.isDebugEnabled()) {
- log.debug("Number of platforms available for the tenant ID - " + tenantId + " :" + platforms.size());
- }
- return platforms;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Error occurred when loading the platforms for tenant - " + tenantId, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occurred when executing query - " + selectQuery, e);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- public Platform getPlatform(String tenantDomain, String platformIdentifier) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- String platformQuery = "SELECT * FROM (SELECT * FROM APPM_PLATFORM WHERE (TENANT_DOMAIN=? AND IDENTIFIER=?) "
- + "OR (IS_SHARED = TRUE AND IDENTIFIER=?) AND FILE_BASED = FALSE ) PLATFORM "
- + "LEFT JOIN APPM_PLATFORM_PROPERTIES PROPS ON PLATFORM.ID = PROPS.PLATFORM_ID";
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(platformQuery);
- preparedStatement.setString(1, tenantDomain);
- preparedStatement.setString(2, platformIdentifier);
- preparedStatement.setString(3, platformIdentifier);
- resultSet = preparedStatement.executeQuery();
- Platform platform = new Platform();
- if (resultSet.next()) {
- platform.setId(resultSet.getInt("PLATFORM.ID"));
- platform.setIdentifier(platformIdentifier);
- platform.setName(resultSet.getString("PLATFORM.NAME"));
- platform.setIconName(resultSet.getString("PLATFORM.DESCRIPTION"));
- platform.setIconName(resultSet.getString("PLATFORM.ICON_NAME"));
- platform.setShared(resultSet.getBoolean("PLATFORM.IS_SHARED"));
- platform.setFileBased(false);
- List properties = new ArrayList<>();
- do {
- if (resultSet.getString("PROPS.PROP_NAME") != null) {
- Platform.Property property = new Platform.Property();
- property.setName(resultSet.getString("PROPS.PROP_NAME"));
- property.setOptional(resultSet.getBoolean("PROPS.OPTIONAL"));
- property.setDefaultValue(resultSet.getString("PROPS.DEFAUL_VALUE"));
- properties.add(property);
- }
- } while (resultSet.next());
- platform.setProperties(properties);
- } else {
- platform.setIdentifier(platformIdentifier);
- platform.setFileBased(true);
- }
- return platform;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Error when loading the platform - " + platformIdentifier, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error in executing the query - " + platformQuery, e);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- @Override
- public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "";
-
- try {
- conn = this.getDBConnection();
- sql = SQLQueries.queryToGetPlatform;
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, identifier);
- stmt.setInt(2, tenantId);
- stmt.setInt(3, tenantId);
- rs = stmt.executeQuery();
-
- Platform platform = null;
-
- if (rs.next()) {
- platform = new Platform();
- platform.setFileBased(rs.getBoolean(3));
- platform.setIdentifier(rs.getString(2));
- platform.setShared(rs.getBoolean(8));
- platform.setDefaultTenantMapping(rs.getBoolean(9));
- platform.setId(rs.getInt(4));
- //Getting tags
- sql = "SELECT * FROM APPM_PLATFORM_TAG WHERE PLATFORM_ID=?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, rs.getInt(4));
- ResultSet rsTags = stmt.executeQuery();
-
- List tags = new ArrayList<>();
- while (rsTags.next()) {
- tags.add(rsTags.getString("NAME"));
- }
- platform.setTags(tags);
-
- if (!platform.isFileBased()) {
- platform.setName(rs.getString(5));
- platform.setDescription(rs.getString(6));
- platform.setIconName(rs.getString(7));
- if (rs.getInt(1) != 0) {
- platform.setEnabled(true);
- } else {
- platform.setEnabled(false);
- }
- }
- }
- return platform;
- } catch (SQLException e) {
- throw new PlatformManagementDAOException(
- "Error occurred while getting platform with the identifier " + identifier + ", for the tenant : "
- + tenantId, e);
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Error occurred while obtaining the DB connection.", e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- }
-
- @Override
- public void removePlatforms(int tenantId) throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- String sql = "DELETE FROM APPM_PLATFORM WHERE TENANT_ID = ?";
-
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(sql);
- preparedStatement.setInt(1, tenantId);
- preparedStatement.executeUpdate();
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Database connection error while removing the platforms for the " + "tenant - " + tenantId);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException(
- "SQL exception while executing the query " + sql + " for " + "the tenant : " + tenantId);
- } finally {
- Util.cleanupResources(preparedStatement, null);
- }
- }
-
- @Override
- public int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId)
- throws PlatformManagementDAOException {
- PreparedStatement preparedStatement = null;
- ResultSet resultSet = null;
- String sql = SQLQueries.queryToGetSupertenantAndOwnPlatforms;
-
- try {
- Connection connection = this.getDBConnection();
- preparedStatement = connection.prepareStatement(sql);
- preparedStatement.setString(1, platformIdentifier);
- preparedStatement.setInt(2, tenantId);
- preparedStatement.setInt(3, MultitenantConstants.SUPER_TENANT_ID);
- resultSet = preparedStatement.executeQuery();
-
- if (resultSet.next()) {
- return resultSet.getInt(1);
- } else {
- return -1;
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Database connection error while removing the platfor for the " + "tenant - " + tenantId);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException(
- "SQL exception while executing the query " + sql + " for " + "the tenant : " + tenantId);
- } finally {
- Util.cleanupResources(preparedStatement, resultSet);
- }
- }
-
- @Override
- public Platform getTenantOwnedPlatform(int tenantId, String platformIdentifier)
- throws PlatformManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "";
-
- try {
- conn = this.getDBConnection();
- sql = "SELECT * from APPM_PLATFORM WHERE TENANT_ID = ? AND IDENTIFIER = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, tenantId);
- stmt.setString(2, platformIdentifier);
- rs = stmt.executeQuery();
-
- Platform platform = null;
-
- if (rs.next()) {
- platform = new Platform();
- platform.setFileBased(rs.getBoolean("FILE_BASED"));
- platform.setIdentifier(rs.getString("IDENTIFIER"));
- platform.setShared(rs.getBoolean("IS_SHARED"));
- platform.setDefaultTenantMapping(rs.getBoolean("IS_DEFAULT_TENANT_MAPPING"));
- if (!platform.isFileBased()) {
- platform.setId(rs.getInt("ID"));
- platform.setName(rs.getString("NAME"));
- platform.setDescription(rs.getString("DESCRIPTION"));
- platform.setIconName(rs.getString("ICON_NAME"));
- }
- }
- return platform;
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("Error occurred while executing the query : " + sql + " for "
- + "getting platforms owned by tenant : " + tenantId, e);
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Error occurred while obtaining the DB connection for getting " + "platforms owned by tenant : "
- + tenantId, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- }
-
- @Override
- public int getMultiTenantPlatforms(String identifier) throws PlatformManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "";
-
- try {
- conn = this.getDBConnection();
- sql = "SELECT ID from APPM_PLATFORM WHERE TENANT_ID != ? AND IDENTIFIER=?";
-
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, MultitenantConstants.SUPER_TENANT_ID);
- stmt.setString(2, identifier);
-
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- return rs.getInt(1);
- }
- return -1;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Database Connection exception while trying to get the tenants "
- + "which has the platforms with the platform identifier : " + identifier, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("SQL exception while executing the query " + sql + " to get the"
- + " tenants which has the platform with the platform identifier : " + identifier, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- }
-
- @Override
- public List getPlatformTags(String name) throws PlatformManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- String sql = "";
- List tagList = new ArrayList<>();
-
- try {
- conn = this.getDBConnection();
- sql = "SELECT NAME FROM APPM_PLATFORM_TAG WHERE NAME LIKE ?";
-
- stmt = conn.prepareStatement(sql);
- stmt.setString(1, name + "%");
- rs = stmt.executeQuery();
-
- if (rs.next()) {
- tagList.add(rs.getString("NAME"));
- }
- return tagList;
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException("Database Connection exception while trying to get the platform "
- + "tags that are starting with " + name, e);
- } catch (SQLException e) {
- throw new PlatformManagementDAOException("SQL exception while executing the query " + sql + " to get the"
- + " platform tags that are starting with " + name, e);
- } finally {
- Util.cleanupResources(stmt, rs);
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/OracleMsSQLPlatformDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/OracleMsSQLPlatformDAOImpl.java
deleted file mode 100644
index 2d9648dab4..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/OracleMsSQLPlatformDAOImpl.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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.application.mgt.core.dao.impl.platform;
-
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
-
-import java.util.List;
-
-/**
- * Oracle and MsSQL specific implementation for Platform DAO.
- */
-public class OracleMsSQLPlatformDAOImpl extends GenericPlatformDAOImpl {
-
- @Override
- public int getSuperTenantAndOwnPlatforms(String platformIdentifier, int tenantId)
- throws PlatformManagementDAOException {
- SQLQueries.queryToGetSupertenantAndOwnPlatforms = "SELECT ID from APPM_PLATFORM where IDENTIFIER "
- + "= ? AND (TENANT_ID = ? OR (TENANT_ID = ? AND IS_SHARED = 1))";
- return super.getSuperTenantAndOwnPlatforms(platformIdentifier, tenantId);
- }
-
- @Override
- public int register(int tenantId, Platform platform) throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatformId =
- "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
- + "IDENTIFIER=?)";
- return super.register(tenantId, platform);
- }
-
- @Override
- public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatform =
- "SELECT MAPPING.ID, PLATFORM.IDENTIFIER, PLATFORM.FILE_BASED, PLATFORM.ID, PLATFORM.NAME, "
- + "PLATFORM.DESCRIPTION, PLATFORM.ICON_NAME, PLATFORM.IS_SHARED, "
- + "PLATFORM.IS_DEFAULT_TENANT_MAPPING FROM (SELECT * FROM APPM_PLATFORM WHERE IDENTIFIER= ? "
- + "AND (TENANT_ID=? OR IS_SHARED = 1)) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
- + "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
- return super.getPlatform(tenantId, identifier);
- }
-
- public void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatformId =
- "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
- + "IDENTIFIER=?)";
- super.removeMappingTenants(platformIdentifier);
- }
-
- public void update(int tenantId, String oldPlatformIdentifier, Platform platform)
- throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatformId =
- "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
- + "IDENTIFIER=?)";
- super.update(tenantId, oldPlatformIdentifier, platform);
- }
-
- public void addMapping(int tenantId, List platformIdentifiers) throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatformId =
- "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = 1 AND "
- + "IDENTIFIER=?)";
- super.addMapping(tenantId, platformIdentifiers);
- }
-
- public List getPlatforms(int tenantId) throws PlatformManagementDAOException {
- SQLQueries.queryToGetPlatforms = "SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM "
- + "WHERE TENANT_ID=? OR IS_SHARED = 1) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
- + "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
- return super.getPlatforms(tenantId);
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/SQLQueries.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/SQLQueries.java
deleted file mode 100644
index 73eab98ac4..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/platform/SQLQueries.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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.application.mgt.core.dao.impl.platform;
-
-/**
- * SQL Queries specific to Platform.
- */
-public class SQLQueries {
- static String queryToGetSupertenantAndOwnPlatforms = "SELECT ID from APPM_PLATFORM where IDENTIFIER "
- + "= ? AND (TENANT_ID = ? OR (TENANT_ID = ? AND IS_SHARED = true))";
- static String queryToGetPlatformId =
- "SELECT ID FROM APPM_PLATFORM WHERE (TENANT_ID=? AND IDENTIFIER=?) OR (IS_SHARED = TRUE AND "
- + "IDENTIFIER=?)";
- static String queryToGetPlatform =
- "SELECT MAPPING.ID, PLATFORM.IDENTIFIER, PLATFORM.FILE_BASED, PLATFORM.ID, PLATFORM.NAME, PLATFORM"
- + ".DESCRIPTION, PLATFORM.ICON_NAME, PLATFORM.IS_SHARED, PLATFORM.IS_DEFAULT_TENANT_MAPPING FROM "
- + "(SELECT * FROM APPM_PLATFORM WHERE IDENTIFIER= ? AND (TENANT_ID=? OR IS_SHARED = TRUE)) "
- + "PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID "
- + "AND MAPPING.TENANT_ID = ?";
- static String queryToGetPlatforms = "SELECT MAPPING.ID, PLATFORM.IDENTIFIER FROM (SELECT * FROM APPM_PLATFORM "
- + "WHERE TENANT_ID=? OR IS_SHARED = TRUE ) PLATFORM LEFT JOIN APPM_PLATFORM_TENANT_MAPPING "
- + "MAPPING ON PLATFORM.ID = MAPPING.PLATFORM_ID AND MAPPING.TENANT_ID = ?";
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java
index 06e9902d8b..d5f0dadf72 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/dao/impl/visibility/GenericVisibilityDAOImpl.java
@@ -17,7 +17,9 @@
*/
package org.wso2.carbon.device.application.mgt.core.dao.impl.visibility;
-import org.wso2.carbon.device.application.mgt.common.Visibility;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util;
@@ -36,121 +38,106 @@ import java.util.List;
*/
public class GenericVisibilityDAOImpl extends AbstractDAOImpl implements VisibilityDAO {
+ private static final Log log = LogFactory.getLog(GenericVisibilityDAOImpl.class);
+
@Override
- public int getVisibilityID(Visibility.Type visibilityType) throws VisibilityManagementDAOException {
+ public void addUnrestrictedRoles(List unrestrictedRoles, int applicationId, int tenantId) throws
+ VisibilityManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Request received in DAO Layer to add unrestricted roles");
+ }
+ Connection conn;
PreparedStatement stmt = null;
- ResultSet resultSet = null;
- try {
- Connection connection = getDBConnection();
- String sql = "SELECT ID FROM APPM_RESOURCE_TYPE WHERE NAME = ?";
- stmt = connection.prepareStatement(sql);
- stmt.setString(1, visibilityType.toString().toUpperCase());
- resultSet = stmt.executeQuery();
- if (resultSet.next()) {
- return resultSet.getInt("ID");
+ ResultSet rs = null;
+ int index = 0;
+ String sql = "INSERT INTO AP_UNRESTRICTED_ROLES (ROLE, TENANT_ID, AP_APP_ID) VALUES (?, ?, ?)";
+ try{
+ conn = this.getDBConnection();
+ conn.setAutoCommit(false);
+ stmt = conn.prepareStatement(sql);
+ for (UnrestrictedRole role : unrestrictedRoles) {
+ stmt.setString(++index, role.getRole());
+ stmt.setInt(++index, tenantId);
+ stmt.setInt(++index, applicationId);
+ stmt.addBatch();
}
- return -1;
- } catch (DBConnectionException e) {
- throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " +
- "for the visibility management of applications", e);
- } catch (SQLException e) {
- throw new VisibilityManagementDAOException("Error occurred when trying to get the ID of the" +
- " visibility type - " + visibilityType.toString(), e);
+ stmt.executeBatch();
+
+ }catch (DBConnectionException e) {
+ throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
+ }catch (SQLException e) {
+ throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally {
- Util.cleanupResources(stmt, resultSet);
+ Util.cleanupResources(stmt, rs);
}
}
@Override
- public void add(int applicationID, int visibilityTypeID, List allowedList)
- throws VisibilityManagementDAOException {
+ public List getUnrestrictedRoles(int applicationId, int tenantId) throws VisibilityManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Request received in DAO Layer to get unrestricted roles");
+ }
+ Connection conn;
PreparedStatement stmt = null;
- try {
- Connection connection = getDBConnection();
- String sql = "INSERT INTO APPM_VISIBILITY (VALUE, RESOURCE_TYPE_ID, APPLICATION_ID) VALUES (?, ?, ?)";
- stmt = connection.prepareStatement(sql);
- if (allowedList == null) {
- stmt.setString(1, null);
- stmt.setInt(2, visibilityTypeID);
- stmt.setInt(3, applicationID);
- stmt.execute();
- } else {
- for (String allowed : allowedList) {
- stmt.setString(1, allowed);
- stmt.setInt(2, visibilityTypeID);
- stmt.setInt(3, applicationID);
- stmt.addBatch();
- }
- stmt.executeBatch();
+ ResultSet rs = null;
+ List unrestrictedRoles = new ArrayList<>();
+ UnrestrictedRole unrestrictedRole = null;
+ int index = 0;
+ String sql = "SELECT ID, ROLE FROM AP_UNRESTRICTED_ROLES WHERE AP_APP_ID = ? AND TENANT_ID = ?;";
+ try{
+ conn = this.getDBConnection();
+ conn.setAutoCommit(false);
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(++index, applicationId);
+ stmt.setInt(++index, tenantId);
+ rs = stmt.executeQuery();
+
+ while (rs.next()){
+ unrestrictedRole = new UnrestrictedRole();
+ unrestrictedRole.setId(rs.getInt("ID"));
+ unrestrictedRole.setRole(rs.getString("ROLE"));
+ unrestrictedRoles.add(unrestrictedRole);
}
- } catch (DBConnectionException e) {
- throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " +
- "for adding the visibility mapping for the application ID - " + applicationID, e);
- } catch (SQLException e) {
- throw new VisibilityManagementDAOException("Error occurred while adding the visibility mapping " +
- "for the application ID - " + applicationID, e);
+ return unrestrictedRoles;
+
+ }catch (DBConnectionException e) {
+ throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
+ }catch (SQLException e) {
+ throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally {
- Util.cleanupResources(stmt, null);
+ Util.cleanupResources(stmt, rs);
}
}
@Override
- public void delete(int applicationId) throws VisibilityManagementDAOException {
- PreparedStatement stmt = null;
- try {
- Connection connection = getDBConnection();
- String sql = "DELETE FROM APPM_VISIBILITY WHERE APPLICATION_ID = ?";
- stmt = connection.prepareStatement(sql);
- stmt.setInt(1, applicationId);
- stmt.execute();
- } catch (DBConnectionException e) {
- throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " +
- "for deleting the visibility mapping for the application ID - " + applicationId, e);
- } catch (SQLException e) {
- throw new VisibilityManagementDAOException("Error occurred while deleting the visibility mapping " +
- "for the application ID - " + applicationId, e);
- } finally {
- Util.cleanupResources(stmt, null);
+ public void deleteUnrestrictedRoles(List unrestrictedRoles, int applicationId, int tenantId) throws VisibilityManagementDAOException {
+ if (log.isDebugEnabled()) {
+ log.debug("Request received in DAO Layer to delete unrestricted roles");
}
- }
-
- public Visibility get(int applicationId) throws VisibilityManagementDAOException {
+ Connection conn;
PreparedStatement stmt = null;
- ResultSet resultSet = null;
- final String visibilityTypeColumn = "VISIBILITY_TYPE";
- final String allowedValColumn = "ALLOWED_VAL";
- try {
- Connection connection = getDBConnection();
- String sql = "SELECT APPM_VISIBILITY.VALUE as " + allowedValColumn + ", APPM_RESOURCE_TYPE.NAME AS " +
- visibilityTypeColumn + " FROM APPM_VISIBILITY JOIN APPM_RESOURCE_TYPE " +
- "ON APPM_VISIBILITY.RESOURCE_TYPE_ID = APPM_RESOURCE_TYPE.ID " +
- "WHERE APPM_VISIBILITY.APPLICATION_ID = ?";
- stmt = connection.prepareStatement(sql);
- stmt.setInt(1, applicationId);
- resultSet = stmt.executeQuery();
- Visibility visibility = new Visibility();
- List allowedVal = new ArrayList<>();
- while (resultSet.next()) {
- if (visibility.getType() == null) {
- visibility.setType(Visibility.Type.valueOf(resultSet.getString(visibilityTypeColumn)));
- }
- String val = resultSet.getString(allowedValColumn);
- if (val != null) {
- allowedVal.add(val);
- }
+ ResultSet rs = null;
+ int index = 0;
+ String sql = "DELETE FROM AP_UNRESTRICTED_ROLES WHERE AP_APP_ID = 1 AND ROLE = 'role1' AND TENANT_ID = -1234;";
+ try{
+ conn = this.getDBConnection();
+ conn.setAutoCommit(false);
+ stmt = conn.prepareStatement(sql);
+
+ for (UnrestrictedRole role : unrestrictedRoles) {
+ stmt.setInt(++index, applicationId);
+ stmt.setString(++index, role.getRole());
+ stmt.setInt(++index, role.getTenantId());
+ stmt.addBatch();
}
- if (!allowedVal.isEmpty()) {
- visibility.setAllowedList(allowedVal);
- }
- return visibility;
- } catch (DBConnectionException e) {
- throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " +
- "for getting the visibility mapping for the application ID - " + applicationId, e);
- } catch (SQLException e) {
- throw new VisibilityManagementDAOException("Error occurred while getting the visibility mapping " +
- "for the application ID - " + applicationId, e);
+ stmt.executeBatch();
+
+ }catch (DBConnectionException e) {
+ throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
+ }catch (SQLException e) {
+ throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally {
- Util.cleanupResources(stmt, resultSet);
+ Util.cleanupResources(stmt, rs);
}
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/Platform.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/Platform.java
deleted file mode 100644
index 104a82ffd8..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/Platform.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
-* 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.application.mgt.core.deployer;
-
-import java.util.List;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlRootElement;
-
-/**
- * Platform represents an Application Platform such as Android, IOS, etc.
- */
-@XmlRootElement(name = "Platform")
-public class Platform {
-
- private String id;
- private String name;
- private String description;
- private String icon;
- private boolean shared;
- private boolean tenantMapping;
- private List properties;
-
- @XmlAttribute(name = "id")
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- @XmlAttribute(name = "name")
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @XmlElement(name = "Property")
- public List getProperties() {
- return properties;
- }
-
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public void setProperties(List properties) {
- this.properties = properties;
- }
-
- @XmlAttribute(name = "icon")
- public String getIcon() {
- return icon;
- }
-
- public void setIcon(String icon) {
- this.icon = icon;
- }
-
- @XmlAttribute(name = "isShared")
- public boolean isShared() {
- return shared;
- }
-
- public void setShared(boolean shared) {
- this.shared = shared;
- }
-
- @XmlAttribute(name = "tenantMapping")
- public boolean isTenantMapping() {
- return tenantMapping;
- }
-
- public void setTenantMapping(boolean tenantMapping) {
- this.tenantMapping = tenantMapping;
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/PlatformDeployer.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/PlatformDeployer.java
deleted file mode 100644
index d03d3e82bd..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/deployer/PlatformDeployer.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
-* 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.application.mgt.core.deployer;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.axis2.deployment.AbstractDeployer;
-import org.apache.axis2.deployment.DeploymentException;
-import org.apache.axis2.deployment.repository.util.DeploymentFileData;
-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.application.mgt.common.exception.PlatformManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
-import org.wso2.carbon.device.application.mgt.core.util.Constants;
-import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBException;
-import javax.xml.bind.Unmarshaller;
-
-/**
- * PlatformDeployer is responsible for deploying platforms that are added in the filesystem.
- * This will deploy the platforms that are added in /repository/deployment/server/platforms directory.
- */
-public class PlatformDeployer extends AbstractDeployer {
-
- private static final Log log = LogFactory.getLog(PlatformDeployer.class);
-
- @Override
- public void init(ConfigurationContext configurationContext) {
- File deployementDir = new File(
- MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext().
- getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME);
- if (!deployementDir.exists()) {
- if (!deployementDir.mkdir()) {
- log.warn("Unable to create the deployment dir at: " + deployementDir.getPath());
- }
- }
- }
-
- @Override
- public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
- File deploymentFile = new File(deploymentFileData.getAbsolutePath());
- try {
- JAXBContext jaxbContext = JAXBContext.newInstance(Platform.class);
- Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
- Platform platformConf = (Platform) unmarshaller.unmarshal(deploymentFile);
- if (platformConf.getId().contentEquals(getPlatformID(deploymentFile.getName()))) {
- org.wso2.carbon.device.application.mgt.common.Platform platform = convert(platformConf);
- PlatformManager platformManager = DataHolder.getInstance().getPlatformManager();
- int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
-
- org.wso2.carbon.device.application.mgt.common.Platform existingPlatform = platformManager
- .getPlatform(tenantID, platform.getIdentifier());
- if (existingPlatform != null && existingPlatform.isFileBased()) {
- platformManager.update(tenantID, platformConf.getId(), platform);
- log.info("Platform configuration : " + deploymentFile.getName() + " updated successfully");
- } else {
- platformManager.register(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platform);
- log.info("Platform configuration : " + deploymentFile.getName() + " deployed successfully");
- }
- } else {
- log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath()
- + "!. Platform config file name - " + deploymentFile.getName()
- + " should match with the 'id' provided within the platform configuration!");
- }
- } catch (JAXBException e) {
- log.error("Platform configuration file - " + deploymentFile.getAbsolutePath() + " is invalid!", e);
- } catch (PlatformManagementException e) {
- log.error("Unable to deploy the platform - " + deploymentFile.getAbsolutePath(), e);
- }
- }
-
- @Override
- public void undeploy(String fileName) throws DeploymentException {
- String platformId = getPlatformID(fileName);
- try {
- DataHolder.getInstance().getPlatformManager()
- .unregister(CarbonContext.getThreadLocalCarbonContext().getTenantId(), platformId, true);
- log.info("Platform configuration : " + fileName + " un-deployed successfully");
- } catch (PlatformManagementException e) {
- log.error("Error occurred while un-deploying the platform - " + fileName, e);
- }
- }
-
- private static String getPlatformID(String deploymentFileName) {
- if (deploymentFileName.contains(Constants.PLATFORM_DEPLOYMENT_EXT)) {
- return deploymentFileName.substring(0, deploymentFileName.length() -
- Constants.PLATFORM_DEPLOYMENT_EXT.length());
- }
- return deploymentFileName;
- }
-
- private org.wso2.carbon.device.application.mgt.common.Platform convert(Platform platformConfig) {
- org.wso2.carbon.device.application.mgt.common.Platform platform =
- new org.wso2.carbon.device.application.mgt.common.Platform();
- platform.setIdentifier(platformConfig.getId());
- platform.setName(platformConfig.getName());
- platform.setDescription(platformConfig.getDescription());
- platform.setIconName(platformConfig.getIcon());
- platform.setFileBased(true);
- platform.setShared(platformConfig.isShared());
- platform.setDefaultTenantMapping(platformConfig.isTenantMapping());
- platform.setEnabled(false);
- List properties = new ArrayList<>();
-
- if (platformConfig.getProperties() != null) {
- for (Property propertyConfig : platformConfig.getProperties()) {
- org.wso2.carbon.device.application.mgt.common.Platform.Property property =
- new org.wso2.carbon.device.application.mgt.common.Platform.Property();
- property.setName(propertyConfig.getName());
- property.setDefaultValue(propertyConfig.getDefaultValue());
- property.setOptional(propertyConfig.isOptional());
- properties.add(property);
- }
- }
- platform.setProperties(properties);
- return platform;
- }
-
- @Override
- public void setDirectory(String s) {
- }
-
- @Override
- public void setExtension(String s) {
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/DAOException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/LifeCycleManagementDAOException.java
similarity index 81%
rename from components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/DAOException.java
rename to components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/LifeCycleManagementDAOException.java
index 82fb6e1530..ae829645c9 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/DAOException.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/LifeCycleManagementDAOException.java
@@ -20,13 +20,13 @@ package org.wso2.carbon.device.application.mgt.core.exception;
/**
* This exception will be thrown when there is an issue with Lifecycle related DAO operations.
*/
-public class DAOException extends Exception {
+public class LifeCycleManagementDAOException extends Exception {
- public DAOException(String message) {
+ public LifeCycleManagementDAOException(String message) {
super(message);
}
- public DAOException(String message, Throwable cause) {
+ public LifeCycleManagementDAOException(String message, Throwable cause) {
super(message, cause);
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/PlatformManagementDAOException.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/PlatformManagementDAOException.java
deleted file mode 100644
index 0cd87944de..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/exception/PlatformManagementDAOException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-* 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.application.mgt.core.exception;
-
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-
-/**
- * Exception that will be thrown when there is a issue during Platform level DAO operations.
- */
-public class PlatformManagementDAOException extends PlatformManagementException {
-
- public PlatformManagementDAOException(String message, Throwable ex) {
- super(message, ex);
- }
-
- public PlatformManagementDAOException(String message) {
- super(message);
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java
index a9d5117942..3c47908545 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationManagerImpl.java
@@ -21,35 +21,29 @@ package org.wso2.carbon.device.application.mgt.core.impl;
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.context.PrivilegedCarbonContext;
-import org.wso2.carbon.device.application.mgt.common.Application;
-import org.wso2.carbon.device.application.mgt.common.ApplicationList;
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.Filter;
-import org.wso2.carbon.device.application.mgt.common.Lifecycle;
-import org.wso2.carbon.device.application.mgt.common.LifecycleState;
-import org.wso2.carbon.device.application.mgt.common.LifecycleStateTransition;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.User;
-import org.wso2.carbon.device.application.mgt.common.Visibility;
+import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.core.dao.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
+import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.exception.ValidationException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
+import org.wso2.carbon.device.mgt.core.dao.*;
+import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.ArrayList;
-import java.util.Date;
import java.util.List;
+import java.sql.Timestamp;
+import java.util.Date;
/**
* Default Concrete implementation of Application Management related implementations.
@@ -57,290 +51,261 @@ import java.util.List;
public class ApplicationManagerImpl implements ApplicationManager {
private static final Log log = LogFactory.getLog(ApplicationManagerImpl.class);
- private static final String CREATED = "CREATED";
+ private DeviceTypeDAO deviceTypeDAO;
+ private VisibilityDAO visibilityDAO;
+ private LifecycleStateDAO lifecycleStateDAO;
+ private ApplicationDAO applicationDAO;
- @Override
- public Application createApplication(Application application) throws ApplicationManagementException {
- application.setUser(new User(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(),
- PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true)));
+ public ApplicationManagerImpl() {
+ initDataAccessObjects();
+ }
+
+ private void initDataAccessObjects() {
+ this.deviceTypeDAO = ApplicationManagementDAOFactory.getDeviceTypeDAO();
+ this.visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
+ this.lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
+ this.applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
+ }
+
+ @Override public Application createApplication(Application application) throws ApplicationManagementException {
+
+ User loggedInUser = new User(PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(),
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true));
+ application.setUser(loggedInUser);
if (log.isDebugEnabled()) {
log.debug("Create Application received for the tenant : " + application.getUser().getTenantId() + " From"
+ " the user : " + application.getUser().getUserName());
}
- validateApplication(application);
- application.setUuid(HelperUtil.generateApplicationUuid());
- application.setCreatedAt(new Date());
- application.setModifiedAt(new Date());
- Platform platform = DataHolder.getInstance().getPlatformManager()
- .getPlatform(application.getUser().getTenantId(), application.getPlatform().getIdentifier());
- if (platform == null) {
- throw new NotFoundException("Invalid platform is provided for the application " + application.getUuid());
- }
- application.setPlatform(platform);
- Category category = DataHolder.getInstance().getCategoryManager()
- .getCategory(application.getCategory().getName());
- if (category == null) {
- throw new NotFoundException("Invalid Category is provided for the application " + application.getUuid());
- }
- application.setCategory(category);
+
+ validateAppCreatingRequest(application);
+ validateReleaseCreateRequest(application.getApplicationReleases());
+ DeviceType deviceType;
+ ApplicationRelease applicationRelease;
try {
ConnectionManagerUtil.beginDBTransaction();
- if (log.isDebugEnabled()) {
- log.debug("Application creation pre-conditions are met and the platform mentioned by identifier "
- + platform.getIdentifier() + " is found");
- }
- LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
- LifecycleState lifecycleState = lifecycleStateDAO.getLifeCycleStateByIdentifier(CREATED);
- if (lifecycleState == null) {
- ConnectionManagerUtil.commitDBTransaction();
- throw new NotFoundException("Invalid lifecycle state.");
- }
- Lifecycle lifecycle = new Lifecycle();
- lifecycle.setLifecycleState(lifecycleState);
- lifecycle.setLifecycleStateModifiedAt(new Date());
- lifecycle.setGetLifecycleStateModifiedBy(application.getUser().getUserName());
- application.setCurrentLifecycle(lifecycle);
- application = DAOFactory.getApplicationDAO().createApplication(application);
- DataHolder.getInstance().getVisibilityManager().put(application.getId(), application.getVisibility());
- ConnectionManagerUtil.commitDBTransaction();
- return application;
- } catch (ApplicationManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
+ int tenantId = application.getUser().getTenantId();
+ deviceType = this.deviceTypeDAO.getDeviceType(application.getType(), application.getUser().getTenantId());
- @Override
- public Application editApplication(Application application) throws ApplicationManagementException {
- String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- if (application.getUuid() == null) {
- throw new ValidationException("Application UUID cannot be empty");
- }
+ if (deviceType == null) {
+ log.error("Device type is not matched with application type");
+ return null;
+ }
+ application.setDevicetype(deviceType);
+ int appId = this.applicationDAO.createApplication(application, deviceType.getId());
- if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
- throw new ApplicationManagementException(
- "User " + userName + " does not have permissions to edit the " + "application with the UUID "
- + application.getUuid());
- }
- if (this.getApplication(application.getUuid()) != null) {
- if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
- throw new NotFoundException("Platform information not available with the application!");
- }
- Platform platform = DataHolder.getInstance().getPlatformManager()
- .getPlatform(tenantId, application.getPlatform().getIdentifier());
- if (platform == null) {
- throw new NotFoundException(
- "Platform specified by identifier " + application.getPlatform().getIdentifier()
- + " is not found. Please give a valid platform identifier.");
- }
- application.setPlatform(platform);
- if (application.getCategory() != null) {
- String applicationCategoryName = application.getCategory().getName();
- if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
- throw new ApplicationManagementException(
- "Application category name cannot be null or " + "empty. Cannot edit the application.");
- }
- Category category = DataHolder.getInstance().getCategoryManager()
- .getCategory(application.getCategory().getName());
- if (category == null) {
- throw new NotFoundException(
- "Invalid Category is provided for the application " + application.getUuid() + ". "
- + "Cannot edit application");
- }
- application.setCategory(category);
- }
- try {
- ConnectionManagerUtil.beginDBTransaction();
- ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
- application.setModifiedAt(new Date());
- Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
- Visibility visibility = DataHolder.getInstance().getVisibilityManager()
- .put(application.getId(), application.getVisibility());
- modifiedApplication.setVisibility(visibility);
- ConnectionManagerUtil.commitDBTransaction();
- return modifiedApplication;
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- } else {
- throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
- }
- }
-
- @Override
- public void deleteApplication(String uuid) throws ApplicationManagementException {
- String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
- throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
- + " the permission to delete the application with UUID " + uuid);
- }
- try {
- ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
- ConnectionManagerUtil.beginDBTransaction();
- int appId = applicationDAO.getApplicationId(uuid, tenantId);
if (appId != -1) {
- applicationDAO.deleteTags(appId);
- applicationDAO.deleteProperties(appId);
- DataHolder.getInstance().getVisibilityManager().remove(appId);
- applicationDAO.deleteApplication(uuid, tenantId);
+ log.error("Application creation Failed");
+ ConnectionManagerUtil.rollbackDBTransaction();
+ } else {
+ if (!application.getTags().isEmpty()) {
+ this.applicationDAO.addTags(application.getTags(), appId, tenantId);
+ }
+ if (application.getIsRestricted() == 1 && !application.getUnrestrictedRoles().isEmpty()) {
+ this.visibilityDAO.addUnrestrictedRoles(application.getUnrestrictedRoles(), appId, tenantId);
+ } else {
+ application.setIsRestricted(0);
+ }
+ ConnectionManagerUtil.commitDBTransaction();
+ applicationRelease = application.getApplicationReleases().get(0);
+ applicationRelease.setCreatedAt((Timestamp) new Date());
+ applicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO().
+ createRelease(applicationRelease, application.getId());
+ //todo add lifecycle and add this into application
}
- ConnectionManagerUtil.commitDBTransaction();
- } catch (ApplicationManagementDAOException e) {
+
+ return application;
+
+ } catch (DeviceManagementDAOException e) {
+ String msg = "Error occurred while getting device type id of " + application.getType();
+ log.error(msg, e);
+ ConnectionManagerUtil.rollbackDBTransaction();
+ throw new ApplicationManagementException(msg, e);
+ } catch (ApplicationManagementException e) {
+ String msg = "Error occurred while adding application";
+ log.error(msg, e);
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Failed to delete application: " + uuid;
throw new ApplicationManagementException(msg, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
- @Override
- public ApplicationList getApplications(Filter filter) throws ApplicationManagementException {
+ @Override public ApplicationList getApplications(Filter filter) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ ApplicationList applicationList;
+ List applicationReleases;
try {
- if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
- userName = "ALL";
- }
- } catch (UserStoreException e) {
- throw new ApplicationManagementException("User-store exception while checking whether the user " +
- userName + " of tenant " + tenantId + " has the publisher permission");
- }
- filter.setUserName(userName);
-
- try {
+ filter.setUserName(userName);
ConnectionManagerUtil.openDBConnection();
- ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
- ApplicationList applicationList = applicationDAO.getApplications(filter, tenantId);
+ applicationList = applicationDAO.getApplications(filter, tenantId);
+ if (!isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
+ applicationList = getRoleRestrictedApplicationList(applicationList, userName);
+ }
+
for (Application application : applicationList.getApplications()) {
- application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
+ applicationReleases = getReleases(application.getId());
+ application.setApplicationReleases(applicationReleases);
}
+
return applicationList;
+ } catch (UserStoreException e) {
+ throw new ApplicationManagementException(
+ "User-store exception while checking whether the user " + userName + " of tenant " + tenantId
+ + " has the publisher permission");
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
- @Override
- public void changeLifecycle(String applicationUuid, String lifecycleIdentifier) throws
- ApplicationManagementException {
- boolean isAvailableNextState = false;
- String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- List nextLifeCycles = getLifeCycleStates(applicationUuid);
-
- for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
- if (log.isDebugEnabled()) {
- log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
- + lifecycleStateTransition.getNextState());
- }
- if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
- isAvailableNextState = true;
- break;
- }
- }
- if (!isAvailableNextState) {
- throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
- + "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
- + lifecycleIdentifier);
- }
- try {
- ConnectionManagerUtil.beginDBTransaction();
- ApplicationDAO applicationDAO = DAOFactory.getApplicationDAO();
- applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public List getLifeCycleStates(String applicationUUID)
- throws ApplicationManagementException {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
- boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
-
- if (log.isDebugEnabled()) {
- log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
- + "application " + applicationUUID);
- }
+ @Override public String getUuidOfLatestRelease(int appId) throws ApplicationManagementException {
try {
ConnectionManagerUtil.openDBConnection();
- List transitions = DAOFactory.getApplicationDAO()
- .getNextLifeCycleStates(applicationUUID, tenantId);
- List filteredTransitions = new ArrayList<>();
+ return applicationDAO.getUuidOfLatestRelease(appId);
+ } finally {
+ ConnectionManagerUtil.closeDBConnection();
+ }
- if (log.isDebugEnabled()) {
- log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
- + transitions.size() + ". The number may vary according to the permission level of user : "
- + userName + " of tenant " + tenantId);
- }
- for (LifecycleStateTransition transition : transitions) {
- String permission = transition.getPermission();
- if (permission != null) {
- if (log.isDebugEnabled()) {
- log.debug("In order to make the state change to " + transition.getNextState() + " permission "
- + permission + " is required");
- }
- if (isAuthorized(userName, tenantId, permission)) {
- filteredTransitions.add(transition);
- } else {
- if (log.isDebugEnabled()) {
- log.debug("User " + userName + " does not have the permission " + permission + " to "
- + "change the life-cycle state to " + transition.getNextState() + " of the "
- + "application " + applicationUUID);
- }
- }
- } else if (isAdminOrApplicationOwner) {
- filteredTransitions.add(transition);
+ }
+
+ private boolean isRoleExists(List unrestrictedRoleList, String userName)
+ throws UserStoreException {
+ String[] roleList;
+ roleList = getRoleOfUser(userName);
+ for (UnrestrictedRole unrestrictedRole : unrestrictedRoleList) {
+ for (String role : roleList) {
+ if (unrestrictedRole.getRole().equals(role)) {
+ return true;
}
}
- if (log.isDebugEnabled()) {
- log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
- + "currently on application with the UUID " + applicationUUID);
+ }
+ return false;
+ }
+
+ private String[] getRoleOfUser(String userName) throws UserStoreException {
+ UserRealm userRealm = CarbonContext.getThreadLocalCarbonContext().getUserRealm();
+ String[] roleList = {};
+ if (userRealm != null) {
+ roleList = userRealm.getUserStoreManager().getRoleListOfUser(userName);
+ } else {
+ log.error("role list is empty of user :" + userName);
+ }
+ return roleList;
+ }
+
+ @Override public Application getApplication(String appType, String appName) throws ApplicationManagementException {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ Application application;
+ boolean isAppAllowed = false;
+ List applicationReleases;
+ try {
+ ConnectionManagerUtil.openDBConnection();
+ application = ApplicationManagementDAOFactory.getApplicationDAO()
+ .getApplication(appType, appName, tenantId);
+ if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
+ return application;
}
- return filteredTransitions;
+
+ if (!application.getUnrestrictedRoles().isEmpty()) {
+ if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
+ isAppAllowed = true;
+ }
+ } else {
+ isAppAllowed = true;
+ }
+
+ if (!isAppAllowed) {
+ return null;
+ }
+
+ applicationReleases = getReleases(application.getId());
+ application.setApplicationReleases(applicationReleases);
+ return application;
} catch (UserStoreException e) {
throw new ApplicationManagementException(
- "Userstore exception while checking whether user " + userName + " from tenant " + tenantId
- + " is authorized to do a life-cycle status change in an application ", e);
+ "User-store exception while getting application with the " + "application name " + appName);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
- @Override
- public Application getApplication(String uuid) throws ApplicationManagementException {
+ @Override public Application getApplicationById(int applicationId) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
-
+ Application application;
+ boolean isAppAllowed = false;
try {
- if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
- userName = "ALL";
+ ConnectionManagerUtil.openDBConnection();
+ application = ApplicationManagementDAOFactory.getApplicationDAO()
+ .getApplicationById(applicationId, tenantId);
+ if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
+ return application;
}
+
+ if (!application.getUnrestrictedRoles().isEmpty()) {
+ if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
+ isAppAllowed = true;
+ }
+ } else {
+ isAppAllowed = true;
+ }
+
+ if (!isAppAllowed) {
+ return null;
+ }
+ return application;
} catch (UserStoreException e) {
throw new ApplicationManagementException(
- "User-store exception while getting application with the UUID " + uuid);
+ "User-store exception while getting application with the " + "application id " + applicationId);
+ } finally {
+ ConnectionManagerUtil.closeDBConnection();
+ }
+ }
+
+ public Boolean verifyApplicationExistenceById(int appId) throws ApplicationManagementException {
+ try {
+ Boolean isAppExist;
+ ConnectionManagerUtil.openDBConnection();
+ isAppExist = ApplicationManagementDAOFactory.getApplicationDAO().verifyApplicationExistenceById(appId);
+ return isAppExist;
+ } finally {
+ ConnectionManagerUtil.closeDBConnection();
+ }
+ }
+
+ public Boolean isUserAllowable(List unrestrictedRoles, String userName)
+ throws ApplicationManagementException {
+ try {
+ return isRoleExists(unrestrictedRoles, userName);
+ } catch (UserStoreException e) {
+ throw new ApplicationManagementException(
+ "User-store exception while verifying whether user have assigned" + "unrestricted roles or not");
+ }
+ }
+
+ @Override public List getReleases(int applicationId) throws ApplicationManagementException {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+
+ Application application = validateApplication(applicationId);
+ List applicationReleases;
+ List filteredApplicationReleases = new ArrayList<>();
+ if (log.isDebugEnabled()) {
+ log.debug("Request is received to retrieve all the releases related with the application " + application
+ .toString());
}
try {
ConnectionManagerUtil.openDBConnection();
- Application application = DAOFactory.getApplicationDAO().getApplication(uuid, tenantId, userName);
- if (application != null) {
- application.setVisibility(DataHolder.getInstance().getVisibilityManager().get(application.getId()));
+ applicationReleases = ApplicationManagementDAOFactory.getApplicationReleaseDAO()
+ .getApplicationReleases(application.getName(), application.getType(), tenantId);
+ for (ApplicationRelease applicationRelease : applicationReleases) {
+ if (!"REMOVED".equals(ApplicationManagementDAOFactory.getLifecycleStateDAO().
+ getLatestLifeCycleStateByReleaseID(applicationRelease.getId()).getCurrentState())) {
+ filteredApplicationReleases.add(applicationRelease);
+ }
}
- return application;
+ return filteredApplicationReleases;
} finally {
ConnectionManagerUtil.closeDBConnection();
}
@@ -355,22 +320,23 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private boolean isApplicationOwnerOrAdmin(String applicationUUID, String userName, int tenantId)
throws ApplicationManagementException {
- try {
- if (isAuthorized(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
- return true;
- }
- } catch (UserStoreException e) {
- throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e);
- }
- try {
- ConnectionManagerUtil.openDBConnection();
- Application application = DAOFactory.getApplicationDAO()
- .getApplication(applicationUUID, tenantId, userName);
- return application.getUser().getUserName().equals(userName)
- && application.getUser().getTenantId() == tenantId;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+ // try {
+ // if (isAdminUser(userName, tenantId, CarbonConstants.UI_ADMIN_PERMISSION_COLLECTION)) {
+ // return true;
+ // }
+ // } catch (UserStoreException e) {
+ // throw new ApplicationManagementException("Userstore exception while checking whether user is an admin", e);
+ // }
+ // try {
+ // ConnectionManagerUtil.openDBConnection();
+ // Application application = ApplicationManagementDAOFactory.getApplicationDAO()
+ // .getApplication(applicationUUID, tenantId, userName);
+ // return application.getUser().getUserName().equals(userName)
+ // && application.getUser().getTenantId() == tenantId;
+ // } finally {
+ // ConnectionManagerUtil.closeDBConnection();
+ // }
+ return false;
}
/**
@@ -382,11 +348,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
* @return true if the current user has the permission, otherwise false.
* @throws UserStoreException UserStoreException
*/
- private boolean isAuthorized(String username, int tenantId, String permission) throws UserStoreException {
+ private boolean isAdminUser(String username, int tenantId, String permission) throws UserStoreException {
UserRealm userRealm = DataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
return userRealm != null && userRealm.getAuthorizationManager() != null && userRealm.getAuthorizationManager()
- .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username),
- permission, CarbonConstants.UI_PERMISSION_ACTION);
+ .isUserAuthorized(MultitenantUtils.getTenantAwareUsername(username), permission,
+ CarbonConstants.UI_PERMISSION_ACTION);
}
/**
@@ -395,30 +361,23 @@ public class ApplicationManagerImpl implements ApplicationManager {
* @param application Application that need to be created
* @throws ValidationException Validation Exception
*/
- private void validateApplication(Application application) throws ValidationException {
+ private void validateAppCreatingRequest(Application application) throws ValidationException {
if (application.getName() == null) {
throw new ValidationException("Application name cannot be empty");
}
-
- if (application.getUser() == null || application.getUser().getUserName() == null ||
- application.getUser().getTenantId() == 0) {
+ if (application.getUser() == null || application.getUser().getUserName() == null
+ || application.getUser().getTenantId() == 0) {
throw new ValidationException("Username and tenant Id cannot be empty");
}
-
- if (application.getCategory() == null || application.getCategory().getName() == null || application
- .getCategory().getName().isEmpty()) {
- throw new ValidationException("Category name cannot be empty");
- }
-
- if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
- throw new ValidationException("Platform identifier cannot be empty");
+ if (application.getAppCategory() == null) {
+ throw new ValidationException("Username and tenant Id cannot be empty");
}
try {
validateApplicationExistence(application);
} catch (ApplicationManagementException e) {
- throw new ValidationException("Error occured while validating whether there is already an application " +
- "registered with same name.", e);
+ throw new ValidationException("Error occured while validating whether there is already an application "
+ + "registered with same name.", e);
}
}
@@ -430,10 +389,264 @@ public class ApplicationManagerImpl implements ApplicationManager {
filter.setLimit(1);
ApplicationList applicationList = getApplications(filter);
- if (applicationList != null && applicationList.getApplications() != null &&
- !applicationList.getApplications().isEmpty()) {
- throw new ValidationException("Already an application registered with same name - "
- + applicationList.getApplications().get(0).getName());
+ if (applicationList != null && applicationList.getApplications() != null && !applicationList.getApplications()
+ .isEmpty()) {
+ throw new ValidationException(
+ "Already an application registered with same name - " + applicationList.getApplications().get(0)
+ .getName());
}
}
+
+ /**
+ * To validate the pre-request of the ApplicationRelease.
+ *
+ * @param applicationID ID of the Application.
+ * @return Application related with the UUID
+ */
+ private Application validateApplication(int applicationID) throws ApplicationManagementException {
+ if (applicationID <= 0) {
+ throw new ApplicationManagementException("Application UUID is null. Application UUID is a required "
+ + "parameter to get the relevant application.");
+ }
+ Application application = DataHolder.getInstance().getApplicationManager().getApplicationById(applicationID);
+ if (application == null) {
+ throw new NotFoundException("Application of the " + applicationID + " does not exist.");
+ }
+ return application;
+ }
+
+ /**
+ * To get role restricted application list.
+ *
+ * @param applicationList list of applications.
+ * @param userName user name
+ * @return Application related with the UUID
+ */
+ private ApplicationList getRoleRestrictedApplicationList(ApplicationList applicationList, String userName)
+ throws ApplicationManagementException {
+ ApplicationList roleRestrictedApplicationList = new ApplicationList();
+ ArrayList unRestrictedApplications = new ArrayList<>();
+ for (Application application : applicationList.getApplications()) {
+ if (application.getUnrestrictedRoles().isEmpty()) {
+ unRestrictedApplications.add(application);
+ } else {
+ try {
+ if (isRoleExists(application.getUnrestrictedRoles(), userName)) {
+ unRestrictedApplications.add(application);
+ }
+ } catch (UserStoreException e) {
+ throw new ApplicationManagementException("Role restriction verifying is failed");
+ }
+ }
+ }
+ roleRestrictedApplicationList.setApplications(unRestrictedApplications);
+ return roleRestrictedApplicationList;
+ }
+
+ /**
+ * To validate a create release request to make sure all the pre-conditions satisfied.
+ *
+ * @param applicationReleases ApplicationRelease that need to be created.
+ * @throws ApplicationManagementException Application Management Exception.
+ */
+ private void validateReleaseCreateRequest(List applicationReleases)
+ throws ApplicationManagementException {
+
+ if (applicationReleases.isEmpty() || applicationReleases.size() > 1) {
+ throw new ApplicationManagementException("ApplicationRelease size is grater than minimal release size or "
+ + "request doesn't contains application release");
+ }
+ if (applicationReleases.get(0).getVersion() == null) {
+ throw new ApplicationManagementException("ApplicationRelease version name is a mandatory parameter for "
+ + "creating release. It cannot be found.");
+ }
+ //todo
+ // if (getRelease(applicationReleases.get(0).getUuid(), applicationReleases.get(0).getVersion(),
+ // applicationReleases.get(0).getReleaseType()) != null) {
+ // throw new ApplicationManagementException( "Application Release for the Application UUID " +
+ // applicationReleases.get(0).getUuid() + " " + "with the version "
+ // + applicationReleases.get(0).getVersion() + " already exists. Cannot create an " +
+ // "application release with the same version.");
+ // }
+ }
+
+ @Override public Application editApplication(Application application) throws ApplicationManagementException {
+ // String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ // int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ // if (application.getUuid() == null) {
+ // throw new ValidationException("Application UUID cannot be empty");
+ // }
+ //
+ // if (!isApplicationOwnerOrAdmin(application.getUuid(), userName, tenantId)) {
+ // throw new ApplicationManagementException(
+ // "User " + userName + " does not have permissions to edit the " + "application with the UUID "
+ // + application.getUuid());
+ // }
+ // if (this.getApplication(application.getUuid()) != null) {
+ // if (application.getPlatform() == null || application.getPlatform().getIdentifier() == null) {
+ // throw new NotFoundException("Platform information not available with the application!");
+ // }
+ // Platform platform = DataHolder.getInstance().getPlatformManager()
+ // .getPlatform(tenantId, application.getPlatform().getIdentifier());
+ // if (platform == null) {
+ // throw new NotFoundException(
+ // "Platform specified by identifier " + application.getPlatform().getIdentifier()
+ // + " is not found. Please give a valid platform identifier.");
+ // }
+ // application.setPlatform(platform);
+ // if (application.getCategory() != null) {
+ // String applicationCategoryName = application.getCategory().getName();
+ // if (applicationCategoryName == null || applicationCategoryName.isEmpty()) {
+ // throw new ApplicationManagementException(
+ // "Application category name cannot be null or " + "empty. Cannot edit the application.");
+ // }
+ // Category category = DataHolder.getInstance().getCategoryManager()
+ // .getCategory(application.getCategory().getName());
+ // if (category == null) {
+ // throw new NotFoundException(
+ // "Invalid Category is provided for the application " + application.getUuid() + ". "
+ // + "Cannot edit application");
+ // }
+ // application.setCategory(category);
+ // }
+ // try {
+ // ConnectionManagerUtil.beginDBTransaction();
+ // ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
+ // application.setModifiedAt(new Date());
+ // Application modifiedApplication = applicationDAO.editApplication(application, tenantId);
+ // Visibility visibility = DataHolder.getInstance().getVisibilityManager()
+ // .put(application.getId(), application.getVisibility());
+ // modifiedApplication.setVisibility(visibility);
+ // ConnectionManagerUtil.commitDBTransaction();
+ // return modifiedApplication;
+ // } catch (ApplicationManagementDAOException e) {
+ // ConnectionManagerUtil.rollbackDBTransaction();
+ // throw e;
+ // } finally {
+ // ConnectionManagerUtil.closeDBConnection();
+ // }
+ // } else {
+ // throw new NotFoundException("No applications found with application UUID - " + application.getUuid());
+ // }
+ return application;
+ }
+
+ @Override public void deleteApplication(String uuid) throws ApplicationManagementException {
+ // String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ // int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ // if (!isApplicationOwnerOrAdmin(uuid, userName, tenantId)) {
+ // throw new ApplicationManagementException("User '" + userName + "' of tenant - " + tenantId + " does have"
+ // + " the permission to delete the application with UUID " + uuid);
+ // }
+ // try {
+ // ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
+ // ConnectionManagerUtil.beginDBTransaction();
+ // int appId = applicationDAO.getApplicationId(uuid, tenantId);
+ // if (appId != -1) {
+ // applicationDAO.deleteTags(appId);
+ // applicationDAO.deleteProperties(appId);
+ // DataHolder.getInstance().getVisibilityManager().remove(appId);
+ // applicationDAO.deleteApplication(uuid, tenantId);
+ // }
+ // ConnectionManagerUtil.commitDBTransaction();
+ // } catch (ApplicationManagementDAOException e) {
+ // ConnectionManagerUtil.rollbackDBTransaction();
+ // String msg = "Failed to delete application: " + uuid;
+ // throw new ApplicationManagementException(msg, e);
+ // } finally {
+ // ConnectionManagerUtil.closeDBConnection();
+ // }
+ }
+
+ @Override public void changeLifecycle(String applicationUuid, String lifecycleIdentifier)
+ throws ApplicationManagementException {
+ // boolean isAvailableNextState = false;
+ // String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ // int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ // List nextLifeCycles = getLifeCycleStates(applicationUuid);
+ //
+ // for (LifecycleStateTransition lifecycleStateTransition : nextLifeCycles) {
+ // if (log.isDebugEnabled()) {
+ // log.debug("Lifecycle state of the application " + applicationUuid + " can be changed to"
+ // + lifecycleStateTransition.getNextState());
+ // }
+ // if (lifecycleStateTransition.getNextState().equalsIgnoreCase(lifecycleIdentifier)) {
+ // isAvailableNextState = true;
+ // break;
+ // }
+ // }
+ // if (!isAvailableNextState) {
+ // throw new ApplicationManagementException("User " + userName + " does not have the permission to change "
+ // + "the lifecycle state of the application " + applicationUuid + " to lifecycle state "
+ // + lifecycleIdentifier);
+ // }
+ // try {
+ // ConnectionManagerUtil.beginDBTransaction();
+ // ApplicationDAO applicationDAO = ApplicationManagementDAOFactory.getApplicationDAO();
+ // applicationDAO.changeLifecycle(applicationUuid, lifecycleIdentifier, userName, tenantId);
+ // ConnectionManagerUtil.commitDBTransaction();
+ // } catch (ApplicationManagementDAOException e) {
+ // ConnectionManagerUtil.rollbackDBTransaction();
+ // throw e;
+ // } finally {
+ // ConnectionManagerUtil.closeDBConnection();
+ // }
+ }
+
+ @Override public List getLifeCycleStates(String applicationUUID)
+ throws ApplicationManagementException {
+ // int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ // String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ // boolean isAdminOrApplicationOwner = isApplicationOwnerOrAdmin(applicationUUID, userName, tenantId);
+ //
+ // if (log.isDebugEnabled()) {
+ // log.debug("User " + userName + " in tenant " + tenantId + " is an Admin or Application owner of the "
+ // + "application " + applicationUUID);
+ // }
+ // try {
+ // ConnectionManagerUtil.openDBConnection();
+ // List transitions = ApplicationManagementDAOFactory.getApplicationDAO()
+ // .getNextLifeCycleStates(applicationUUID, tenantId);
+ // List filteredTransitions = new ArrayList<>();
+ //
+ // if (log.isDebugEnabled()) {
+ // log.debug("Lifecycle of the application with UUID : " + applicationUUID + " can be changed to "
+ // + transitions.size() + ". The number may vary according to the permission level of user : "
+ // + userName + " of tenant " + tenantId);
+ // }
+ // for (LifecycleStateTransition transition : transitions) {
+ // String permission = transition.getPermission();
+ // if (permission != null) {
+ // if (log.isDebugEnabled()) {
+ // log.debug("In order to make the state change to " + transition.getNextState() + " permission "
+ // + permission + " is required");
+ // }
+ // if (isAdminUser(userName, tenantId, permission)) {
+ // filteredTransitions.add(transition);
+ // } else {
+ // if (log.isDebugEnabled()) {
+ // log.debug("User " + userName + " does not have the permission " + permission + " to "
+ // + "change the life-cycle state to " + transition.getNextState() + " of the "
+ // + "application " + applicationUUID);
+ // }
+ // }
+ // } else if (isAdminOrApplicationOwner) {
+ // filteredTransitions.add(transition);
+ // }
+ // }
+ // if (log.isDebugEnabled()) {
+ // log.debug("User " + userName + " can do " + filteredTransitions.size() + " life-cyle state changes "
+ // + "currently on application with the UUID " + applicationUUID);
+ // }
+ // return filteredTransitions;
+ // } catch (UserStoreException e) {
+ // throw new ApplicationManagementException(
+ // "Userstore exception while checking whether user " + userName + " from tenant " + tenantId
+ // + " is authorized to do a life-cycle status change in an application ", e);
+ // } finally {
+ // ConnectionManagerUtil.closeDBConnection();
+ // }
+ return null;
+ }
+
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationReleaseManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationReleaseManagerImpl.java
index 77672a7076..957421223d 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationReleaseManagerImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationReleaseManagerImpl.java
@@ -25,12 +25,13 @@ import org.wso2.carbon.device.application.mgt.common.Application;
import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
+import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
@@ -41,18 +42,18 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
private static Log log = LogFactory.getLog(ApplicationReleaseManagerImpl.class);
@Override
- public ApplicationRelease createRelease(String appicationUuid, ApplicationRelease applicationRelease) throws
+ public ApplicationRelease createRelease(int applicationId, ApplicationRelease applicationRelease) throws
ApplicationManagementException {
- Application application = validateApplication(appicationUuid);
- validateReleaseCreateRequest(appicationUuid, applicationRelease);
+ Application application = validateApplication(applicationId);
+ validateReleaseCreateRequest(applicationRelease);
if (log.isDebugEnabled()) {
log.debug("Application release request is received for the application " + application.toString());
}
- applicationRelease.setCreatedAt(new Date());
+ applicationRelease.setCreatedAt((Timestamp) new Date());
try {
ConnectionManagerUtil.beginDBTransaction();
- applicationRelease.setApplication(application);
- applicationRelease = DAOFactory.getApplicationReleaseDAO().createRelease(applicationRelease);
+ applicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO().
+ createRelease(applicationRelease, application.getId());
ConnectionManagerUtil.commitDBTransaction();
return applicationRelease;
} catch (ApplicationManagementDAOException e) {
@@ -63,124 +64,158 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
}
}
+ //todo
@Override
- public ApplicationRelease getRelease(String applicationUuid, String version) throws
+ public ApplicationRelease getRelease(String applicationUuid, String version, String releaseType) throws
ApplicationManagementException {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Application application = validateApplication(applicationUuid);
- if (log.isDebugEnabled()) {
- log.debug("Application release retrieval request is received for the application " +
- application.toString() + " and version " + version);
- }
- try {
- ConnectionManagerUtil.openDBConnection();
- return DAOFactory.getApplicationReleaseDAO().getRelease(applicationUuid, version, tenantId);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+ return null;
+// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+// Application application = validateApplicationRelease(applicationUuid);
+// if (log.isDebugEnabled()) {
+// log.debug("Application release retrieval request is received for the application " +
+// application.toString() + " and version " + version);
+// }
+// try {
+// ConnectionManagerUtil.openDBConnection();
+// return ApplicationManagementDAOFactory.getApplicationReleaseDAO()
+// .getRelease(application.getName(), application.getType(), version, releaseType, tenantId );
+// } finally {
+// ConnectionManagerUtil.closeDBConnection();
+// }
+ }
+
+ //todo
+ @Override public ApplicationRelease getReleaseByUuid(String applicationUuid) throws ApplicationManagementException {
+ return null;
}
@Override
- public List getReleases(String applicationUuid) throws ApplicationManagementException {
+ public List getReleases(int applicationId) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Application application = validateApplication(applicationUuid);
+
+ Application application = validateApplication(applicationId);
if (log.isDebugEnabled()) {
log.debug("Request is received to retrieve all the releases related with the application " +
application.toString());
}
try {
ConnectionManagerUtil.openDBConnection();
- return DAOFactory.getApplicationReleaseDAO().getApplicationReleases(applicationUuid, tenantId);
+ return ApplicationManagementDAOFactory.getApplicationReleaseDAO()
+ .getApplicationReleases(application.getName(), application.getType(), tenantId);
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
+// ToDo
@Override
public void changeDefaultRelease(String uuid, String version, boolean isDefault, String releaseChannel) throws
ApplicationManagementException {
- Application application = validateApplication(uuid);
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- if (log.isDebugEnabled()) {
- log.debug("Request received to change the default release for the release channel " + releaseChannel
- + "for the application " + application.toString());
- }
-
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getApplicationReleaseDAO()
- .changeReleaseDefault(uuid, version, isDefault, releaseChannel, tenantId);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+// Application application = validateApplicationRelease(uuid);
+// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+// if (log.isDebugEnabled()) {
+// log.debug("Request received to change the default release for the release channel " + releaseChannel
+// + "for the application " + application.toString());
+// }
+//
+// try {
+// ConnectionManagerUtil.beginDBTransaction();
+// ApplicationManagementDAOFactory.getApplicationReleaseDAO()
+// .changeReleaseDefault(uuid, version, isDefault, releaseChannel, tenantId);
+// ConnectionManagerUtil.commitDBTransaction();
+// } catch (ApplicationManagementDAOException e) {
+// ConnectionManagerUtil.rollbackDBTransaction();
+// throw e;
+// } finally {
+// ConnectionManagerUtil.closeDBConnection();
+// }
}
+// ToDo
@Override
- public ApplicationRelease updateRelease(String applicationUuid, ApplicationRelease applicationRelease)
+ public ApplicationRelease updateRelease(int appId, ApplicationRelease applicationRelease)
throws ApplicationManagementException {
- Application application = validateApplication(applicationUuid);
- ApplicationRelease oldApplicationRelease = null;
- if (applicationRelease == null || applicationRelease.getVersionName() != null) {
- throw new ApplicationManagementException(
- "Version is important to update the release of the application " + "with application UUID "
- + applicationUuid);
- }
- oldApplicationRelease = getRelease(applicationUuid, applicationRelease.getVersionName());
- if (oldApplicationRelease == null) {
- throw new ApplicationManagementException(
- "Application release for the application " + applicationUuid + " with version " + applicationRelease
- .getVersionName() + " does not exist. Cannot update the "
- + "release that is not existing.");
- }
- applicationRelease.setApplication(application);
- try {
- ConnectionManagerUtil.beginDBTransaction();
- ApplicationRelease newApplicationRelease = DAOFactory.getApplicationReleaseDAO()
- .updateRelease(applicationRelease);
- ConnectionManagerUtil.commitDBTransaction();
- return newApplicationRelease;
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+// Application application = validateApplicationRelease(applicationUuid);
+// ApplicationRelease oldApplicationRelease = null;
+// if (applicationRelease == null || applicationRelease.getVersion() != null) {
+// throw new ApplicationManagementException(
+// "Version is important to update the release of the application " + "with application UUID "
+// + applicationUuid);
+// }
+// oldApplicationRelease = getRelease(applicationUuid, applicationRelease.getVersion());
+// if (oldApplicationRelease == null) {
+// throw new ApplicationManagementException(
+// "Application release for the application " + applicationUuid + " with version " + applicationRelease
+// .getVersion() + " does not exist. Cannot update the "
+// + "release that is not existing.");
+// }
+// applicationRelease.setApplication(application);
+// try {
+// ConnectionManagerUtil.beginDBTransaction();
+// ApplicationRelease newApplicationRelease = ApplicationManagementDAOFactory.getApplicationReleaseDAO()
+// .updateRelease(applicationRelease);
+// ConnectionManagerUtil.commitDBTransaction();
+// return newApplicationRelease;
+// } catch (ApplicationManagementDAOException e) {
+// ConnectionManagerUtil.rollbackDBTransaction();
+// throw e;
+// } finally {
+// ConnectionManagerUtil.closeDBConnection();
+// }
+ return null;
}
+ //todo
@Override
- public void deleteApplicationRelease(String applicationUuid, String version)
+ public void deleteApplicationRelease(String applicationUuid, String version, String releaseType)
throws ApplicationManagementException {
- Application application = validateApplication(applicationUuid);
- ApplicationRelease applicationRelease = getRelease(applicationUuid, version);
- if (applicationRelease == null) {
- throw new ApplicationManagementException(
- "Cannot delete a non-existing application release for the " + "application with UUID "
- + applicationUuid);
- }
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getApplicationReleaseDAO().deleteRelease(application.getId(), version);
- DAOFactory.getApplicationReleaseDAO().deleteReleaseProperties(applicationRelease.getId());
- ConnectionManagerUtil.commitDBTransaction();
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+// Application application = validateApplicationRelease(applicationUuid);
+// ApplicationRelease applicationRelease = getRelease(applicationUuid, version, releaseType);
+// if (applicationRelease == null) {
+// throw new ApplicationManagementException(
+// "Cannot delete a non-existing application release for the " + "application with UUID "
+// + applicationUuid);
+// }
+// try {
+// ConnectionManagerUtil.beginDBTransaction();
+// ApplicationManagementDAOFactory.getApplicationReleaseDAO().deleteRelease(application.getId(), version);
+//// ToDO remove storage details as well
+// ConnectionManagerUtil.commitDBTransaction();
+// } catch (ApplicationManagementDAOException e) {
+// ConnectionManagerUtil.rollbackDBTransaction();
+// throw e;
+// } finally {
+// ConnectionManagerUtil.closeDBConnection();
+// }
}
+ //todo
@Override
public void deleteApplicationReleases(String applicationUuid) throws ApplicationManagementException {
- List applicationReleases = getReleases(applicationUuid);
+// List applicationReleases = getReleases(applicationUuid);
+//
+// for (ApplicationRelease applicationRelease : applicationReleases) {
+// deleteApplicationRelease(applicationUuid, applicationRelease.getVersion());
+// }
+ }
- for (ApplicationRelease applicationRelease : applicationReleases) {
- deleteApplicationRelease(applicationUuid, applicationRelease.getVersionName());
+ /**
+ * To validate the pre-request of the ApplicationRelease.
+ *
+ * @param applicationID ID of the Application.
+ * @return Application related with the UUID
+ */
+ private Application validateApplication(int applicationID) throws ApplicationManagementException {
+ if (applicationID <= 0) {
+ throw new ApplicationManagementException("Application UUID is null. Application UUID is a required "
+ + "parameter to get the relevant application.");
}
+ Application application = DataHolder.getInstance().getApplicationManager().getApplicationById(applicationID);
+ if (application == null) {
+ throw new NotFoundException(
+ "Application of the " + applicationID + " does not exist.");
+ }
+ return application;
}
/**
@@ -189,37 +224,37 @@ public class ApplicationReleaseManagerImpl implements ApplicationReleaseManager
* @param applicationUuid UUID of the Application.
* @return Application related with the UUID
*/
- private Application validateApplication(String applicationUuid) throws ApplicationManagementException {
+ private ApplicationRelease validateApplicationRelease(String applicationUuid) throws ApplicationManagementException {
if (applicationUuid == null) {
throw new ApplicationManagementException("Application UUID is null. Application UUID is a required "
+ "parameter to get the relevant application.");
}
- Application application = DataHolder.getInstance().getApplicationManager().getApplication(applicationUuid);
- if (application == null) {
+ ApplicationRelease applicationRelease = DataHolder.getInstance().getApplicationReleaseManager()
+ .getReleaseByUuid(applicationUuid);
+ if (applicationRelease == null) {
throw new NotFoundException(
"Application with UUID " + applicationUuid + " does not exist.");
}
- return application;
+ return applicationRelease;
}
/**
* To validate a create release request to make sure all the pre-conditions satisfied.
*
- * @param applicationUuid UUID of the Application.
* @param applicationRelease ApplicationRelease that need to be created.
* @throws ApplicationManagementException Application Management Exception.
*/
- private void validateReleaseCreateRequest(String applicationUuid, ApplicationRelease applicationRelease)
+ private void validateReleaseCreateRequest(ApplicationRelease applicationRelease)
throws ApplicationManagementException {
- if (applicationRelease == null || applicationRelease.getVersionName() == null) {
+ if (applicationRelease == null || applicationRelease.getVersion() == null) {
throw new ApplicationManagementException("ApplicationRelease version name is a mandatory parameter for "
+ "creating release. It cannot be found.");
}
- if (getRelease(applicationUuid, applicationRelease.getVersionName()) != null) {
- throw new ApplicationManagementException(
- "Application Release for the Application UUID " + applicationUuid + " " + "with the version "
- + applicationRelease.getVersionName() + " already exists. Cannot create an "
- + "application release with the same version.");
+ if (getRelease(applicationRelease.getUuid(), applicationRelease.getVersion(),
+ applicationRelease.getReleaseType()) != null) {
+ throw new ApplicationManagementException( "Application Release for the Application UUID " +
+ applicationRelease.getUuid() + " " + "with the version " + applicationRelease.getVersion() +
+ " already exists. Cannot create an " + "application release with the same version.");
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java
index 60cea3d56e..dace15841d 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/ApplicationStorageManagerImpl.java
@@ -19,6 +19,8 @@
package org.wso2.carbon.device.application.mgt.core.impl;
+import org.apache.commons.codec.digest.DigestUtils;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
@@ -27,12 +29,9 @@ import org.wso2.carbon.device.application.mgt.common.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
+import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants;
@@ -68,201 +67,245 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
}
@Override
- public void uploadImageArtifacts(String applicationUUID, InputStream iconFileStream, InputStream bannerFileStream,
- List screenShotStreams) throws ResourceManagementException {
+ public ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease, InputStream iconFileStream,
+ InputStream bannerFileStream,List screenShotStreams) throws ResourceManagementException {
+
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Application application = validateApplication(applicationUUID);
- String artifactDirectoryPath = storagePath + application.getId();
- if (log.isDebugEnabled()) {
- log.debug("Artifact Directory Path for saving the artifacts related with application " + applicationUUID
- + " is " + artifactDirectoryPath);
- }
- StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
- if (iconFileStream != null) {
- try {
- saveFile(iconFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0]);
- } catch (IOException e) {
- throw new ApplicationStorageManagementException(
- "IO Exception while saving the icon file in the server for " + "the application "
- + applicationUUID, e);
- }
- }
- if (bannerFileStream != null) {
- try {
- saveFile(bannerFileStream, artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1]);
- } catch (IOException e) {
- throw new ApplicationStorageManagementException(
- "IO Exception while saving the banner file in the server for" + " the application "
- + applicationUUID, e);
- }
- }
- if (screenShotStreams != null) {
- int count = application.getScreenShotCount() + 1;
- boolean maxCountReached = false;
+ String artifactDirectoryPath = null;
+ String iconStoredLocation;
+ String bannerStoredLocation;
+ String scStoredLocation;
- if (count > screenShotMaxCount) {
- log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
- + " Cannot upload another screenshot for the application with the UUID " + applicationUUID);
- maxCountReached = true;
- }
- String screenshotName;
+ try {
- if (maxCountReached) {
- return;
+ artifactDirectoryPath = storagePath + applicationRelease.getAppHashValue();
+ StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
+ iconStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[0];
+ bannerStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[1];
+
+ if (iconFileStream != null){
+ saveFile(iconFileStream, iconStoredLocation);
+ applicationRelease.setIconLoc(iconStoredLocation);
}
- for (InputStream screenshotStream : screenShotStreams) {
- try {
- screenshotName = Constants.IMAGE_ARTIFACTS[2] + count;
- saveFile(screenshotStream, artifactDirectoryPath + File.separator + screenshotName);
- count++;
- if (count > screenShotMaxCount) {
- log.error("Maximum limit for the screen-shot is " + screenShotMaxCount
- + " Cannot upload another screenshot for the application with the UUID "
- + applicationUUID);
- break;
+
+ if (bannerFileStream != null){
+ saveFile(bannerFileStream, bannerStoredLocation);
+ applicationRelease.setBannerLoc(bannerStoredLocation);
+ }
+
+
+ if (screenShotStreams.size() > screenShotMaxCount) {
+ throw new ApplicationStorageManagementException("Maximum limit for the screen-shot exceeds");
+ }else if(!screenShotStreams.isEmpty() && screenShotStreams.size() <= screenShotMaxCount){
+ int count = 1;
+ for (InputStream screenshotStream : screenShotStreams) {
+ scStoredLocation = artifactDirectoryPath + File.separator + Constants.IMAGE_ARTIFACTS[2] + count;
+ if (count == 1) {
+ applicationRelease.setScreenshotLoc1(scStoredLocation);
}
- } catch (IOException e) {
- throw new ApplicationStorageManagementException(
- "IO Exception while saving the screens hots for the " + "application " + applicationUUID,
- e);
+ if (count == 2) {
+ applicationRelease.setScreenshotLoc2(scStoredLocation);
+ }
+ if (count == 3) {
+ applicationRelease.setScreenshotLoc3(scStoredLocation);
+ }
+ saveFile(screenshotStream, scStoredLocation);
+ count++;
}
}
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getApplicationDAO().updateScreenShotCount(applicationUUID, tenantId, count - 1);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new ApplicationStorageManagementException("Transaction Management exception while trying to "
- + "update the screen-shot count of the application " + applicationUUID + " for the tenant "
- + tenantId, e);
- } catch (DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new ApplicationStorageManagementException("Database connection management exception while "
- + "trying to update the screen-shot count for the application " + applicationUUID + " for the"
- + " tenant " + tenantId, e);
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new ApplicationStorageManagementException("Application Management DAO exception while trying to"
- + " update the screen-shot count for the application " + applicationUUID + " for the tenant "
- + tenantId, e);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
+
+ return applicationRelease;
+ } catch (IOException e) {
+ throw new ApplicationStorageManagementException(
+ "IO Exception while saving the screens hots for the " + "application " +
+ applicationRelease.getUuid(), e);
+ } catch (ApplicationStorageManagementException e) {
+ ConnectionManagerUtil.rollbackDBTransaction();
+ throw new ApplicationStorageManagementException("Application Management DAO exception while trying to "
+ + "update the screen-shot count for the application " + applicationRelease.getUuid() +
+ " for the tenant id " + tenantId, e);
}
+
}
@Override
- public void uploadReleaseArtifacts(String applicationUUID, String versionName, InputStream binaryFile)
- throws ResourceManagementException {
- Application application = validateApplication(applicationUUID);
- String artifactDirectoryPath = storagePath + application.getId();
- if (log.isDebugEnabled()) {
- log.debug("Artifact Directory Path for saving the application release related artifacts related with "
- + "application " + applicationUUID + " is " + artifactDirectoryPath);
+ public ApplicationRelease updateImageArtifacts(int applicationId, String uuid, InputStream iconFileStream,
+ InputStream bannerFileStream, List screenShotStreams)
+ throws ResourceManagementException, ApplicationManagementException {
+
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+
+ try {
+ ApplicationRelease applicationRelease = validateApplicationRelease(uuid);
+ applicationRelease = uploadImageArtifacts(applicationRelease, iconFileStream, bannerFileStream, screenShotStreams);
+ return applicationRelease;
+ } catch (ApplicationStorageManagementException e) {
+ ConnectionManagerUtil.rollbackDBTransaction();
+ throw new ApplicationStorageManagementException("Application Storage exception while trying to"
+ + " update the screen-shot count for the application " + applicationId + " for the tenant "
+ + tenantId, e);
+ } catch (ApplicationManagementException e) {
+ ConnectionManagerUtil.rollbackDBTransaction();
+ throw new ApplicationManagementException("Application Management DAO exception while trying to"
+ + " update the screen-shot count for the application " + applicationId + " for the tenant "
+ + tenantId, e);
}
- StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
- if (binaryFile != null) {
+
+ }
+
+ @Override
+ public ApplicationRelease uploadReleaseArtifacts(ApplicationRelease applicationRelease , InputStream binaryFile)
+ throws ResourceManagementException {
+
+ String artifactDirectoryPath;
+ String md5OfApp;
+ md5OfApp = getMD5(binaryFile);
+ //todo validate binary file.
+
+ if(md5OfApp != null){
+ artifactDirectoryPath = storagePath + md5OfApp;
+ StorageManagementUtil.createArtifactDirectory(artifactDirectoryPath);
+ if (log.isDebugEnabled()) {
+ log.debug("Artifact Directory Path for saving the application release related artifacts related with "
+ + "application UUID " + applicationRelease.getUuid() + " is " + artifactDirectoryPath);
+ }
try {
- saveFile(binaryFile, artifactDirectoryPath + File.separator + versionName);
+ saveFile(binaryFile, artifactDirectoryPath);
+ applicationRelease.setAppStoredLoc(artifactDirectoryPath);
+ applicationRelease.setAppHashValue(md5OfApp);
} catch (IOException e) {
throw new ApplicationStorageManagementException(
- "IO Exception while saving the release artifacts in the server for the application "
- + applicationUUID, e);
+ "IO Exception while saving the release artifacts in the server for the application UUID "
+ + applicationRelease.getUuid(), e);
}
+
+ }else{
+ log.error("Verify application existence and md5sum value retrieving process");
+ }
+
+ return applicationRelease;
+ }
+
+ @Override
+ public ApplicationRelease updateReleaseArtifacts(int applicationId, String applicationUuid, InputStream binaryFile)
+ throws ResourceManagementException {
+
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+
+ ApplicationRelease applicationRelease = null;
+ try {
+ applicationRelease = validateApplicationRelease(applicationUuid);
+ applicationRelease = uploadReleaseArtifacts(applicationRelease,binaryFile);
+ return applicationRelease;
+ } catch (ApplicationManagementException e) {
+ throw new ApplicationStorageManagementException("Application Management exception while trying to"
+ + " update the Application artifact for the application " + applicationId + " for the tenant "
+ + tenantId, e);
}
}
+ //todo
@Override
public InputStream getReleasedArtifacts(String applicationUUID, String versionName)
throws ApplicationStorageManagementException {
- Application application = validateApplication(applicationUUID);
- String artifactPath = storagePath + application.getId() + File.separator + versionName;
-
- if (log.isDebugEnabled()) {
- log.debug("ApplicationRelease artifacts are searched in the location " + artifactPath);
- }
-
- File binaryFile = new File(artifactPath);
-
- if (!binaryFile.exists()) {
- throw new ApplicationStorageManagementException("Binary file does not exist for this release");
- } else {
- try {
- return new FileInputStream(artifactPath);
- } catch (FileNotFoundException e) {
- throw new ApplicationStorageManagementException(
- "Binary file does not exist for the version " + versionName + " for the application ", e);
- }
- }
+ return null;
+ // todo this should be validate application release
+ // Application application = validateApplication(applicationUUID);
+ // String artifactPath = storagePath + application.getId() + File.separator + versionName;
+ //
+ // if (log.isDebugEnabled()) {
+ // log.debug("ApplicationRelease artifacts are searched in the location " + artifactPath);
+ // }
+ //
+ // File binaryFile = new File(artifactPath);
+ //
+ // if (!binaryFile.exists()) {
+ // throw new ApplicationStorageManagementException("Binary file does not exist for this release");
+ // } else {
+ // try {
+ // return new FileInputStream(artifactPath);
+ // } catch (FileNotFoundException e) {
+ // throw new ApplicationStorageManagementException(
+ // "Binary file does not exist for the version " + versionName + " for the application ", e);
+ // }
+ // }
}
+ //todo
@Override
public void deleteApplicationArtifacts(String applicationUUID) throws ApplicationStorageManagementException {
- Application application = validateApplication(applicationUUID);
- String artifactDirectoryPath = storagePath + application.getId();
- File artifactDirectory = new File(artifactDirectoryPath);
-
- if (artifactDirectory.exists()) {
- StorageManagementUtil.deleteDir(artifactDirectory);
- }
+ // todo this should be validate application release
+ // Application application = validateApplication(applicationUUID);
+ // String artifactDirectoryPath = storagePath + application.getId();
+ // File artifactDirectory = new File(artifactDirectoryPath);
+ //
+ // if (artifactDirectory.exists()) {
+ // StorageManagementUtil.deleteDir(artifactDirectory);
+ // }
}
+ //todo
@Override
public void deleteApplicationReleaseArtifacts(String applicationUUID, String version)
throws ApplicationStorageManagementException {
- Application application = validateApplication(applicationUUID);
- String artifactPath = storagePath + application.getId() + File.separator + version;
- File artifact = new File(artifactPath);
-
- if (artifact.exists()) {
- StorageManagementUtil.deleteDir(artifact);
- }
+ // todo this should be validate application release
+ // Application application = validateApplication(applicationUUID);
+ // String artifactPath = storagePath + application.getId() + File.separator + version;
+ // File artifact = new File(artifactPath);
+ //
+ // if (artifact.exists()) {
+ // StorageManagementUtil.deleteDir(artifact);
+ // }
}
+ //todo
@Override
public void deleteAllApplicationReleaseArtifacts(String applicationUUID) throws
ApplicationStorageManagementException {
- validateApplication(applicationUUID);
- try {
- List applicationReleases = DataHolder.getInstance().getReleaseManager()
- .getReleases(applicationUUID);
- for (ApplicationRelease applicationRelease : applicationReleases) {
- deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersionName());
- }
- } catch (ApplicationManagementException e) {
- throw new ApplicationStorageManagementException(
- "Application Management Exception while getting releases " + "for the application "
- + applicationUUID, e);
- }
+ // todo this should be validate application release
+ // validateApplication(applicationUUID);
+ // try {
+ // List applicationReleases = DataHolder.getInstance().getApplicationReleaseManager()
+ // .getReleases(applicationUUID);
+ // for (ApplicationRelease applicationRelease : applicationReleases) {
+ // deleteApplicationReleaseArtifacts(applicationUUID, applicationRelease.getVersion());
+ // }
+ // } catch (ApplicationManagementException e) {
+ // throw new ApplicationStorageManagementException(
+ // "Application Management Exception while getting releases " + "for the application "
+ // + applicationUUID, e);
+ // }
}
+ //todo
@Override
public ImageArtifact getImageArtifact(String applicationUUID, String name, int count) throws
ApplicationStorageManagementException {
- Application application = validateApplication(applicationUUID);
- validateImageArtifactNames(name);
- String imageArtifactPath = storagePath + application.getId() + File.separator + name.toLowerCase();
-
- if (name.equalsIgnoreCase(Constants.IMAGE_ARTIFACTS[2])) {
- imageArtifactPath += count;
- }
- File imageFile = new File(imageArtifactPath);
- if (!imageFile.exists()) {
- throw new ApplicationStorageManagementException(
- "Image artifact " + name + " does not exist for the " + "application with UUID " + applicationUUID);
- } else {
- try {
- return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath);
- } catch (FileNotFoundException e) {
- throw new ApplicationStorageManagementException(
- "File not found exception while trying to get the image artifact " + name + " for the "
- + "application " + applicationUUID, e);
- } catch (IOException e) {
- throw new ApplicationStorageManagementException("IO Exception while trying to detect the image "
- + "artifact " + name + " for the application " + applicationUUID, e);
- }
- }
+ return null;
+ // todo this should be validate application release
+ // Application application = validateApplication(applicationUUID);
+ // validateImageArtifactNames(name);
+ // String imageArtifactPath = storagePath + application.getId() + File.separator + name.toLowerCase();
+ //
+ // if (name.equalsIgnoreCase(Constants.IMAGE_ARTIFACTS[2])) {
+ // imageArtifactPath += count;
+ // }
+ // File imageFile = new File(imageArtifactPath);
+ // if (!imageFile.exists()) {
+ // throw new ApplicationStorageManagementException(
+ // "Image artifact " + name + " does not exist for the " + "application with UUID " + applicationUUID);
+ // } else {
+ // try {
+ // return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath);
+ // } catch (FileNotFoundException e) {
+ // throw new ApplicationStorageManagementException(
+ // "File not found exception while trying to get the image artifact " + name + " for the "
+ // + "application " + applicationUUID, e);
+ // } catch (IOException e) {
+ // throw new ApplicationStorageManagementException("IO Exception while trying to detect the image "
+ // + "artifact " + name + " for the application " + applicationUUID, e);
+ // }
+ // }
}
/**
@@ -284,24 +327,52 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
/**
* To validate the Application before storing and retrieving the artifacts of a particular application.
*
- * @param uuid UUID of the Application
- * @return {@link Application} if it is validated
+ * @param appId ID of the Application
+ * @return boolean if it is validated
* @throws ApplicationStorageManagementException Application Storage Management Exception will be thrown if a
* valid application related with the specific UUID
* could not be found.
*/
- private Application validateApplication(String uuid) throws ApplicationStorageManagementException {
- Application application;
+ private Boolean validateApplication(int appId) throws ApplicationStorageManagementException {
+ Boolean isAppExist;
try {
- application = DataHolder.getInstance().getApplicationManager().getApplication(uuid);
+ isAppExist = DataHolder.getInstance().getApplicationManager().verifyApplicationExistenceById(appId);
} catch (ApplicationManagementException e) {
throw new ApplicationStorageManagementException(
- "Exception while retrieving the application details for the application with UUID "
- + uuid);
+ "Exception while verifing the application existence for the application with ID "+ appId);
}
- if (application == null) {
- throw new ApplicationStorageManagementException("Application with UUID " + uuid + " does not exist.");
+
+ return isAppExist;
+ }
+
+ /**
+ * To validate the pre-request of the ApplicationRelease.
+ *
+ * @param applicationUuid UUID of the Application.
+ * @return Application related with the UUID
+ */
+ private ApplicationRelease validateApplicationRelease(String applicationUuid) throws ApplicationManagementException {
+ if (applicationUuid == null) {
+ throw new ApplicationManagementException("Application UUID is null. Application UUID is a required "
+ + "parameter to get the relevant application.");
}
- return application;
+ ApplicationRelease applicationRelease = DataHolder.getInstance().getApplicationReleaseManager().
+ getReleaseByUuid(applicationUuid);
+ if (applicationRelease == null) {
+ throw new NotFoundException(
+ "Application with UUID " + applicationUuid + " does not exist.");
+ }
+ return applicationRelease;
+ }
+
+ private String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException {
+ String md5;
+ try {
+ md5 = DigestUtils.md5Hex(IOUtils.toByteArray(binaryFile));
+ } catch (IOException e) {
+ throw new ApplicationStorageManagementException
+ ("IO Exception while trying to get the md5sum value of application");
+ }
+ return md5;
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CategoryManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CategoryManagerImpl.java
deleted file mode 100644
index 2d547b7bb8..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/CategoryManagerImpl.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
-* 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.application.mgt.core.impl;
-
-import org.wso2.carbon.device.application.mgt.common.Category;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationCategoryManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-
-import java.util.List;
-
-/**
- * This class is the default implementation for the CategoryManager.
- *
- */
-public class CategoryManagerImpl implements CategoryManager {
-
- @Override
- public Category createCategory(Category category) throws ApplicationManagementException {
- if (category == null) {
- throw new ApplicationCategoryManagementException("Category is null. Cannot create a category.");
- }
- if (category.getName() == null) {
- throw new ApplicationCategoryManagementException(
- "Application category name cannot be null. Application category creation failed.");
- }
- if (getCategory(category.getName()) != null) {
- throw new ApplicationCategoryManagementException("Application category wth the name " + category.getName()
- + "exists already. Please select a different name");
- }
- try {
- ConnectionManagerUtil.beginDBTransaction();
- Category createdCategory = DAOFactory.getCategoryDAO().addCategory(category);
- ConnectionManagerUtil.commitDBTransaction();
- return createdCategory;
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public List getCategories() throws ApplicationManagementException {
- try {
- ConnectionManagerUtil.openDBConnection();
- return DAOFactory.getCategoryDAO().getCategories();
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public Category getCategory(String name) throws ApplicationManagementException {
- if (name == null || name.isEmpty()) {
- throw new ApplicationCategoryManagementException("Name cannot be empty or null. Cannot get category");
- }
- try {
- ConnectionManagerUtil.openDBConnection();
- return DAOFactory.getCategoryDAO().getCategory(name);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void deleteCategory(String name) throws ApplicationManagementException {
- Category category = getCategory(name);
- if (category == null) {
- throw new NotFoundException(
- "Category with the name '" + name + "' not found. Cannot delete the " + "non-existing category");
- }
- try {
- ConnectionManagerUtil.beginDBTransaction();
- boolean isApplicationExistForCategory = DAOFactory.getApplicationDAO().isApplicationExist(name);
- if (isApplicationExistForCategory) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new ApplicationCategoryManagementException(
- "Cannot delete the the category " + name + ". Applications " + "exists for this category");
- }
- DAOFactory.getCategoryDAO().deleteCategory(name);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (ApplicationManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/LifecycleStateManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/LifecycleStateManagerImpl.java
index 9e9f8d9b74..b88c2e382c 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/LifecycleStateManagerImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/LifecycleStateManagerImpl.java
@@ -24,8 +24,8 @@ import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionExcep
import org.wso2.carbon.device.application.mgt.common.exception.LifecycleManagementException;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
import org.wso2.carbon.device.application.mgt.core.dao.LifecycleStateDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.exception.DAOException;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
+import org.wso2.carbon.device.application.mgt.core.exception.LifeCycleManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.util.List;
@@ -38,13 +38,13 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
private static final Log log = LogFactory.getLog(LifecycleStateManagerImpl.class);
@Override
- public List getLifecycleStates() throws LifecycleManagementException {
+ public List getLifecycleStates(int appReleaseId) throws LifecycleManagementException {
List lifecycleStates = null;
try {
ConnectionManagerUtil.openDBConnection();
- LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
- lifecycleStates = lifecycleStateDAO.getLifecycleStates();
- } catch (DAOException | DBConnectionException e) {
+ LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
+ lifecycleStates = lifecycleStateDAO.getLifecycleStates(appReleaseId);
+ } catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed get lifecycle states.", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
@@ -56,9 +56,9 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
public void addLifecycleState(LifecycleState state) throws LifecycleManagementException {
try {
ConnectionManagerUtil.openDBConnection();
- LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
+ LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
lifecycleStateDAO.addLifecycleState(state);
- } catch (DAOException | DBConnectionException e) {
+ } catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed to add lifecycle state", e);
} finally {
ConnectionManagerUtil.closeDBConnection();
@@ -66,13 +66,13 @@ public class LifecycleStateManagerImpl implements LifecycleStateManager {
}
@Override
- public void deleteLifecycleState(String identifier) throws LifecycleManagementException {
+ public void deleteLifecycleState(int identifier) throws LifecycleManagementException {
try {
ConnectionManagerUtil.openDBConnection();
- LifecycleStateDAO lifecycleStateDAO = DAOFactory.getLifecycleStateDAO();
+ LifecycleStateDAO lifecycleStateDAO = ApplicationManagementDAOFactory.getLifecycleStateDAO();
lifecycleStateDAO.deleteLifecycleState(identifier);
- } catch (DAOException | DBConnectionException e) {
+ } catch (LifeCycleManagementDAOException | DBConnectionException e) {
throw new LifecycleManagementException("Failed to add lifecycle state: " + identifier, e);
} finally {
ConnectionManagerUtil.closeDBConnection();
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformManagerImpl.java
deleted file mode 100644
index bff99724d1..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformManagerImpl.java
+++ /dev/null
@@ -1,561 +0,0 @@
-/*
-* 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.application.mgt.core.impl;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.TransactionManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.exception.PlatformManagementDAOException;
-import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-import org.wso2.carbon.user.api.Tenant;
-import org.wso2.carbon.user.api.TenantManager;
-import org.wso2.carbon.user.api.UserStoreException;
-import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Implementation of {@link PlatformManager}, which manages the CRUD operations on Application platforms.
- */
-public class PlatformManagerImpl implements PlatformManager {
- private Map> inMemoryStore;
- private static Log log = LogFactory.getLog(PlatformManagerImpl.class);
-
- public PlatformManagerImpl() {
- this.inMemoryStore = new HashMap<>();
- }
-
- @Override
- public void initialize(int tenantId) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- List platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
- List platformIdentifiers = new ArrayList<>();
- for (Platform platform : platforms) {
- if (!platform.isEnabled() & platform.isDefaultTenantMapping()) {
- platformIdentifiers.add(platform.getIdentifier());
- }
- }
- DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Transaction Management Exception while initializing the " + "platforms for the tenant : "
- + tenantId, e);
- } catch (DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while initializing the " + "platforms for the tenant : " + tenantId,
- e);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public List getPlatforms(int tenantId) throws PlatformManagementException {
- int platformIndex = 0;
- List platforms;
- if (log.isDebugEnabled()) {
- log.debug("Request for getting platforms received for the tenant ID " + tenantId + " at "
- + "PlatformManager level");
- }
- try {
- ConnectionManagerUtil.openDBConnection();
- platforms = DAOFactory.getPlatformDAO().getPlatforms(tenantId);
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Database Connection Exception while getting the platforms for the tenant : " + tenantId, e);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- if (log.isDebugEnabled()) {
- log.debug("Number of platforms received from DAO layer is " + platforms.size() + " for the tenant "
- + tenantId);
- }
- for (Platform platform : platforms) {
- if (platform.isFileBased()) {
- Map superTenantPlatforms = this.inMemoryStore
- .get(MultitenantConstants.SUPER_TENANT_ID);
- Platform registeredPlatform = superTenantPlatforms.get(platform.getIdentifier());
- if (registeredPlatform != null) {
- platforms.set(platformIndex, new Platform(registeredPlatform));
- if (log.isDebugEnabled()) {
- log.debug("Platform Name - " + platform.getName() + ", IsRegistered - " + true);
- }
- } else {
- platforms.remove(platformIndex);
- if (log.isDebugEnabled()) {
- log.debug("Platform Name - " + platform.getName() + ", IsRegistered - " + false);
- }
- }
- }
- platformIndex++;
- }
- if (log.isDebugEnabled()) {
- log.debug("Number of effective platforms for the tenant " + tenantId + " : " + platforms.size());
- }
- return platforms;
- }
-
- @Override
- public Platform getPlatform(int tenantId, String identifier) throws PlatformManagementException {
- Platform platform = getPlatformFromInMemory(tenantId, identifier);
- if (platform == null) {
- try {
- ConnectionManagerUtil.openDBConnection();
- platform = DAOFactory.getPlatformDAO().getPlatform(tenantId, identifier);
- if (platform != null) {
- return platform;
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to get the " + "platform with the id :" + identifier
- + " for the tenant : " + tenantId, e);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- } else {
- return new Platform(platform);
- }
- return null;
- }
-
- private Platform getPlatformFromInMemory(int tenantId, String identifier) {
- Map platformMap = this.inMemoryStore.get(tenantId);
- if (platformMap != null) {
- Platform platform = platformMap.get(identifier);
- if (platform != null) {
- return platform;
- }
- }
- if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
- platformMap = this.inMemoryStore.get(MultitenantConstants.SUPER_TENANT_ID);
- if (platformMap != null) {
- Platform platform = platformMap.get(identifier);
- if (platform != null && platform.isShared()) {
- return platform;
- }
- }
- }
- return null;
- }
-
- @Override
- public synchronized void register(int tenantId, Platform platform) throws PlatformManagementException {
- validateBeforeRegister(tenantId, platform);
- try {
- ConnectionManagerUtil.beginDBTransaction();
- int platformId = DAOFactory.getPlatformDAO().register(tenantId, platform);
- if (platform.isFileBased()) {
- platform.setId(platformId);
- Map tenantPlatforms = this.inMemoryStore.get(tenantId);
- if (tenantPlatforms == null) {
- tenantPlatforms = new HashMap<>();
- this.inMemoryStore.put(tenantId, tenantPlatforms);
- }
- if (tenantPlatforms.get(platform.getIdentifier()) == null) {
- tenantPlatforms.put(platform.getIdentifier(), platform);
- } else {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementException(
- "Platform - " + platform.getIdentifier() + " is already registered!");
- }
- }
- if (platform.isDefaultTenantMapping()) {
- try {
- if (platform.isShared()) {
- sharePlatformWithOtherTenants(platform.getIdentifier());
- }
- DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
- } catch (UserStoreException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
- e);
- }
- }
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Transaction Management Exception while trying to register a " + "platform with id " + platform
- .getIdentifier() + " for tenant " + tenantId);
- } catch (DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to register a " + "platform with id " + platform
- .getIdentifier() + " for tenant " + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void update(int tenantId, String oldPlatformIdentifier, Platform platform) throws
- PlatformManagementException {
- Platform oldPlatform = validateBeforeUpdate(tenantId, oldPlatformIdentifier, platform);
- try {
- ConnectionManagerUtil.beginDBTransaction();
- if (platform.isFileBased()) {
- Map tenantPlatforms = this.inMemoryStore.get(tenantId);
- // File based configurations will be updated in the server start-up as well.So in that case, cache,
- // will be empty.
- if (tenantPlatforms != null) {
- if (tenantPlatforms.get(oldPlatformIdentifier) == null) {
- throw new PlatformManagementException(
- "Cannot update platform with identifier " + oldPlatformIdentifier + " as it is not "
- + " existing already for the tenant " + tenantId);
- }
- } else {
- tenantPlatforms = new HashMap<>();
- this.inMemoryStore.put(tenantId, tenantPlatforms);
- }
- DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
- platform.setId(oldPlatform.getId());
- tenantPlatforms.put(platform.getIdentifier(), platform);
- } else {
- DAOFactory.getPlatformDAO().update(tenantId, oldPlatformIdentifier, platform);
- }
-
- try {
- if (platform.isShared() && !oldPlatform.isShared()) {
- sharePlatformWithOtherTenants(platform.getIdentifier());
- }
- } catch (UserStoreException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementException("Error occurred while assigning the platforms for tenants!",
- e);
- }
- if (!platform.isShared() && oldPlatform.isShared()) {
- DAOFactory.getPlatformDAO().removeMappingTenants(platform.getIdentifier());
- }
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Transaction Management Exception while trying to update " + "platform : " + oldPlatformIdentifier
- + " of tenant :" + tenantId);
- } catch (DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to update " + "platform : " + oldPlatformIdentifier
- + " of tenant :" + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void unregister(int tenantId, String identifier, boolean isFileBased) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getPlatformDAO().unregister(tenantId, identifier, isFileBased);
-
- if (isFileBased) {
- Map tenantPlatforms = this.inMemoryStore.get(tenantId);
- if (tenantPlatforms != null) {
- tenantPlatforms.remove(identifier);
- }
- }
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Transaction Management Exception while trying to un-register " + "the platform with identifier : "
- + identifier + " tenant :" + tenantId, e);
- } catch (DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to un-register " + "the platform with identifier : "
- + identifier + " tenant :" + tenantId, e);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void addMapping(int tenantId, List platformIdentifiers) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getPlatformDAO().addMapping(tenantId, platformIdentifiers);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (DBConnectionException | TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to add tenant " + "mapping for tenant ID : "
- + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void addMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
- List identifiers = new ArrayList<>();
- identifiers.add(platformIdentifier);
- addMapping(tenantId, identifiers);
- }
-
- @Override
- public void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getPlatformDAO().removeMapping(tenantId, platformIdentifier);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (DBConnectionException | TransactionManagementException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException(
- "Database Connection Exception while trying to remove tenant mapping for tenant ID : " + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void updatePlatformStatus(int tenantId, String platformIdentifier, String status)
- throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- Platform platform = DAOFactory.getPlatformDAO().getPlatform(tenantId, platformIdentifier);
-
- if (platform == null) {
- ConnectionManagerUtil.commitDBTransaction();
- throw new PlatformManagementException("Platform with identifier : " + platformIdentifier + " does not"
- + " exist for the tenant with id " + tenantId);
- } else {
- boolean isEnabledNewStatus = status.equalsIgnoreCase("ENABLED");
-
- // If the platform is already in the same status. No need to enable the platform again
- if (isEnabledNewStatus == platform.isEnabled()) {
- if (log.isDebugEnabled()) {
- log.debug("Platform with identifier : " + platformIdentifier + " is already in " +
- (isEnabledNewStatus ? "Enabled" : "Disabled") + " status. No need to update.");
- }
- ConnectionManagerUtil.commitDBTransaction();
- return;
- } else {
- if (isEnabledNewStatus) {
- DAOFactory.getPlatformDAO().addMapping(tenantId, getListOfString(platform.getIdentifier()));
- } else {
- DAOFactory.getPlatformDAO().removeMapping(tenantId, platform.getIdentifier());
- }
- if (log.isDebugEnabled()) {
- log.debug("Platform with identifier : " + platformIdentifier + " successfully " +
- (isEnabledNewStatus ? "Enabled" : "Disabled"));
- }
- }
- }
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException | DBConnectionException ex) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException("Database exception while trying to update the status of platform "
- + "with identifier '" + platformIdentifier + "' for the tenant" + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public void removePlatforms(int tenantId) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.beginDBTransaction();
- DAOFactory.getPlatformDAO().removePlatforms(tenantId);
- ConnectionManagerUtil.commitDBTransaction();
- } catch (TransactionManagementException | DBConnectionException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw new PlatformManagementDAOException("Database exception while trying to remove all the platforms for"
- + " the tenant " + tenantId);
- } catch (PlatformManagementDAOException e) {
- ConnectionManagerUtil.rollbackDBTransaction();
- throw e;
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- @Override
- public List getPlatformTags(String name) throws PlatformManagementException {
- try {
- ConnectionManagerUtil.openDBConnection();
- return DAOFactory.getPlatformDAO().getPlatformTags(name);
- } catch (DBConnectionException e) {
- throw new PlatformManagementException("Database Connection Exception while getting the platform tags that"
- + " are starting with the character sequence " + name, e);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- /**
- * To share the super-tenant platform with other tenants
- * @param platformIdentifier Identifier of the platform
- * @throws UserStoreException User Store Exception
- * @throws PlatformManagementDAOException Platform Management DAO Exception
- */
- private void sharePlatformWithOtherTenants(String platformIdentifier)
- throws UserStoreException, PlatformManagementDAOException {
- TenantManager tenantManager = DataHolder.getInstance().getRealmService().getTenantManager();
- Tenant[] tenants = tenantManager.getAllTenants();
- for (Tenant tenant : tenants) {
- DAOFactory.getPlatformDAO()
- .addMapping(tenant.getId(), getListOfString(platformIdentifier));
- }
- }
-
- /**
- * Validation need to be done before registering the platform
- *
- * @param tenantId ID of the tenant which the platform need to registered to
- * @param platform Platform that need to be registered
- * @throws PlatformManagementException Platform Management Exception
- */
- private void validateBeforeRegister(int tenantId, Platform platform) throws PlatformManagementException {
- validatePlatformSharing(tenantId, platform);
- try {
- ConnectionManagerUtil.openDBConnection();
- int existingPlatformId = DAOFactory.getPlatformDAO()
- .getSuperTenantAndOwnPlatforms(platform.getIdentifier(), tenantId);
- if (existingPlatformId != -1) {
- throw new PlatformManagementException(
- "Another platform exists with the identifier " + platform.getIdentifier() + " in the tenant "
- + tenantId + " or super-tenant. Please choose a "
- + "different identifier for your platform");
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementException(
- "Error while checking pre-conditions before registering" + " platform identifier '" + platform
- .getIdentifier() + "' for the tenant :" + tenantId);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- /**
- * Validations that need to be done before updating the platform
- *
- * @param tenantId ID of the tenant
- * @param oldPlatformIdentifier Identifier of the old platform
- * @param platform Updated platform
- * @return Old platform if all the validation succeeds
- * @throws PlatformManagementException Platform ManagementException
- */
- private Platform validateBeforeUpdate(int tenantId, String oldPlatformIdentifier, Platform platform) throws
- PlatformManagementException {
- validatePlatformSharing(tenantId, platform);
- try {
- ConnectionManagerUtil.openDBConnection();
- Platform oldPlatform = DAOFactory.getPlatformDAO().getTenantOwnedPlatform(tenantId, oldPlatformIdentifier);
- if (oldPlatform == null) {
- throw new PlatformManagementException(
- "Cannot update platform. Platform with identifier : " + oldPlatformIdentifier
- + " does not exist for the tenant : " + tenantId);
- }
- if (platform.getIdentifier() != null && !platform.getIdentifier().equals(oldPlatformIdentifier)) {
- int existingPlatformID = DAOFactory.getPlatformDAO()
- .getSuperTenantAndOwnPlatforms(platform.getIdentifier(), tenantId);
- if (existingPlatformID == -1) {
- throw new PlatformManagementException(
- "Cannot update the identifier of the platform from '" + oldPlatformIdentifier + "' to '"
- + platform.getIdentifier() + "'. Another platform exists "
- + "already with the identifier '" + platform.getIdentifier() + "' for the tenant : "
- + tenantId + " or in super-tenant");
- }
- }
- return oldPlatform;
- } catch (DBConnectionException e) {
- throw new PlatformManagementException(
- "Database error while validating the platform update with the " + "platform identifier: "
- + oldPlatformIdentifier + " for the tenant :" + tenantId);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- /**
- * To validate whether this platform can be shared or not before registering and updating the platform
- *
- * @param tenantId ID of the tenant
- * @param platform Platform to be validated for sharing
- */
- private void validatePlatformSharing(int tenantId, Platform platform) throws PlatformManagementException {
- if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
- throw new PlatformManagementException(
- "Platform sharing is a restricted operation, therefore Platform - " + platform.getIdentifier()
- + " cannot be shared by the tenant domain - " + tenantId);
- }
- try {
- ConnectionManagerUtil.openDBConnection();
- if (platform.isShared()) {
- int sharedPlatform = DAOFactory.getPlatformDAO().getMultiTenantPlatforms(platform.getIdentifier());
- if (sharedPlatform != -1) {
- throw new PlatformManagementException(
- "Platform '" + platform.getIdentifier() + "' cannot be shared as some other tenants have "
- + "platforms with the same identifier.");
- }
- }
- } catch (DBConnectionException e) {
- throw new PlatformManagementException(
- "Error while checking platform sharing conditions for " + " platform identifier '" + platform
- .getIdentifier() + "' for the tenant :" + tenantId);
- } finally {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
-
- /**
- * To get the list of the given platform Identifier
- * @param platformIdentifier Identifier of the Platform
- * @return Platform Identifier as a list
- */
- private List getListOfString(String platformIdentifier) {
- List identifiers = new ArrayList<>();
- identifiers.add(platformIdentifier);
- return identifiers;
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformStorageManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformStorageManagerImpl.java
deleted file mode 100644
index d0b71fcd2d..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/PlatformStorageManagerImpl.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * 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.application.mgt.core.impl;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.base.MultitenantConstants;
-import org.wso2.carbon.context.CarbonContext;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.device.application.mgt.common.ImageArtifact;
-import org.wso2.carbon.device.application.mgt.common.Platform;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformStorageManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
-import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
-import org.wso2.carbon.device.application.mgt.core.util.Constants;
-import org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil;
-import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-
-import static org.wso2.carbon.device.application.mgt.core.util.StorageManagementUtil.saveFile;
-
-/**
- * This is the concrete implementation of {@link PlatformStorageManager}
- */
-public class PlatformStorageManagerImpl implements PlatformStorageManager {
- private static final Log log = LogFactory.getLog(ApplicationStorageManagerImpl.class);
- private String storagePath;
-
- /**
- * This creates a new instance of PlatformStorageManager.
- * @param storagePath Storage path to store the artifacts related with platform.
- */
- public PlatformStorageManagerImpl(String storagePath) {
- this.storagePath = storagePath;
- }
-
- @Override
- public void uploadIcon(String platformIdentifier, InputStream iconFileStream) throws ResourceManagementException {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Platform platform = validatePlatform(tenantId, platformIdentifier);
-
- if (platform.isFileBased()) {
- throw new ApplicationStorageManagementException("Icons for the file based platforms need to be added "
- + "directly to the deployment location inside icon folder");
- }
- if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
- throw new PlatformStorageManagementException("Platform " + platformIdentifier
- + " is a shared platform from super-tenant. Only the super-tenant users can modify it");
- }
- if (log.isDebugEnabled()) {
- log.debug("Artifact Directory Path for saving the artifacts related with application " + platformIdentifier
- + " is " + storagePath);
- }
- StorageManagementUtil.createArtifactDirectory(storagePath);
- if (iconFileStream != null) {
- try {
- saveFile(iconFileStream, storagePath + File.separator + platform.getId());
- } catch (IOException e) {
- throw new ApplicationStorageManagementException(
- "IO Exception while saving the icon file in the server for the platform " + platformIdentifier,
- e);
- }
- }
- }
-
- @Override
- public ImageArtifact getIcon(String platformIdentifier) throws PlatformStorageManagementException {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Platform platform = validatePlatform(tenantId, platformIdentifier);
- String imageArtifactPath = storagePath + platform.getId();
- File imageFile = null;
-
- if (platform.isFileBased()) {
- imageFile = new File(MultitenantUtils.getAxis2RepositoryPath(CarbonContext.getThreadLocalCarbonContext().
- getTenantId()) + Constants.PLATFORMS_DEPLOYMENT_DIR_NAME + File.separator
- + Constants.IMAGE_ARTIFACTS[0] + File.separator + platformIdentifier);
- } else {
- imageFile = new File(imageArtifactPath);
- }
-
- if (!imageFile.exists()) {
- return null;
- } else {
- try {
- return StorageManagementUtil.createImageArtifact(imageFile, imageArtifactPath);
- } catch (FileNotFoundException e) {
- throw new PlatformStorageManagementException(
- "File not found exception while trying to get the icon for the " + "platform "
- + platformIdentifier, e);
- } catch (IOException e) {
- throw new PlatformStorageManagementException(
- "IO Exception while trying to detect the file type of the platform icon of "
- + platformIdentifier, e);
- }
- }
- }
-
- @Override
- public void deleteIcon(String platformIdentifier) throws PlatformStorageManagementException {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
- Platform platform = validatePlatform(tenantId, platformIdentifier);
- String imageArtifactPath = storagePath + platform.getId();
-
- if (platform.isShared() && tenantId != MultitenantConstants.SUPER_TENANT_ID) {
- throw new PlatformStorageManagementException("Platform " + platformIdentifier + " is a shared platform "
- + "from super-tenant. Only the super-tenant users can modify it");
- }
- if (platform.isFileBased()) {
- throw new PlatformStorageManagementException("Platform " + platformIdentifier + " is a file based one. "
- + "Please remove the relevant icon file directly from file system.");
- }
-
- File imageFile = new File(imageArtifactPath);
- if (imageFile.exists()) {
- imageFile.delete();
- }
- }
-
- /**
- * To validate the platform, whether the given identifier has a valid platform.
- *
- * @param tenantId ID of the tenant
- * @param identifier Identifier of the platform
- * @return Platform related with the particular identifier.
- */
- private Platform validatePlatform(int tenantId, String identifier) throws PlatformStorageManagementException {
- Platform platform;
- try {
- PlatformManager platformManager = DataHolder.getInstance().getPlatformManager();
- platform = platformManager.getPlatform(tenantId, identifier);
- } catch (PlatformManagementException e) {
- throw new PlatformStorageManagementException(
- "Platform Management Exception while getting the platform " + "related with the identifier "
- + identifier);
- }
-
- if (platform == null) {
- throw new PlatformStorageManagementException("Platform does not exist with the identifier " + identifier);
- }
- return platform;
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java
index 0331630f34..b6bb3f5349 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/SubscriptionManagerImpl.java
@@ -22,8 +22,6 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.internal.DataHolder;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
@@ -32,12 +30,9 @@ import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.app.mgt.DeviceApplicationMapping;
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.core.dao.DeviceManagementDAOException;
-import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
-import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@@ -103,52 +98,53 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
private List installApplication(String applicationUUID, List deviceList,
String versionName) throws ApplicationManagementException {
- List failedDeviceList = new ArrayList<>(deviceList);
- // Todo: try whether we can optimise this by sending bulk inserts to db
- // Todo: atomicity is not maintained as deveice managment provider service uses separate db connection. fix this??
- log.info("Install application: " + applicationUUID + "[" + versionName + "]" + " to: "
- + deviceList.size() + " devices.");
- for (DeviceIdentifier device : deviceList) {
- org.wso2.carbon.device.mgt.common.DeviceIdentifier deviceIdentifier = new org.wso2.carbon.device.mgt
- .common.DeviceIdentifier(device.getId(), device.getType());
- try {
- DeviceManagementProviderService dmpService = HelperUtil.getDeviceManagementProviderService();
- if (!dmpService.isEnrolled(deviceIdentifier)) {
- log.error("Device with ID: [" + device.getId() + "] is not enrolled to install the application.");
- } else {
- if (log.isDebugEnabled()) {
- log.debug("Installing application to : " + device.getId());
- }
- //Todo: generating one time download link for the application and put install operation to device.
-
- // put app install operation to the device
- ProfileOperation operation = new ProfileOperation();
- operation.setCode(INSTALL_APPLICATION);
- operation.setType(Operation.Type.PROFILE);
- operation.setPayLoad("{'type':'enterprise', 'url':'http://10.100.5.76:8000/app-debug.apk', 'app':'"
- + applicationUUID + "'}");
- List deviceIdentifiers = new ArrayList<>();
- deviceIdentifiers.add(deviceIdentifier);
- dmpService.addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID,
- operation, deviceIdentifiers);
-
- DeviceApplicationMapping deviceApp = new DeviceApplicationMapping();
- deviceApp.setDeviceIdentifier(device.getId());
- deviceApp.setApplicationUUID(applicationUUID);
- deviceApp.setVersionName(versionName);
- deviceApp.setInstalled(false);
- dmpService.addDeviceApplicationMapping(deviceApp);
-// DeviceManagementDAOFactory.openConnection();
-// DAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false);
- failedDeviceList.remove(device);
- }
- } catch (DeviceManagementException | OperationManagementException | InvalidDeviceException e) {
- log.error("Error while installing application to device[" + deviceIdentifier.getId() + "]", e);
- }
+ return null;
+// List failedDeviceList = new ArrayList<>(deviceList);
+// // Todo: try whether we can optimise this by sending bulk inserts to db
+// // Todo: atomicity is not maintained as deveice managment provider service uses separate db connection. fix this??
+// log.info("Install application: " + applicationUUID + "[" + versionName + "]" + " to: "
+// + deviceList.size() + " devices.");
+// for (DeviceIdentifier device : deviceList) {
+// org.wso2.carbon.device.mgt.common.DeviceIdentifier deviceIdentifier = new org.wso2.carbon.device.mgt
+// .common.DeviceIdentifier(device.getId(), device.getType());
+// try {
+// DeviceManagementProviderService dmpService = HelperUtil.getDeviceManagementProviderService();
+// if (!dmpService.isEnrolled(deviceIdentifier)) {
+// log.error("Device with ID: [" + device.getId() + "] is not enrolled to install the application.");
+// } else {
+// if (log.isDebugEnabled()) {
+// log.debug("Installing application to : " + device.getId());
+// }
+// //Todo: generating one time download link for the application and put install operation to device.
+//
+// // put app install operation to the device
+// ProfileOperation operation = new ProfileOperation();
+// operation.setCode(INSTALL_APPLICATION);
+// operation.setType(Operation.Type.PROFILE);
+// operation.setPayLoad("{'type':'enterprise', 'url':'http://10.100.5.76:8000/app-debug.apk', 'app':'"
+// + applicationUUID + "'}");
+// List deviceIdentifiers = new ArrayList<>();
+// deviceIdentifiers.add(deviceIdentifier);
+// dmpService.addOperation(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID,
+// operation, deviceIdentifiers);
+//
+// DeviceApplicationMapping deviceApp = new DeviceApplicationMapping();
+// deviceApp.setDeviceIdentifier(device.getId());
+// deviceApp.setApplicationUUID(applicationUUID);
+// deviceApp.setVersionName(versionName);
+// deviceApp.setInstalled(false);
+// dmpService.addDeviceApplicationMapping(deviceApp);
+//// DeviceManagementDAOFactory.openConnection();
+//// ApplicationManagementDAOFactory.getSubscriptionDAO().addDeviceApplicationMapping(device.getId(), applicationUUID, false);
+// failedDeviceList.remove(device);
+// }
+// } catch (DeviceManagementException | OperationManagementException | InvalidDeviceException e) {
+// log.error("Error while installing application to device[" + deviceIdentifier.getId() + "]", e);
+// }
// finally {
// DeviceManagementDAOFactory.closeConnection();
// }
- }
- return failedDeviceList;
+// }
+// return failedDeviceList;
}
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/UnrestrictedRoleManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/UnrestrictedRoleManagerImpl.java
new file mode 100644
index 0000000000..c4ab85ee8f
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/UnrestrictedRoleManagerImpl.java
@@ -0,0 +1,116 @@
+/*
+* 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.application.mgt.core.impl;
+
+import org.wso2.carbon.device.application.mgt.common.UnrestrictedRole;
+import org.wso2.carbon.device.application.mgt.common.Visibility;
+import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
+import org.wso2.carbon.device.application.mgt.common.exception.VisibilityManagementException;
+import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
+import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
+import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
+
+import java.util.List;
+
+//todo need to work on business logic
+/**
+ * This is the default implementation for the visibility manager.
+ */
+public class UnrestrictedRoleManagerImpl implements UnrestrictedRoleManager {
+
+ @Override
+ public Visibility put(int applicationID, Visibility visibility) throws VisibilityManagementException {
+ return null;
+// if (visibility == null) {
+// visibility = new Visibility();
+// visibility.setType(Visibility.Type.PUBLIC);
+// }
+// if (visibility.getAllowedList() == null && !visibility.getType().equals(Visibility.Type.PUBLIC)) {
+// throw new VisibilityManagementException("Visibility is configured for '" + visibility.getType()
+// + "' but doesn't have any allowed list provided!");
+// }
+// boolean isTransactionStarted = false;
+// try {
+// isTransactionStarted = ConnectionManagerUtil.isTransactionStarted();
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.beginDBTransaction();
+// }
+// VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
+// int visibilityTypeId = visibilityDAO.getVisibilityID(visibility.getType());
+// visibilityDAO.delete(applicationID);
+// visibilityDAO.add(applicationID, visibilityTypeId, visibility.getAllowedList());
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.commitDBTransaction();
+// }
+// return visibility;
+// } catch (ApplicationManagementException e) {
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.rollbackDBTransaction();
+// }
+// throw new VisibilityManagementException("Problem occured when trying to fetch the application with ID - "
+// + applicationID, e);
+// } finally {
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.closeDBConnection();
+// }
+// }
+ }
+
+ @Override
+ public List getUnrestrictedRoles(int applicationID, int tenantId) throws VisibilityManagementException {
+ try {
+ VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
+ List unrestrictedRoles = visibilityDAO.getUnrestrictedRoles(applicationID, tenantId);
+ if (unrestrictedRoles == null) {
+ return null;
+ }
+ return unrestrictedRoles;
+ } catch (ApplicationManagementException e) {
+ throw new VisibilityManagementException("Problem occured when trying to fetch the application with ID - "
+ + applicationID, e);
+ }
+ }
+
+ @Override
+ public void remove(int applicationID) throws VisibilityManagementException {
+// boolean isTransactionStarted = false;
+// try {
+// isTransactionStarted = ConnectionManagerUtil.isTransactionStarted();
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.beginDBTransaction();
+// }
+// VisibilityDAO visibilityDAO = ApplicationManagementDAOFactory.getVisibilityDAO();
+// visibilityDAO.delete(applicationID);
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.commitDBTransaction();
+// }
+// } catch (ApplicationManagementException e) {
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.rollbackDBTransaction();
+// }
+// throw new VisibilityManagementException("Problem occurred when trying to fetch the application with ID - "
+// + applicationID, e);
+// } finally {
+// if (!isTransactionStarted) {
+// ConnectionManagerUtil.closeDBConnection();
+// }
+// }
+ }
+
+}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/VisibilityManagerImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/VisibilityManagerImpl.java
deleted file mode 100644
index 85d032c561..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/impl/VisibilityManagerImpl.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
-* 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.application.mgt.core.impl;
-
-import org.wso2.carbon.device.application.mgt.common.Visibility;
-import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
-import org.wso2.carbon.device.application.mgt.common.exception.VisibilityManagementException;
-import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
-import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
-import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
-
-/**
- * This is the default implementation for the visibility manager.
- */
-public class VisibilityManagerImpl implements VisibilityManager {
-
- @Override
- public Visibility put(int applicationID, Visibility visibility) throws VisibilityManagementException {
- if (visibility == null) {
- visibility = new Visibility();
- visibility.setType(Visibility.Type.PUBLIC);
- }
- if (visibility.getAllowedList() == null && !visibility.getType().equals(Visibility.Type.PUBLIC)) {
- throw new VisibilityManagementException("Visibility is configured for '" + visibility.getType()
- + "' but doesn't have any allowed list provided!");
- }
- boolean isTransactionStarted = false;
- try {
- isTransactionStarted = ConnectionManagerUtil.isTransactionStarted();
- if (!isTransactionStarted) {
- ConnectionManagerUtil.beginDBTransaction();
- }
- VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
- int visibilityTypeId = visibilityDAO.getVisibilityID(visibility.getType());
- visibilityDAO.delete(applicationID);
- visibilityDAO.add(applicationID, visibilityTypeId, visibility.getAllowedList());
- if (!isTransactionStarted) {
- ConnectionManagerUtil.commitDBTransaction();
- }
- return visibility;
- } catch (ApplicationManagementException e) {
- if (!isTransactionStarted) {
- ConnectionManagerUtil.rollbackDBTransaction();
- }
- throw new VisibilityManagementException("Problem occured when trying to fetch the application with ID - "
- + applicationID, e);
- } finally {
- if (!isTransactionStarted) {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
- }
-
- @Override
- public Visibility get(int applicationID) throws VisibilityManagementException {
- try {
- VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
- Visibility visibility = visibilityDAO.get(applicationID);
- if (visibility.getType() == null && (visibility.getAllowedList() == null ||
- visibility.getAllowedList().isEmpty())) {
- visibility.setType(Visibility.Type.PUBLIC);
- }
- return visibility;
- } catch (ApplicationManagementException e) {
- throw new VisibilityManagementException("Problem occured when trying to fetch the application with ID - "
- + applicationID, e);
- }
- }
-
- @Override
- public void remove(int applicationID) throws VisibilityManagementException {
- boolean isTransactionStarted = false;
- try {
- isTransactionStarted = ConnectionManagerUtil.isTransactionStarted();
- if (!isTransactionStarted) {
- ConnectionManagerUtil.beginDBTransaction();
- }
- VisibilityDAO visibilityDAO = DAOFactory.getVisibilityDAO();
- visibilityDAO.delete(applicationID);
- if (!isTransactionStarted) {
- ConnectionManagerUtil.commitDBTransaction();
- }
- } catch (ApplicationManagementException e) {
- if (!isTransactionStarted) {
- ConnectionManagerUtil.rollbackDBTransaction();
- }
- throw new VisibilityManagementException("Problem occurred when trying to fetch the application with ID - "
- + applicationID, e);
- } finally {
- if (!isTransactionStarted) {
- ConnectionManagerUtil.closeDBConnection();
- }
- }
- }
-
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java
index 5019ac1cd9..8088293c28 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/DataHolder.java
@@ -21,13 +21,10 @@ package org.wso2.carbon.device.application.mgt.core.internal;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
-import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
-import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
+import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.user.core.service.RealmService;
@@ -44,22 +41,16 @@ public class DataHolder {
private ApplicationReleaseManager releaseManager;
- private CategoryManager categoryManager;
-
private CommentsManager commentsManager;
private LifecycleStateManager lifecycleStateManager;
- private PlatformManager platformManager;
-
private SubscriptionManager subscriptionManager;
- private VisibilityManager visibilityManager;
+ private UnrestrictedRoleManager unrestrictedRoleManager;
private ApplicationStorageManager applicationStorageManager;
- private PlatformStorageManager platformStorageManager;
-
private static final DataHolder applicationMgtDataHolder = new DataHolder();
private DataHolder() {
@@ -86,22 +77,14 @@ public class DataHolder {
this.applicationManager = applicationManager;
}
- public ApplicationReleaseManager getReleaseManager() {
+ public ApplicationReleaseManager getApplicationReleaseManager() {
return releaseManager;
}
- public void setReleaseManager(ApplicationReleaseManager releaseManager) {
+ public void setApplicationReleaseManager(ApplicationReleaseManager releaseManager) {
this.releaseManager = releaseManager;
}
- public CategoryManager getCategoryManager() {
- return categoryManager;
- }
-
- public void setCategoryManager(CategoryManager categoryManager) {
- this.categoryManager = categoryManager;
- }
-
public CommentsManager getCommentsManager() {
return commentsManager;
}
@@ -118,14 +101,6 @@ public class DataHolder {
this.lifecycleStateManager = lifecycleStateManager;
}
- public PlatformManager getPlatformManager() {
- return platformManager;
- }
-
- public void setPlatformManager(PlatformManager platformManager) {
- this.platformManager = platformManager;
- }
-
public SubscriptionManager getSubscriptionManager() {
return subscriptionManager;
}
@@ -134,12 +109,12 @@ public class DataHolder {
this.subscriptionManager = subscriptionManager;
}
- public VisibilityManager getVisibilityManager() {
- return visibilityManager;
+ public UnrestrictedRoleManager getVisibilityManager() {
+ return unrestrictedRoleManager;
}
- public void setVisibilityManager(VisibilityManager visibilityManager) {
- this.visibilityManager = visibilityManager;
+ public void setVisibilityManager(UnrestrictedRoleManager unrestrictedRoleManager) {
+ this.unrestrictedRoleManager = unrestrictedRoleManager;
}
public RealmService getRealmService() {
@@ -157,12 +132,4 @@ public class DataHolder {
public ApplicationStorageManager getApplicationStorageManager() {
return applicationStorageManager;
}
-
- public void setPlatformStorageManager(PlatformStorageManager platformStorageManager) {
- this.platformStorageManager = platformStorageManager;
- }
-
- public PlatformStorageManager getPlatformStorageManager() {
- return platformStorageManager;
- }
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/PlatformManagementAxis2ConfigurationObserverImpl.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/PlatformManagementAxis2ConfigurationObserverImpl.java
deleted file mode 100644
index 3c6e9cc92a..0000000000
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/PlatformManagementAxis2ConfigurationObserverImpl.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * 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.application.mgt.core.internal;
-
-import org.apache.axis2.context.ConfigurationContext;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.device.application.mgt.common.exception.PlatformManagementException;
-import org.wso2.carbon.utils.AbstractAxis2ConfigurationContextObserver;
-
-/**
- * PlatformManagementAxis2ConfigurationObserverImpl is responsible for adding relevant platform mapping of shared
- * platforms during the tenant creation time.
- */
-public class PlatformManagementAxis2ConfigurationObserverImpl extends AbstractAxis2ConfigurationContextObserver {
- private static Log log = LogFactory.getLog(PlatformManagementAxis2ConfigurationObserverImpl.class);
-
- /**
- * Whenever a new tenant creation happens, shared platforms need to be added for the relevant tenant.
- * @param tenantId Id of the tenant that is being created
- */
- @Override
- public void creatingConfigurationContext(int tenantId) {
- try {
- DataHolder.getInstance().getPlatformManager().initialize(tenantId);
- } catch (PlatformManagementException e) {
- log.error("Error while trying add platforms to the newly created tenant " + tenantId, e);
- }
- }
-
- /**
- * Whenever terminating a tenant,the platforms added by the tenant need to be removed.
- * @param configContext Configuration context.
- */
- @Override
- public void terminatingConfigurationContext(ConfigurationContext configContext) {
- PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
- int tenantId = carbonContext.getTenantId();
- try {
- DataHolder.getInstance().getPlatformManager().removePlatforms(tenantId);
- } catch (PlatformManagementException e) {
- log.error("Error while removing shared platforms while removing the tenant: " + tenantId, e);
- }
- }
-}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java
index 9de7e593b2..c7a7ad0317 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/internal/ServiceComponent.java
@@ -26,21 +26,17 @@ import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurat
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
-import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
-import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
+import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
-import org.wso2.carbon.device.application.mgt.core.dao.common.DAOFactory;
+import org.wso2.carbon.device.application.mgt.core.dao.common.ApplicationManagementDAOFactory;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ApplicationManagementUtil;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.user.core.service.RealmService;
-import org.wso2.carbon.utils.Axis2ConfigurationContextObserver;
import javax.naming.NamingException;
@@ -75,7 +71,6 @@ public class ServiceComponent {
BundleContext bundleContext = componentContext.getBundleContext();
try {
String datasourceName = ConfigurationManager.getInstance().getConfiguration().getDatasourceName();
- DAOFactory.init(datasourceName);
ApplicationManager applicationManager = ApplicationManagementUtil.getApplicationManagerInstance();
DataHolder.getInstance().setApplicationManager(applicationManager);
@@ -83,13 +78,9 @@ public class ServiceComponent {
ApplicationReleaseManager applicationReleaseManager = ApplicationManagementUtil
.getApplicationReleaseManagerInstance();
- DataHolder.getInstance().setReleaseManager(applicationReleaseManager);
+ DataHolder.getInstance().setApplicationReleaseManager(applicationReleaseManager);
bundleContext.registerService(ApplicationReleaseManager.class.getName(), applicationReleaseManager, null);
- CategoryManager categoryManager = ApplicationManagementUtil.getCategoryManagerInstance();
- DataHolder.getInstance().setCategoryManager(categoryManager);
- bundleContext.registerService(CategoryManager.class.getName(), categoryManager, null);
-
CommentsManager commentsManager = ApplicationManagementUtil.getCommentsManagerInstance();
DataHolder.getInstance().setCommentsManager(commentsManager);
bundleContext.registerService(CommentsManager.class.getName(), commentsManager, null);
@@ -98,33 +89,21 @@ public class ServiceComponent {
DataHolder.getInstance().setLifecycleStateManager(lifecycleStateManager);
bundleContext.registerService(LifecycleStateManager.class.getName(), lifecycleStateManager, null);
- PlatformManager platformManager = ApplicationManagementUtil.getPlatformManagerInstance();
- DataHolder.getInstance().setPlatformManager(platformManager);
- bundleContext.registerService(PlatformManager.class.getName(), platformManager, null);
-
SubscriptionManager subscriptionManager = ApplicationManagementUtil.getSubscriptionManagerInstance();
DataHolder.getInstance().setSubscriptionManager(subscriptionManager);
bundleContext.registerService(SubscriptionManager.class.getName(), subscriptionManager, null);
- VisibilityManager visibilityManager = ApplicationManagementUtil.getVisibilityManagerInstance();
- DataHolder.getInstance().setVisibilityManager(visibilityManager);
- bundleContext.registerService(VisibilityManager.class.getName(), visibilityManager, null);
+ UnrestrictedRoleManager unrestrictedRoleManager = ApplicationManagementUtil.getVisibilityManagerInstance();
+ DataHolder.getInstance().setVisibilityManager(unrestrictedRoleManager);
+ bundleContext.registerService(UnrestrictedRoleManager.class.getName(), unrestrictedRoleManager, null);
ApplicationStorageManager applicationStorageManager = ApplicationManagementUtil
.getApplicationStorageManagerInstance();
DataHolder.getInstance().setApplicationStorageManager(applicationStorageManager);
bundleContext.registerService(ApplicationStorageManager.class.getName(), applicationStorageManager, null);
- PlatformStorageManager platformStorageManager = ApplicationManagementUtil
- .getPlatformStorageManagerInstance();
- DataHolder.getInstance().setPlatformStorageManager(platformStorageManager);
- bundleContext.registerService(PlatformStorageManager.class.getName(), platformStorageManager, null);
-
- bundleContext.registerService(Axis2ConfigurationContextObserver.class.getName(),
- new PlatformManagementAxis2ConfigurationObserverImpl(), null);
-
- DAOFactory.init(datasourceName);
- DAOFactory.initDatabases();
+ ApplicationManagementDAOFactory.init(datasourceName);
+ ApplicationManagementDAOFactory.initDatabases();
log.info("ApplicationManagement core bundle has been successfully initialized");
} catch (InvalidConfigurationException e) {
log.error("Error while activating Application Management core component. ", e);
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java
index 1604b4768d..72f2407dcb 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/ApplicationManagementUtil.java
@@ -24,13 +24,10 @@ import org.wso2.carbon.device.application.mgt.common.exception.InvalidConfigurat
import org.wso2.carbon.device.application.mgt.common.services.ApplicationManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationReleaseManager;
import org.wso2.carbon.device.application.mgt.common.services.ApplicationStorageManager;
-import org.wso2.carbon.device.application.mgt.common.services.CategoryManager;
import org.wso2.carbon.device.application.mgt.common.services.CommentsManager;
import org.wso2.carbon.device.application.mgt.common.services.LifecycleStateManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformManager;
-import org.wso2.carbon.device.application.mgt.common.services.PlatformStorageManager;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
-import org.wso2.carbon.device.application.mgt.common.services.VisibilityManager;
+import org.wso2.carbon.device.application.mgt.common.services.UnrestrictedRoleManager;
import org.wso2.carbon.device.application.mgt.core.config.ConfigurationManager;
import org.wso2.carbon.device.application.mgt.core.config.Extension;
@@ -57,12 +54,6 @@ public class ApplicationManagementUtil {
return getInstance(extension, ApplicationReleaseManager.class);
}
- public static CategoryManager getCategoryManagerInstance() throws InvalidConfigurationException {
- ConfigurationManager configurationManager = ConfigurationManager.getInstance();
- Extension extension = configurationManager.getExtension(Extension.Name.CategoryManager);
- return getInstance(extension, CategoryManager.class);
- }
-
public static CommentsManager getCommentsManagerInstance() throws InvalidConfigurationException {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Extension extension = configurationManager.getExtension(Extension.Name.CommentsManager);
@@ -75,16 +66,10 @@ public class ApplicationManagementUtil {
return getInstance(extension, LifecycleStateManager.class);
}
- public static PlatformManager getPlatformManagerInstance() throws InvalidConfigurationException {
- ConfigurationManager configurationManager = ConfigurationManager.getInstance();
- Extension extension = configurationManager.getExtension(Extension.Name.PlatformManager);
- return getInstance(extension, PlatformManager.class);
- }
-
- public static VisibilityManager getVisibilityManagerInstance() throws InvalidConfigurationException {
+ public static UnrestrictedRoleManager getVisibilityManagerInstance() throws InvalidConfigurationException {
ConfigurationManager configurationManager = ConfigurationManager.getInstance();
Extension extension = configurationManager.getExtension(Extension.Name.VisibilityManager);
- return getInstance(extension, VisibilityManager.class);
+ return getInstance(extension, UnrestrictedRoleManager.class);
}
public static SubscriptionManager getSubscriptionManagerInstance() throws InvalidConfigurationException {
@@ -100,14 +85,6 @@ public class ApplicationManagementUtil {
return getInstance(extension, ApplicationStorageManager.class);
}
- public static PlatformStorageManager getPlatformStorageManagerInstance() throws
- InvalidConfigurationException {
- ConfigurationManager configurationManager = ConfigurationManager.getInstance();
- Extension extension = configurationManager.getExtension(Extension.Name.PlatformStorageManager);
- return getInstance(extension, PlatformStorageManager.class);
- }
-
-
private static T getInstance(Extension extension, Class cls) throws InvalidConfigurationException {
try {
Class theClass = Class.forName(extension.getClassName());
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java
index 76d01d6e83..6d55e999e4 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/Constants.java
@@ -31,6 +31,7 @@ public class Constants {
public static final String DEFAULT_CONFIG_FILE_LOCATION = CarbonUtils.getCarbonConfigDirPath() + File.separator +
Constants.APPLICATION_CONFIG_XML_FILE;
+ //can remove
public static final String PLATFORMS_DEPLOYMENT_DIR_NAME = "platforms";
public static final String PLATFORM_DEPLOYMENT_EXT = ".xml";
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java
index 94b05a69ee..0d3d5a6860 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/main/java/org/wso2/carbon/device/application/mgt/core/util/StorageManagementUtil.java
@@ -44,11 +44,9 @@ public class StorageManagementUtil {
public static void createArtifactDirectory(String artifactDirectoryPath) throws ResourceManagementException {
File artifactDirectory = new File(artifactDirectoryPath);
- if (!artifactDirectory.exists()) {
- if (!artifactDirectory.mkdirs()) {
+ if (!artifactDirectory.exists() && !artifactDirectory.mkdirs()) {
throw new ResourceManagementException(
"Cannot create directories in the path to save the application related artifacts");
- }
}
}
@@ -81,9 +79,9 @@ public class StorageManagementUtil {
outStream = new FileOutputStream(new File(path));
outStream.write(buffer);
} finally {
- if (inputStream != null) {
- inputStream.close();
- }
+
+ inputStream.close();
+
if (outStream != null) {
outStream.close();
}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml
index 618a2093b9..974cd4df3a 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.core/src/test/resources/application-mgt.xml
@@ -51,7 +51,7 @@
org.wso2.carbon.device.application.mgt.core.impl.SubscriptionManagerImpl
- org.wso2.carbon.device.application.mgt.core.impl.VisibilityManagerImpl
+ org.wso2.carbon.device.application.mgt.core.impl.UnrestrictedRoleManagerImpl
org.wso2.carbon.device.application.mgt.core.impl.VisibilityTypeManagerImpl
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml
similarity index 97%
rename from components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml
rename to components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml
index 412879e98c..ca0acc2be0 100644
--- a/components/application-mgt/org.wso2.carbon.device.application.mgt.api/pom.xml
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/pom.xml
@@ -22,13 +22,13 @@
application-mgt
org.wso2.carbon.devicemgt
- 3.0.46-SNAPSHOT
+ 3.0.217-SNAPSHOT
../pom.xml
4.0.0
- org.wso2.carbon.device.application.mgt.api
- 3.0.46-SNAPSHOT
+ org.wso2.carbon.device.application.mgt.publisher.api
+ 3.0.217-SNAPSHOT
war
WSO2 Carbon - Application Management API
WSO2 Carbon - Application Management API
@@ -66,7 +66,7 @@
-
+
@@ -85,7 +85,7 @@
org.codehaus.mojo
exec-maven-plugin
- 1.2.1
+ 1.5.0
test
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/APIUtil.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/APIUtil.java
new file mode 100644
index 0000000000..0e399d2d07
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/APIUtil.java
@@ -0,0 +1,186 @@
+/*
+ * 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.application.mgt.publisher.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.application.mgt.common.services.*;
+import org.wso2.carbon.device.application.mgt.publisher.api.beans.ErrorResponse;
+
+import javax.ws.rs.core.Response;
+
+
+/**
+ * Holds util methods required for Application-Mgt API component.
+ */
+public class APIUtil {
+
+ private static Log log = LogFactory.getLog(APIUtil.class);
+
+ private static ApplicationManager applicationManager;
+ private static LifecycleStateManager lifecycleStateManager;
+ private static ApplicationReleaseManager applicationReleaseManager;
+ private static ApplicationStorageManager applicationStorageManager;
+ private static SubscriptionManager subscriptionManager;
+ private static UnrestrictedRoleManager unrestrictedRoleManager;
+
+
+ public static ApplicationManager getApplicationManager() {
+ if (applicationManager == null) {
+ synchronized (APIUtil.class) {
+ if (applicationManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ applicationManager =
+ (ApplicationManager) ctx.getOSGiService(ApplicationManager.class, null);
+ if (applicationManager == null) {
+ String msg = "Application Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+
+ return applicationManager;
+ }
+
+ public static LifecycleStateManager getLifecycleStateManager() {
+ if (lifecycleStateManager == null) {
+ synchronized (APIUtil.class) {
+ if (lifecycleStateManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ lifecycleStateManager =
+ (LifecycleStateManager) ctx.getOSGiService(LifecycleStateManager.class, null);
+ if (lifecycleStateManager == null) {
+ String msg = "Lifecycle Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+ return lifecycleStateManager;
+ }
+
+ /**
+ * To get the Application Release Manager from the osgi context.
+ *
+ * @return ApplicationRelease Manager instance in the current osgi context.
+ */
+ public static ApplicationReleaseManager getApplicationReleaseManager() {
+ if (applicationReleaseManager == null) {
+ synchronized (APIUtil.class) {
+ if (applicationReleaseManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ applicationReleaseManager = (ApplicationReleaseManager) ctx
+ .getOSGiService(ApplicationReleaseManager.class, null);
+ if (applicationReleaseManager == null) {
+ String msg = "Application Release Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+ return applicationReleaseManager;
+ }
+
+ /**
+ * To get the Application Storage Manager from the osgi context.
+ * @return ApplicationStoreManager instance in the current osgi context.
+ */
+ public static ApplicationStorageManager getApplicationStorageManager() {
+ if (applicationStorageManager == null) {
+ synchronized (APIUtil.class) {
+ if (applicationStorageManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ applicationStorageManager = (ApplicationStorageManager) ctx
+ .getOSGiService(ApplicationStorageManager.class, null);
+ if (applicationStorageManager == null) {
+ String msg = "Application Storage Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+ return applicationStorageManager;
+ }
+
+ public static Response getResponse(Exception ex, Response.Status status) {
+ return getResponse(ex.getMessage(), status);
+ }
+
+ public static Response getResponse(String message, Response.Status status) {
+ ErrorResponse errorMessage = new ErrorResponse();
+ errorMessage.setMessage(message);
+ if (status == null) {
+ status = Response.Status.INTERNAL_SERVER_ERROR;
+ }
+ errorMessage.setCode(status.getStatusCode());
+ return Response.status(status).entity(errorMessage).build();
+ }
+
+ /**
+ * To get the Subscription Manager from the osgi context.
+ * @return SubscriptionManager instance in the current osgi context.
+ */
+ public static SubscriptionManager getSubscriptionManager() {
+ if (subscriptionManager == null) {
+ synchronized (APIUtil.class) {
+ if (subscriptionManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ subscriptionManager =
+ (SubscriptionManager) ctx.getOSGiService(SubscriptionManager.class, null);
+ if (subscriptionManager == null) {
+ String msg = "Subscription Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+
+ return subscriptionManager;
+ }
+
+ /**
+ * To get the Unrestricted Role manager from the osgi context.
+ * @return Unrestricted Role manager instance in the current osgi context.
+ */
+ public static UnrestrictedRoleManager getUnrestrictedRoleManager() {
+ if (unrestrictedRoleManager == null) {
+ synchronized (APIUtil.class) {
+ if (unrestrictedRoleManager == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ unrestrictedRoleManager =
+ (UnrestrictedRoleManager) ctx.getOSGiService(UnrestrictedRoleManager.class, null);
+ if (unrestrictedRoleManager == null) {
+ String msg = "Subscription Manager service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ }
+ }
+ }
+
+ return unrestrictedRoleManager;
+ }
+}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/FileStreamingOutput.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/FileStreamingOutput.java
new file mode 100644
index 0000000000..3c6fc98bda
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/FileStreamingOutput.java
@@ -0,0 +1,55 @@
+/*
+ * 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.application.mgt.publisher.api;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.StreamingOutput;
+
+/**
+ * FileStreamingOutput to allow the user to send the files as Stream.
+ */
+public class FileStreamingOutput implements StreamingOutput {
+ private InputStream inputStream;
+
+ public FileStreamingOutput(InputStream inputStream) {
+ this.inputStream = inputStream;
+ }
+
+ @Override
+ public void write(OutputStream outputStream) throws IOException, WebApplicationException {
+ try {
+ byte[] buffer = new byte[inputStream.available()];
+ inputStream.read(buffer);
+ outputStream.write(buffer);
+ outputStream.flush();
+ } finally {
+ if (inputStream != null) {
+ inputStream.close();
+ }
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+
+ }
+}
diff --git a/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/JSONMessageHandler.java b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/JSONMessageHandler.java
new file mode 100644
index 0000000000..16137573e7
--- /dev/null
+++ b/components/application-mgt/org.wso2.carbon.device.application.mgt.publisher.api/src/main/java/org/wso2/carbon/device/application/mgt/publisher/api/JSONMessageHandler.java
@@ -0,0 +1,92 @@
+/*
+ * 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.application.mgt.publisher.api;
+
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import org.wso2.carbon.device.application.mgt.common.jaxrs.AnnotationExclusionStrategy;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Type;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.Produces;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.ext.MessageBodyReader;
+import javax.ws.rs.ext.MessageBodyWriter;
+import javax.ws.rs.ext.Provider;
+
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
+
+/**
+ * This provider is used to change a JSON object to complex object and inversely in request and response.
+ */
+@Provider
+@Produces(APPLICATION_JSON)
+@Consumes(APPLICATION_JSON)
+public class JSONMessageHandler implements MessageBodyWriter