Merge pull request #1182 from lasanthaDLPDS/application-mgt-new

Adding New Application Management Component
This commit is contained in:
Madawa Soysa 2018-02-12 11:38:38 +05:30 committed by GitHub
commit 8403455f4b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1198 changed files with 109374 additions and 17320 deletions

1
.gitignore vendored
View File

@ -13,6 +13,7 @@ target
*.class *.class
*.swp
# Mobile Tools for Java (J2ME) # Mobile Tools for Java (J2ME)
.mtj.tmp/ .mtj.tmp/

View File

@ -1,8 +1,7 @@
# carbon-device-mgt # carbon-device-mgt
<a href='https://opensource.org/licenses/Apache-2.0'><img src='https://img.shields.io/badge/License-Apache%202.0-blue.svg'></a><br/> <a href='https://opensource.org/licenses/Apache-2.0'><img src='https://img.shields.io/badge/License-Apache%202.0-blue.svg'></a><br/>
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/badge/icon'></a> - Java7<br/> <a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt/badge/icon'></a> - Java8<br/>
<a href='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt__java8/'><img src='https://wso2.org/jenkins/job/platform-builds/job/carbon-device-mgt__java8/badge/icon'></a> - Java8
WSO2 CONNECTED DEVICE MANAGEMENT COMPONENTS WSO2 CONNECTED DEVICE MANAGEMENT COMPONENTS

View File

@ -22,13 +22,13 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name> <name>WSO2 Carbon - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description> <description>WSO2 Carbon - API Management Custom Annotation Module</description>

View File

@ -21,12 +21,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name> <name>WSO2 Carbon - API Application Management API</name>
@ -197,6 +197,32 @@
<warName>${project.artifactId}</warName> <warName>${project.artifactId}</warName>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -44,6 +44,9 @@ public class APIUtil {
private static final String DEFAULT_CDMF_API_TAG = "device_management"; 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_AGENT_API_TAG = "device_agent";
private static final String DEFAULT_CERT_API_TAG = "scep_management"; 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 final String PERMISSION_PROPERTY_NAME = "name";
public static String getAuthenticatedUser() { public static String getAuthenticatedUser() {
@ -108,6 +111,9 @@ public class APIUtil {
allowedApisTags.add(DEFAULT_CDMF_API_TAG); allowedApisTags.add(DEFAULT_CDMF_API_TAG);
allowedApisTags.add(DEFAULT_CERT_API_TAG); allowedApisTags.add(DEFAULT_CERT_API_TAG);
allowedApisTags.add(DEFAULT_AGENT_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; return allowedApisTags;
} }

View File

@ -22,12 +22,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name> <name>WSO2 Carbon - API Application Management</name>
@ -119,6 +119,32 @@
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -21,13 +21,13 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId> <artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Security Handler Component</name> <name>WSO2 Carbon - API Security Handler Component</name>
<description>WSO2 Carbon - API Management Security Handler Module</description> <description>WSO2 Carbon - API Management Security Handler Module</description>
@ -55,6 +55,11 @@
<groupId>org.json.wso2</groupId> <groupId>org.json.wso2</groupId>
<artifactId>json</artifactId> <artifactId>json</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -97,6 +102,41 @@
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -26,37 +26,8 @@ public class APIMCertificateMGTException extends Exception{
private static final long serialVersionUID = -37676242646464497L; 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) { public APIMCertificateMGTException(String msg, Exception nestedEx) {
super(msg, 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);
} }
} }

View File

@ -19,7 +19,6 @@ package org.wso2.carbon.apimgt.handlers;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.MessageContext;
import org.apache.axis2.description.HandlerDescription;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.synapse.core.axis2.Axis2MessageContext; import org.apache.synapse.core.axis2.Axis2MessageContext;
@ -51,11 +50,9 @@ import java.util.StringTokenizer;
*/ */
public class AuthenticationHandler extends AbstractHandler { public class AuthenticationHandler extends AbstractHandler {
private static final Log log = LogFactory.getLog(AuthenticationHandler.class); 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 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 JWTTOKEN = "JWTToken";
private static final String AUTHORIZATION = "Authorization"; private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Bearer "; private static final String BEARER = "Bearer ";
@ -69,15 +66,14 @@ public class AuthenticationHandler extends AbstractHandler {
public AuthenticationHandler() { public AuthenticationHandler() {
log.info("Engaging API Security Handler.........."); log.info("Engaging API Security Handler..........");
restInvoker = new RESTInvoker(); restInvoker = new RESTInvoker();
this.handlerDesc = EMPTY_HANDLER_METADATA;
this.iotServerConfiguration = Utils.initConfig(); this.iotServerConfiguration = Utils.initConfig();
} }
/** /**
* Handling the message and checking the security. * Handling the message and checking the security.
* *
* @param messageContext * @param messageContext Request message context.
* @return * @return Boolean value of the result of the processing the request.
*/ */
@Override @Override
public boolean handleRequest(org.apache.synapse.MessageContext messageContext) { public boolean handleRequest(org.apache.synapse.MessageContext messageContext) {
@ -91,16 +87,19 @@ public class AuthenticationHandler extends AbstractHandler {
Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS); Map<String, String> headers = (Map<String, String>) axisMC.getProperty(MessageContext.TRANSPORT_HEADERS);
try { try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
RESTResponse response; RESTResponse response = null;
if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) { if (headers.containsKey(AuthConstants.MDM_SIGNATURE)) {
String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE).toString(); String mdmSignature = headers.get(AuthConstants.MDM_SIGNATURE);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verify Cert:\n" + mdmSignature); log.debug("Verify Cert:\n" + mdmSignature);
} }
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
if (deviceType == null) {
return false;
}
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders(); Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(mdmSignature); certificate.setPem(mdmSignature);
@ -109,8 +108,7 @@ public class AuthenticationHandler extends AbstractHandler {
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
String str = response.getContent(); String str = response.getContent();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -125,7 +123,7 @@ public class AuthenticationHandler extends AbstractHandler {
} }
} else if (headers.containsKey(AuthConstants.PROXY_MUTUAL_AUTH_HEADER)) { } 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()) { if (log.isDebugEnabled()) {
log.debug("Verify subject DN: " + subjectDN); log.debug("Verify subject DN: " + subjectDN);
@ -133,7 +131,7 @@ public class AuthenticationHandler extends AbstractHandler {
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders(); Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(subjectDN); certificate.setPem(subjectDN);
certificate.setTenantId(tenantId); certificate.setTenantId(tenantId);
@ -141,8 +139,7 @@ public class AuthenticationHandler extends AbstractHandler {
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent()); log.debug("Verify response:" + response.getContent());
} }
@ -152,23 +149,19 @@ public class AuthenticationHandler extends AbstractHandler {
CertificateFactory cf = CertificateFactory.getInstance("X.509"); CertificateFactory cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded()); ByteArrayInputStream bais = new ByteArrayInputStream(certs[0].getEncoded());
X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais); X509Certificate x509 = (X509Certificate) cf.generateCertificate(bais);
if (bais != null) { bais.close();
bais.close();
}
if (x509 != null) { if (x509 != null) {
headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509)); headers.put(AuthConstants.PROXY_MUTUAL_AUTH_HEADER, CertificateGenerator.getCommonName(x509));
return true; return true;
} else {
response = null;
} }
} else if (headers.containsKey(AuthConstants.ENCODED_PEM)) { } 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()) { if (log.isDebugEnabled()) {
log.debug("Verify Cert:\n" + encodedPem); log.debug("Verify Cert:\n" + encodedPem);
} }
String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim()); String deviceType = this.getDeviceType(messageContext.getTo().getAddress().trim());
URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType); URI certVerifyUrl = new URI(iotServerConfiguration.getVerificationEndpoint() + deviceType);
Map<String, String> certVerifyHeaders = this.setHeaders(); Map<String, String> certVerifyHeaders = this.setHeaders(this.restInvoker);
Certificate certificate = new Certificate(); Certificate certificate = new Certificate();
certificate.setPem(encodedPem); certificate.setPem(encodedPem);
@ -176,8 +169,7 @@ public class AuthenticationHandler extends AbstractHandler {
certificate.setSerial(""); certificate.setSerial("");
Gson gson = new Gson(); Gson gson = new Gson();
String certVerifyContent = gson.toJson(certificate); String certVerifyContent = gson.toJson(certificate);
response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, null, response = restInvoker.invokePOST(certVerifyUrl, certVerifyHeaders, certVerifyContent);
null, certVerifyContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Verify response:" + response.getContent()); log.debug("Verify response:" + response.getContent());
} }
@ -224,9 +216,9 @@ public class AuthenticationHandler extends AbstractHandler {
return null; return null;
} }
private Map<String, String> setHeaders() throws APIMCertificateMGTException { private Map<String, String> setHeaders(RESTInvoker restInvoker) throws APIMCertificateMGTException {
Map<String, String> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
String accessToken = Utils.getAccessToken(iotServerConfiguration); String accessToken = Utils.getAccessToken(iotServerConfiguration, restInvoker);
map.put(AUTHORIZATION, BEARER + accessToken); map.put(AUTHORIZATION, BEARER + accessToken);
map.put(CONTENT_TYPE, "application/json"); map.put(CONTENT_TYPE, "application/json");
return map; return map;

View File

@ -17,11 +17,9 @@
*/ */
package org.wso2.carbon.apimgt.handlers.invoker; package org.wso2.carbon.apimgt.handlers.invoker;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
@ -32,42 +30,37 @@ import org.apache.http.util.EntityUtils;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map; import java.util.Map;
import java.util.Set;
public class RESTInvoker { public class RESTInvoker {
private static final Log log = LogFactory.getLog(RESTInvoker.class); 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 CloseableHttpClient client = null;
private PoolingHttpClientConnectionManager connectionManager = null;
public RESTInvoker() { public RESTInvoker() {
configureHttpClient(); configureHttpClient();
} }
private void configureHttpClient() { private void configureHttpClient() {
int connectionTimeout = 120000;
int socketTimeout = 120000;
int maxTotalConnectionsPerRoute = 100;
int maxTotalConnections = 100;
RequestConfig defaultRequestConfig = RequestConfig.custom() RequestConfig defaultRequestConfig = RequestConfig.custom()
.setExpectContinueEnabled(true) .setExpectContinueEnabled(true)
.setConnectTimeout(connectionTimeout) .setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout) .setSocketTimeout(socketTimeout)
.build(); .build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute); connectionManager.setDefaultMaxPerRoute(maxTotalConnectionsPerRoute);
connectionManager.setMaxTotal(maxTotalConnections); connectionManager.setMaxTotal(maxTotalConnections);
client = HttpClients.custom() client = HttpClients.custom()
.setConnectionManager(connectionManager) .setConnectionManager(connectionManager)
.setDefaultRequestConfig(defaultRequestConfig) .setDefaultRequestConfig(defaultRequestConfig)
.build(); .build();
if (log.isDebugEnabled()) {
if(log.isDebugEnabled()){
log.debug("REST client initialized with " + log.debug("REST client initialized with " +
"maxTotalConnection = " + maxTotalConnections + "maxTotalConnection = " + maxTotalConnections +
"maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute + "maxConnectionsPerRoute = " + maxTotalConnectionsPerRoute +
@ -76,81 +69,24 @@ public class RESTInvoker {
} }
public void closeHttpClient() { public RESTResponse invokePOST(URI uri, Map<String, String> requestHeaders, String payload) throws IOException {
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<String, String> 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<String, String> requestHeaders, String username,
String password, String payload) throws IOException {
HttpPost httpPost = null; HttpPost httpPost = null;
CloseableHttpResponse response = null; CloseableHttpResponse response = null;
Header[] headers;
int httpStatus; int httpStatus;
String contentType;
String output; String output;
try { try {
httpPost = new HttpPost(uri); httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(payload)); httpPost.setEntity(new StringEntity(payload));
if (requestHeaders != null && !requestHeaders.isEmpty()) { if (requestHeaders != null && !requestHeaders.isEmpty()) {
Object keys[] = requestHeaders.keySet().toArray(); Set<String> keys = requestHeaders.keySet();
for (Object header : keys) { for (String header : keys) {
httpPost.setHeader(header.toString(), requestHeaders.get(header).toString()); httpPost.setHeader(header, requestHeaders.get(header));
} }
} }
response = sendReceiveRequest(httpPost, username, password); response = sendReceiveRequest(httpPost);
output = IOUtils.toString(response.getEntity().getContent()); output = IOUtils.toString(response.getEntity().getContent());
headers = response.getAllHeaders();
httpStatus = response.getStatusLine().getStatusCode(); httpStatus = response.getStatusLine().getStatusCode();
contentType = response.getEntity().getContentType().getValue();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Invoked POST " + uri.toString() + log.debug("Invoked POST " + uri.toString() +
" - Input payload: " + payload + " - Response message: " + output); " - Input payload: " + payload + " - Response message: " + output);
@ -164,116 +100,11 @@ public class RESTInvoker {
httpPost.releaseConnection(); httpPost.releaseConnection();
} }
} }
return new RESTResponse(contentType, output, headers, httpStatus); return new RESTResponse(output, httpStatus);
} }
/** private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase)
* 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<String, String> 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<String, String> 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)
throws IOException { throws IOException {
CloseableHttpResponse response; return client.execute(requestBase);
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;
} }
} }

View File

@ -17,40 +17,25 @@
*/ */
package org.wso2.carbon.apimgt.handlers.invoker; package org.wso2.carbon.apimgt.handlers.invoker;
import org.apache.http.Header;
/** /**
* RESTResponse class holds the data retrieved from the HTTP invoke response. * RESTResponse class holds the data retrieved from the HTTP invoke response.
*/ */
public class RESTResponse { public class RESTResponse {
private String contentType;
private String content; private String content;
private Header[] headers;
private int httpStatus; private int httpStatus;
/** /**
* Constructor * Constructor
* *
* @param contentType from the REST invoke response
* @param content 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 * @param httpStatus from the REST invoke response
*/ */
public RESTResponse(String contentType, String content, Header[] headers, int httpStatus) { RESTResponse(String content, int httpStatus) {
this.contentType = contentType;
this.content = content; this.content = content;
this.headers = headers;
this.httpStatus = httpStatus; 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 * Get contents of the REST invoke response
@ -61,15 +46,6 @@ public class RESTResponse {
return content; 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 * Get the HTTP Status code from REST invoke response
* *

View File

@ -21,18 +21,6 @@ package org.wso2.carbon.apimgt.handlers.utils;
* This initializes the constance. * This initializes the constance.
*/ */
public class AuthConstants { 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 MDM_SIGNATURE = "mdm-signature";
public static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header"; public static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header";
public static final String MUTUAL_AUTH_HEADER = "mutual-auth-header"; public static final String MUTUAL_AUTH_HEADER = "mutual-auth-header";

View File

@ -59,14 +59,22 @@ public class Utils {
/** /**
* This method initializes the iot-api-config.xml file. * This method initializes the iot-api-config.xml file.
* @return *
* @return IoTServerConfiguration Object based on the configuration file.
*/ */
public static IOTServerConfiguration initConfig() { 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; * This methods initialized the iot-api-config.xml from provided path.
File file = new File(IOTServerAPIConfigurationPath); *
* @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); Document doc = Utils.convertToDocument(file);
JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class); 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. * 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 = "\\$\\{(.*?)\\}"; String regex = "\\$\\{(.*?)\\}";
Pattern pattern = Pattern.compile(regex); Pattern pattern = Pattern.compile(regex);
Matcher matchPattern = pattern.matcher(text); Matcher matchPattern = pattern.matcher(text);
@ -107,16 +115,18 @@ public class Utils {
/** /**
* This class build the iot-api-config.xml file. * 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 * @throws APIMCertificateMGTException
*/ */
public static Document convertToDocument(File file) throws APIMCertificateMGTException { private static Document convertToDocument(File file) throws APIMCertificateMGTException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
try { try {
DocumentBuilder docBuilder = factory.newDocumentBuilder(); factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file); return docBuilder.parse(file);
} catch (Exception e) { } catch (Exception e) {
throw new APIMCertificateMGTException("Error occurred while parsing file, while converting " + 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. * 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 * @throws APIMCertificateMGTException
*/ */
public static String getAccessToken(IOTServerConfiguration iotServerConfiguration) public static String getAccessToken(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker)
throws APIMCertificateMGTException { throws APIMCertificateMGTException {
try { try {
if (clientId == null || clientSecret == null) { if (clientId == null || clientSecret == null) {
getClientSecretes(iotServerConfiguration); getClientSecretes(iotServerConfiguration, restInvoker);
} }
URI tokenUrl = new URI(iotServerConfiguration.getOauthTokenEndpoint()); 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"; iotServerConfiguration.getPassword() + "&scope=activity-view";
String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes()); String tokenBasicAuth = "Basic " + Base64.encode((clientId + ":" + clientSecret).getBytes());
Map<String, String> tokenHeaders = new HashMap<String, String>(); Map<String, String> tokenHeaders = new HashMap<>();
tokenHeaders.put("Authorization", tokenBasicAuth); tokenHeaders.put("Authorization", tokenBasicAuth);
tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded"); tokenHeaders.put("Content-Type", "application/x-www-form-urlencoded");
RESTInvoker restInvoker = new RESTInvoker(); RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, tokenContent);
RESTResponse response = restInvoker.invokePOST(tokenUrl, tokenHeaders, null, null, tokenContent); if (log.isDebugEnabled()) {
if(log.isDebugEnabled()) {
log.debug("Token response:" + response.getContent()); log.debug("Token response:" + response.getContent());
} }
JSONObject jsonResponse = new JSONObject(response.getContent()); JSONObject jsonResponse = new JSONObject(response.getContent());
String accessToken = jsonResponse.getString("access_token"); return jsonResponse.getString("access_token");
return accessToken;
} catch (URISyntaxException e) { } catch (URISyntaxException | IOException e) {
throw new APIMCertificateMGTException("Error occurred while trying to call oauth token endpoint", e); throw new APIMCertificateMGTException("Error occurred while trying to call oauth token endpoint", e);
} catch (JSONException e) { } catch (JSONException e) {
throw new APIMCertificateMGTException("Error occurred while converting the json to object", 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. * This method register an application to get the client key and secret.
* @param iotServerConfiguration *
* @param iotServerConfiguration Instance of the IoTServerConfiguration.
* @throws APIMCertificateMGTException * @throws APIMCertificateMGTException
*/ */
private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration) private static void getClientSecretes(IOTServerConfiguration iotServerConfiguration, RESTInvoker restInvoker)
throws APIMCertificateMGTException { throws APIMCertificateMGTException {
try { try {
String username = iotServerConfiguration.getUsername(); String username = iotServerConfiguration.getUsername();
@ -180,13 +188,12 @@ public class Utils {
dcr.setCallbackUrl(AuthConstants.CALLBACK_URL); dcr.setCallbackUrl(AuthConstants.CALLBACK_URL);
dcr.setIsSaasApp(true); dcr.setIsSaasApp(true);
String dcrContent = dcr.toJSON(); String dcrContent = dcr.toJSON();
Map<String, String> dcrHeaders = new HashMap<String, String>(); Map<String, String> dcrHeaders = new HashMap<>();
String basicAuth = Base64.encode((username + ":" + password).getBytes()); String basicAuth = Base64.encode((username + ":" + password).getBytes());
dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE); dcrHeaders.put(AuthConstants.CONTENT_TYPE_HEADER, AuthConstants.CONTENT_TYPE);
dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth); dcrHeaders.put(AuthConstants.AUTHORIZATION_HEADER, AuthConstants.BASIC_AUTH_PREFIX + basicAuth);
URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint()); URI dcrUrl = new URI(iotServerConfiguration.getDynamicClientRegistrationEndpoint());
RESTInvoker restInvoker = new RESTInvoker(); RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, dcrContent);
RESTResponse response = restInvoker.invokePOST(dcrUrl, dcrHeaders, null, null, dcrContent);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("DCR response :" + response.getContent()); log.debug("DCR response :" + response.getContent());
} }

View File

@ -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("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
boolean response = this.handler.handleRequest(createSynapseMessageContext("<empty/>", 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<String, String> 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("<empty/>", 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<String, String> 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("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MUTUAL_AUTH_HEADER, "Test Header");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getValidationResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(getInvalidResponse());
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.ENCODED_PEM, "encoded pem");
setMockClient();
this.mockClient.setResponse(getAccessTokenReponse());
this.mockClient.setResponse(null);
MessageContext messageContext = createSynapseMessageContext("<empty/>", 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<String, String> transportHeaders = new HashMap<>();
transportHeaders.put(AuthConstants.MDM_SIGNATURE, "some cert");
AuthenticationHandler handler = new AuthenticationHandler();
boolean response = handler.handleRequest(createSynapseMessageContext("<empty/>", 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<String, String> 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;
}
}

View File

@ -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);
}
}

View File

@ -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");
}
}

View File

@ -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);
}
}

View File

@ -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<CloseableHttpResponse> 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;
}
}

View File

@ -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) {
}
}

View File

@ -0,0 +1,7 @@
{
"scope": "API_SUBSCRIBER_SCOPE",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "33c3be152ebf0030b3fb76f2c1f80bf8",
"access_token": "292ff0fd256814536baca0926f483c8d"
}

View File

@ -0,0 +1,656 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This is the main server configuration file
${carbon.home} represents the carbon.home system property.
Other system properties can be specified in a similar manner.
-->
<Server xmlns="http://wso2.org/projects/carbon/carbon.xml">
<!--
Product Name
-->
<Name>${product.name}</Name>
<!--
machine readable unique key to identify each product
-->
<ServerKey>${product.key}</ServerKey>
<!--
Product Version
-->
<Version>${product.version}</Version>
<!--
Host name or IP address of the machine hosting this server
e.g. www.wso2.org, 192.168.1.10
This is will become part of the End Point Reference of the
services deployed on this server instance.
-->
<!--HostName>www.wso2.org</HostName-->
<!--
Host name to be used for the Carbon management console
-->
<!--MgtHostName>mgt.wso2.org</MgtHostName-->
<!--
The URL of the back end server. This is where the admin services are hosted and
will be used by the clients in the front end server.
This is required only for the Front-end server. This is used when seperating BE server from FE server
-->
<ServerURL>local:/${carbon.context}/services/</ServerURL>
<!--
<ServerURL>https://${carbon.local.ip}:${carbon.management.port}${carbon.context}/services/</ServerURL>
-->
<!--
The URL of the index page. This is where the user will be redirected after signing in to the
carbon server.
-->
<!-- IndexPageURL>/carbon/admin/index.jsp</IndexPageURL-->
<!--
For cApp deployment, we have to identify the roles that can be acted by the current server.
The following property is used for that purpose. Any number of roles can be defined here.
Regular expressions can be used in the role.
Ex : <Role>.*</Role> means this server can act any role
-->
<ServerRoles>
<Role>${default.server.role}</Role>
</ServerRoles>
<!-- uncommnet this line to subscribe to a bam instance automatically -->
<!--<BamServerURL>https://bamhost:bamport/services/</BamServerURL>-->
<!--
The fully qualified name of the server
-->
<Package>org.wso2.carbon</Package>
<!--
Webapp context root of WSO2 Carbon management console.
-->
<WebContextRoot>/</WebContextRoot>
<!--
Proxy context path is a useful parameter to add a proxy path when a Carbon server is fronted by reverse proxy. In addtion
to the proxy host and proxy port this parameter allows you add a path component to external URLs. e.g.
URL of the Carbon server -> https://10.100.1.1:9443/carbon
URL of the reverse proxy -> https://prod.abc.com/appserver/carbon
appserver - proxy context path. This specially required whenever you are generating URLs to displace in
Carbon UI components.
-->
<!--
<MgtProxyContextPath></MgtProxyContextPath>
<ProxyContextPath></ProxyContextPath>
-->
<!-- In-order to get the registry http Port from the back-end when the default http transport is not the same-->
<!--RegistryHttpPort>9763</RegistryHttpPort-->
<!--
Number of items to be displayed on a management console page. This is used at the
backend server for pagination of various items.
-->
<ItemsPerPage>15</ItemsPerPage>
<!-- The endpoint URL of the cloud instance management Web service -->
<!--<InstanceMgtWSEndpoint>https://ec2.amazonaws.com/</InstanceMgtWSEndpoint>-->
<!--
Ports used by this server
-->
<Ports>
<!-- Ports offset. This entry will set the value of the ports defined below to
the define value + Offset.
e.g. Offset=2 and HTTPS port=9443 will set the effective HTTPS port to 9445
-->
<Offset>0</Offset>
<!-- The JMX Ports -->
<JMX>
<!--The port RMI registry is exposed-->
<RMIRegistryPort>9999</RMIRegistryPort>
<!--The port RMI server should be exposed-->
<RMIServerPort>11111</RMIServerPort>
</JMX>
<!-- Embedded LDAP server specific ports -->
<EmbeddedLDAP>
<!-- Port which embedded LDAP server runs -->
<LDAPServerPort>10389</LDAPServerPort>
<!-- Port which KDC (Kerberos Key Distribution Center) server runs -->
<KDCServerPort>8000</KDCServerPort>
</EmbeddedLDAP>
<!--
Override datasources JNDIproviderPort defined in bps.xml and datasources.properties files
-->
<!--<JNDIProviderPort>2199</JNDIProviderPort>-->
<!--Override receive port of thrift based entitlement service.-->
<ThriftEntitlementReceivePort>10500</ThriftEntitlementReceivePort>
</Ports>
<!--
JNDI Configuration
-->
<JNDI>
<!--
The fully qualified name of the default initial context factory
-->
<DefaultInitialContextFactory>org.wso2.carbon.tomcat.jndi.CarbonJavaURLContextFactory</DefaultInitialContextFactory>
<!--
The restrictions that are done to various JNDI Contexts in a Multi-tenant environment
-->
<Restrictions>
<!--
Contexts that will be available only to the super-tenant
-->
<!-- <SuperTenantOnly>
<UrlContexts>
<UrlContext>
<Scheme>foo</Scheme>
</UrlContext>
<UrlContext>
<Scheme>bar</Scheme>
</UrlContext>
</UrlContexts>
</SuperTenantOnly> -->
<!--
Contexts that are common to all tenants
-->
<AllTenants>
<UrlContexts>
<UrlContext>
<Scheme>java</Scheme>
</UrlContext>
<!-- <UrlContext>
<Scheme>foo</Scheme>
</UrlContext> -->
</UrlContexts>
</AllTenants>
<!--
All other contexts not mentioned above will be available on a per-tenant basis
(i.e. will not be shared among tenants)
-->
</Restrictions>
</JNDI>
<!--
Property to determine if the server is running an a cloud deployment environment.
This property should only be used to determine deployment specific details that are
applicable only in a cloud deployment, i.e when the server deployed *-as-a-service.
-->
<IsCloudDeployment>false</IsCloudDeployment>
<!--
Property to determine whether usage data should be collected for metering purposes
-->
<EnableMetering>false</EnableMetering>
<!-- The Max time a thread should take for execution in seconds -->
<MaxThreadExecutionTime>600</MaxThreadExecutionTime>
<!--
A flag to enable or disable Ghost Deployer. By default this is set to false. That is
because the Ghost Deployer works only with the HTTP/S transports. If you are using
other transports, don't enable Ghost Deployer.
-->
<GhostDeployment>
<Enabled>false</Enabled>
</GhostDeployment>
<!--
Eager loading or lazy loading is a design pattern commonly used in computer programming which
will initialize an object upon creation or load on-demand. In carbon, lazy loading is used to
load tenant when a request is received only. Similarly Eager loading is used to enable load
existing tenants after carbon server starts up. Using this feature, you will be able to include
or exclude tenants which are to be loaded when server startup.
We can enable only one LoadingPolicy at a given time.
1. Tenant Lazy Loading
This is the default behaviour and enabled by default. With this policy, tenants are not loaded at
server startup, but loaded based on-demand (i.e when a request is received for a tenant).
The default tenant idle time is 30 minutes.
2. Tenant Eager Loading
This is by default not enabled. It can be be enabled by un-commenting the <EagerLoading> section.
The eager loading configurations supported are as below. These configurations can be given as the
value for <Include> element with eager loading.
(i)Load all tenants when server startup - *
(ii)Load all tenants except foo.com & bar.com - *,!foo.com,!bar.com
(iii)Load only foo.com & bar.com to be included - foo.com,bar.com
-->
<Tenant>
<LoadingPolicy>
<LazyLoading>
<IdleTime>30</IdleTime>
</LazyLoading>
<!-- <EagerLoading>
<Include>*,!foo.com,!bar.com</Include>
</EagerLoading>-->
</LoadingPolicy>
</Tenant>
<!--
Caching related configurations
-->
<Cache>
<!-- Default cache timeout in minutes -->
<DefaultCacheTimeout>15</DefaultCacheTimeout>
</Cache>
<!--
Axis2 related configurations
-->
<Axis2Config>
<!--
Location of the Axis2 Services & Modules repository
This can be a directory in the local file system, or a URL.
e.g.
1. /home/wso2wsas/repository/ - An absolute path
2. repository - In this case, the path is relative to CARBON_HOME
3. file:///home/wso2wsas/repository/
4. http://wso2wsas/repository/
-->
<RepositoryLocation>${carbon.home}/repository/deployment/server/</RepositoryLocation>
<!--
Deployment update interval in seconds. This is the interval between repository listener
executions.
-->
<DeploymentUpdateInterval>15</DeploymentUpdateInterval>
<!--
Location of the main Axis2 configuration descriptor file, a.k.a. axis2.xml file
This can be a file on the local file system, or a URL
e.g.
1. /home/repository/axis2.xml - An absolute path
2. conf/axis2.xml - In this case, the path is relative to CARBON_HOME
3. file:///home/carbon/repository/axis2.xml
4. http://repository/conf/axis2.xml
-->
<ConfigurationFile>${carbon.home}/repository/conf/axis2/axis2.xml</ConfigurationFile>
<!--
ServiceGroupContextIdleTime, which will be set in ConfigurationContex
for multiple clients which are going to access the same ServiceGroupContext
Default Value is 30 Sec.
-->
<ServiceGroupContextIdleTime>30000</ServiceGroupContextIdleTime>
<!--
This repository location is used to crete the client side configuration
context used by the server when calling admin services.
-->
<ClientRepositoryLocation>${carbon.home}/repository/deployment/client/</ClientRepositoryLocation>
<!-- This axis2 xml is used in createing the configuration context by the FE server
calling to BE server -->
<clientAxis2XmlLocation>${carbon.home}/repository/conf/axis2/axis2_client.xml</clientAxis2XmlLocation>
<!-- If this parameter is set, the ?wsdl on an admin service will not give the admin service wsdl. -->
<HideAdminServiceWSDLs>true</HideAdminServiceWSDLs>
<!--WARNING-Use With Care! Uncommenting bellow parameter would expose all AdminServices in HTTP transport.
With HTTP transport your credentials and data routed in public channels are vulnerable for sniffing attacks.
Use bellow parameter ONLY if your communication channels are confirmed to be secured by other means -->
<!--HttpAdminServices>*</HttpAdminServices-->
</Axis2Config>
<!--
The default user roles which will be created when the server
is started up for the first time.
-->
<ServiceUserRoles>
<Role>
<Name>admin</Name>
<Description>Default Administrator Role</Description>
</Role>
<Role>
<Name>user</Name>
<Description>Default User Role</Description>
</Role>
</ServiceUserRoles>
<!--
Enable following config to allow Emails as usernames.
-->
<!--EnableEmailUserName>true</EnableEmailUserName-->
<!--
Security configurations
-->
<Security>
<!--
KeyStore which will be used for encrypting/decrypting passwords
and other sensitive information.
-->
<KeyStore>
<!-- Keystore file location-->
<Location>${carbon.home}/repository/resources/security/wso2carbon.jks</Location>
<!-- Keystore type (JKS/PKCS12 etc.)-->
<Type>JKS</Type>
<!-- Keystore password-->
<Password>wso2carbon</Password>
<!-- Private Key alias-->
<KeyAlias>wso2carbon</KeyAlias>
<!-- Private Key password-->
<KeyPassword>wso2carbon</KeyPassword>
</KeyStore>
<!--
System wide trust-store which is used to maintain the certificates of all
the trusted parties.
-->
<TrustStore>
<!-- trust-store file location -->
<Location>${carbon.home}/repository/resources/security/client-truststore.jks</Location>
<!-- trust-store type (JKS/PKCS12 etc.) -->
<Type>JKS</Type>
<!-- trust-store password -->
<Password>wso2carbon</Password>
</TrustStore>
<!--
The Authenticator configuration to be used at the JVM level. We extend the
java.net.Authenticator to make it possible to authenticate to given servers and
proxies.
-->
<NetworkAuthenticatorConfig>
<!--
Below is a sample configuration for a single authenticator. Please note that
all child elements are mandatory. Not having some child elements would lead to
exceptions at runtime.
-->
<!-- <Credential> -->
<!--
the pattern that would match a subset of URLs for which this authenticator
would be used
-->
<!-- <Pattern>regularExpression</Pattern> -->
<!--
the type of this authenticator. Allowed values are:
1. server
2. proxy
-->
<!-- <Type>proxy</Type> -->
<!-- the username used to log in to server/proxy -->
<!-- <Username>username</Username> -->
<!-- the password used to log in to server/proxy -->
<!-- <Password>password</Password> -->
<!-- </Credential> -->
</NetworkAuthenticatorConfig>
<!--
The Tomcat realm to be used for hosted Web applications. Allowed values are;
1. UserManager
2. Memory
If this is set to 'UserManager', the realm will pick users & roles from the system's
WSO2 User Manager. If it is set to 'memory', the realm will pick users & roles from
CARBON_HOME/repository/conf/tomcat/tomcat-users.xml
-->
<TomcatRealm>UserManager</TomcatRealm>
<!--Option to disable storing of tokens issued by STS-->
<DisableTokenStore>false</DisableTokenStore>
<!--
Security token store class name. If this is not set, default class will be
org.wso2.carbon.security.util.SecurityTokenStore
-->
<!--TokenStoreClassName>org.wso2.carbon.identity.sts.store.DBTokenStore</TokenStoreClassName-->
</Security>
<!--
The temporary work directory
-->
<WorkDirectory>${carbon.home}/tmp/work</WorkDirectory>
<!--
House-keeping configuration
-->
<HouseKeeping>
<!--
true - Start House-keeping thread on server startup
false - Do not start House-keeping thread on server startup.
The user will run it manually as and when he wishes.
-->
<AutoStart>true</AutoStart>
<!--
The interval in *minutes*, between house-keeping runs
-->
<Interval>10</Interval>
<!--
The maximum time in *minutes*, temp files are allowed to live
in the system. Files/directories which were modified more than
"MaxTempFileLifetime" minutes ago will be removed by the
house-keeping task
-->
<MaxTempFileLifetime>30</MaxTempFileLifetime>
</HouseKeeping>
<!--
Configuration for handling different types of file upload & other file uploading related
config parameters.
To map all actions to a particular FileUploadExecutor, use
<Action>*</Action>
-->
<FileUploadConfig>
<!--
The total file upload size limit in MB
-->
<TotalFileSizeLimit>100</TotalFileSizeLimit>
<Mapping>
<Actions>
<Action>keystore</Action>
<Action>certificate</Action>
<Action>*</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.AnyFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>jarZip</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.JarZipUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>dbs</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.DBSFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>tools</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsFileUploadExecutor</Class>
</Mapping>
<Mapping>
<Actions>
<Action>toolsAny</Action>
</Actions>
<Class>org.wso2.carbon.ui.transports.fileupload.ToolsAnyFileUploadExecutor</Class>
</Mapping>
</FileUploadConfig>
<!--
Processors which process special HTTP GET requests such as ?wsdl, ?policy etc.
In order to plug in a processor to handle a special request, simply add an entry to this
section.
The value of the Item element is the first parameter in the query string(e.g. ?wsdl)
which needs special processing
The value of the Class element is a class which implements
org.wso2.carbon.transport.HttpGetRequestProcessor
-->
<HttpGetRequestProcessors>
<Processor>
<Item>info</Item>
<Class>org.wso2.carbon.core.transports.util.InfoProcessor</Class>
</Processor>
<Processor>
<Item>wsdl</Item>
<Class>org.wso2.carbon.core.transports.util.Wsdl11Processor</Class>
</Processor>
<Processor>
<Item>wsdl2</Item>
<Class>org.wso2.carbon.core.transports.util.Wsdl20Processor</Class>
</Processor>
<Processor>
<Item>xsd</Item>
<Class>org.wso2.carbon.core.transports.util.XsdProcessor</Class>
</Processor>
</HttpGetRequestProcessors>
<!-- Deployment Synchronizer Configuration. t Enabled value to true when running with "svn based" dep sync.
In master nodes you need to set both AutoCommit and AutoCheckout to true
and in worker nodes set only AutoCheckout to true.
-->
<DeploymentSynchronizer>
<Enabled>false</Enabled>
<AutoCommit>false</AutoCommit>
<AutoCheckout>true</AutoCheckout>
<RepositoryType>svn</RepositoryType>
<SvnUrl>http://svnrepo.example.com/repos/</SvnUrl>
<SvnUser>username</SvnUser>
<SvnPassword>password</SvnPassword>
<SvnUrlAppendTenantId>true</SvnUrlAppendTenantId>
</DeploymentSynchronizer>
<!-- Deployment Synchronizer Configuration. Uncomment the following section when running with "registry based" dep sync.
In master nodes you need to set both AutoCommit and AutoCheckout to true
and in worker nodes set only AutoCheckout to true.
-->
<!--<DeploymentSynchronizer>
<Enabled>true</Enabled>
<AutoCommit>false</AutoCommit>
<AutoCheckout>true</AutoCheckout>
</DeploymentSynchronizer>-->
<!-- Mediation persistence configurations. Only valid if mediation features are available i.e. ESB -->
<!--<MediationConfig>
<LoadFromRegistry>false</LoadFromRegistry>
<SaveToFile>false</SaveToFile>
<Persistence>enabled</Persistence>
<RegistryPersistence>enabled</RegistryPersistence>
</MediationConfig>-->
<!--
Server intializing code, specified as implementation classes of org.wso2.carbon.core.ServerInitializer.
This code will be run when the Carbon server is initialized
-->
<ServerInitializers>
<!--<Initializer></Initializer>-->
</ServerInitializers>
<!--
Indicates whether the Carbon Servlet is required by the system, and whether it should be
registered
-->
<RequireCarbonServlet>${require.carbon.servlet}</RequireCarbonServlet>
<!--
Carbon H2 OSGI Configuration
By default non of the servers start.
name="web" - Start the web server with the H2 Console
name="webPort" - The port (default: 8082)
name="webAllowOthers" - Allow other computers to connect
name="webSSL" - Use encrypted (HTTPS) connections
name="tcp" - Start the TCP server
name="tcpPort" - The port (default: 9092)
name="tcpAllowOthers" - Allow other computers to connect
name="tcpSSL" - Use encrypted (SSL) connections
name="pg" - Start the PG server
name="pgPort" - The port (default: 5435)
name="pgAllowOthers" - Allow other computers to connect
name="trace" - Print additional trace information; for all servers
name="baseDir" - The base directory for H2 databases; for all servers
-->
<!--H2DatabaseConfiguration>
<property name="web" />
<property name="webPort">8082</property>
<property name="webAllowOthers" />
<property name="webSSL" />
<property name="tcp" />
<property name="tcpPort">9092</property>
<property name="tcpAllowOthers" />
<property name="tcpSSL" />
<property name="pg" />
<property name="pgPort">5435</property>
<property name="pgAllowOthers" />
<property name="trace" />
<property name="baseDir">${carbon.home}</property>
</H2DatabaseConfiguration-->
<!--Disabling statistics reporter by default-->
<StatisticsReporterDisabled>true</StatisticsReporterDisabled>
<!-- Enable accessing Admin Console via HTTP -->
<!-- EnableHTTPAdminConsole>true</EnableHTTPAdminConsole -->
<!--
Default Feature Repository of WSO2 Carbon.
-->
<FeatureRepository>
<RepositoryName>default repository</RepositoryName>
<RepositoryURL>${p2.repo.url}</RepositoryURL>
</FeatureRepository>
<!--
Configure API Management
-->
<APIManagement>
<!--Uses the embedded API Manager by default. If you want to use an external
API Manager instance to manage APIs, configure below externalAPIManager-->
<Enabled>true</Enabled>
<!--Uncomment and configure API Gateway and
Publisher URLs to use external API Manager instance-->
<!--ExternalAPIManager>
<APIGatewayURL>http://localhost:8281</APIGatewayURL>
<APIPublisherURL>http://localhost:8281/publisher</APIPublisherURL>
</ExternalAPIManager-->
<LoadAPIContextsInServerStartup>true</LoadAPIContextsInServerStartup>
</APIManagement>
</Server>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<ServerConfig>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>testuser</Username>
<Password>testuserpwd</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfig

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<ServerConfig>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>testuser</Username>
<Password>testuserpwd</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfig>

View File

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<ServerConfiguration>
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
<!--End point to verify the certificate-->
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
<!--Admin username/password - this is to use for oauth token generation-->
<Username>testuser</Username>
<Password>testuserpwd</Password>
<!--Dynamic client registration endpoint-->
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register</DynamicClientRegistrationEndpoint>
<!--Oauth token endpoint-->
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
<APIS>
<ContextPath>/services</ContextPath>
</APIS>
</ServerConfiguration>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<wso2registry>
<!--
For details on configuring different config & governance registries see;
http://wso2.org/library/tutorials/2010/04/sharing-registry-space-across-multiple-product-instances
-->
<currentDBConfig>wso2registry</currentDBConfig>
<readOnly>false</readOnly>
<enableCache>true</enableCache>
<registryRoot>/</registryRoot>
<dbConfig name="wso2registry">
<url>jdbc:h2:./target/databasetest/CARBON_TEST</url>
<!--userName>sa</userName>
<password>sa</password-->
<driverName>org.h2.Driver</driverName>
<maxActive>80</maxActive>
<maxWait>60000</maxWait>
<minIdle>5</minIdle>
</dbConfig>
<versionResourcesOnChange>false</versionResourcesOnChange>
<!-- NOTE: You can edit the options under "StaticConfiguration" only before the
startup. -->
<staticConfiguration>
<versioningProperties>true</versioningProperties>
<versioningComments>true</versioningComments>
<versioningTags>true</versioningTags>
<versioningRatings>true</versioningRatings>
</staticConfiguration>
</wso2registry>

View File

@ -0,0 +1,6 @@
{
"callBackURL": "www.google.lk",
"clientName": null,
"clientId": "HfEl1jJPdg5tbtrxhAwybN05QGoa",
"clientSecret": "l6c0aoLcWR3fwezHhc7XoGOht5Aa"
}

View File

@ -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-----

View File

@ -0,0 +1,30 @@
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="DeviceManagementExtensions">
<parameter name="useDefaultListeners" value="false"/>
<test name="API Management Auth Handlers" preserve-order="true">
<classes>
<class name="org.wso2.carbon.apimgt.handlers.IOTServerConfigurationTest"/>
<class name="org.wso2.carbon.apimgt.handlers.AuthenticationHandlerTest"/>
</classes>
</test>
</suite>

View File

@ -13,13 +13,13 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId> <artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Client</name> <name>WSO2 Carbon - API Management Integration Client</name>
<description>WSO2 Carbon - API Management Integration Client</description> <description>WSO2 Carbon - API Management Integration Client</description>
@ -80,6 +80,32 @@
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>

View File

@ -25,14 +25,32 @@ import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
public class IntegrationClientServiceImpl implements IntegrationClientService { public class IntegrationClientServiceImpl implements IntegrationClientService {
private static StoreClient storeClient; private static IntegrationClientServiceImpl instance;
private static PublisherClient publisherClient; private StoreClient storeClient;
private PublisherClient publisherClient;
private OAuthRequestInterceptor oAuthRequestInterceptor;
public IntegrationClientServiceImpl() { private IntegrationClientServiceImpl() {
RequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor(); oAuthRequestInterceptor = new OAuthRequestInterceptor();
storeClient = new StoreClient(oAuthRequestInterceptor); storeClient = new StoreClient(oAuthRequestInterceptor);
publisherClient = new PublisherClient(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 @Override
public StoreClient getStoreClient() { public StoreClient getStoreClient() {
return storeClient; return storeClient;

View File

@ -40,6 +40,7 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* This is a request interceptor to add oauth token header. * 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 static final long DEFAULT_REFRESH_TIME_OFFSET_IN_MILLIS = 100000;
private DCRClient dcrClient; private DCRClient dcrClient;
private static OAuthApplication oAuthApplication; private static OAuthApplication oAuthApplication;
private static Map<String, AccessTokenInfo> tenantUserTokenMap = new HashMap<>(); private static Map<String, AccessTokenInfo> tenantUserTokenMap = new ConcurrentHashMap<>();
private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class); private static final Log log = LogFactory.getLog(OAuthRequestInterceptor.class);
/** /**
@ -97,10 +98,14 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService() JWTClient jwtClient = APIIntegrationClientDataHolder.getInstance().getJwtClientManagerService()
.getJWTClient(); .getJWTClient();
tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(), tenantBasedAccessTokenInfo = jwtClient.getAccessToken(oAuthApplication.getClientId(),
oAuthApplication.getClientSecret(), username, oAuthApplication.getClientSecret(), username,
REQUIRED_SCOPE); REQUIRED_SCOPE);
tenantBasedAccessTokenInfo.setExpiresIn( tenantBasedAccessTokenInfo.setExpiresIn(
System.currentTimeMillis() + (tenantBasedAccessTokenInfo.getExpiresIn() * 1000)); 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)) { if (tenantBasedAccessTokenInfo.getScopes().contains(APIM_SUBSCRIBE_SCOPE)) {
tenantUserTokenMap.put(username, tenantBasedAccessTokenInfo); 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);
}
} }

View File

@ -79,6 +79,7 @@ public class APIMConfigReader {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
try { try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder(); DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file); return docBuilder.parse(file);

View File

@ -35,7 +35,7 @@ public class APIMClientOAuthException extends RuntimeException {
this.responseStatus = status; this.responseStatus = status;
} }
APIMClientOAuthException(String message) { public APIMClientOAuthException(String message) {
super(message); super(message);
} }

View File

@ -49,7 +49,7 @@ public class APIIntegrationClientServiceComponent {
/* Initializing webapp publisher configuration */ /* Initializing webapp publisher configuration */
APIMConfigReader.init(); APIMConfigReader.init();
BundleContext bundleContext = componentContext.getBundleContext(); BundleContext bundleContext = componentContext.getBundleContext();
bundleContext.registerService(IntegrationClientService.class.getName(), new IntegrationClientServiceImpl(), null); bundleContext.registerService(IntegrationClientService.class.getName(), IntegrationClientServiceImpl.getInstance(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("apimgt client bundle has been successfully initialized"); log.debug("apimgt client bundle has been successfully initialized");

View File

@ -26,6 +26,9 @@ import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
*/ */
public interface IntegrationClientService { public interface IntegrationClientService {
void resetUserInfo(String username, String tenantDomain);
/** /**
* *
* @return API Store Client. * @return API Store Client.

View File

@ -13,13 +13,13 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId> <artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Generated Client</name> <name>WSO2 Carbon - API Management Integration Generated Client</name>
<description>WSO2 Carbon - API Management Integration Client</description> <description>WSO2 Carbon - API Management Integration Client</description>

View File

@ -22,19 +22,24 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId> <artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Webapp Publisher</name> <name>WSO2 Carbon - API Management Webapp Publisher</name>
<description>WSO2 Carbon - API Management Webapp Publisher</description> <description>WSO2 Carbon - API Management Webapp Publisher</description>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<dependencies> <dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.osgi</groupId> <groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId> <artifactId>org.eclipse.osgi</artifactId>
@ -103,10 +108,15 @@
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId> <artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
@ -150,29 +160,54 @@
org.wso2.carbon.apimgt.annotations.*, org.wso2.carbon.apimgt.annotations.*,
org.wso2.carbon.governance.lcm.util.*, org.wso2.carbon.governance.lcm.util.*,
org.wso2.carbon.registry.core.*, org.wso2.carbon.registry.core.*,
io.swagger.annotations, io.swagger.annotations,
javax.net.ssl, javax.net.ssl,
org.scannotation, org.scannotation,
org.scannotation.archiveiterator, org.scannotation.archiveiterator,
org.w3c.dom, org.w3c.dom,
org.wso2.carbon.apimgt.integration.client.*, org.wso2.carbon.apimgt.integration.client.*,
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.core.util, org.wso2.carbon.core.util,
org.wso2.carbon.user.api, org.wso2.carbon.user.api,
org.wso2.carbon.user.core.*, org.wso2.carbon.user.core.*,
org.wso2.carbon.utils.multitenancy, org.wso2.carbon.utils.multitenancy,
org.wso2.carbon.apimgt.integration.generated.client.publisher.api, org.wso2.carbon.apimgt.integration.generated.client.publisher.api,
org.wso2.carbon.apimgt.integration.generated.client.publisher.model org.wso2.carbon.apimgt.integration.generated.client.publisher.model
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
javax.ws.rs-api, javax.ws.rs-api,
scribe;scope=compile|runtime;inline=false; scribe;scope=compile|runtime;inline=false;
</Embed-Dependency> </Embed-Dependency>
<DynamicImport-Package>*</DynamicImport-Package> <DynamicImport-Package>*</DynamicImport-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<destFile>${basedir}/target/coverage-reports/jacoco-unit.exec</destFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<dataFile>${basedir}/target/coverage-reports/jacoco-unit.exec</dataFile>
<outputDirectory>${basedir}/target/coverage-reports/site</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -57,6 +57,7 @@ public class APIConfig {
private String tenantDomain; private String tenantDomain;
private String[] tags; private String[] tags;
private Set<ApiScope> scopes; private Set<ApiScope> scopes;
private boolean isDefault = true;
@XmlElement(name = "Policy", required = true) @XmlElement(name = "Policy", required = true)
public String getPolicy() { public String getPolicy() {
@ -184,4 +185,13 @@ public class APIConfig {
public void setScopes(Set<ApiScope> scopes) { public void setScopes(Set<ApiScope> scopes) {
this.scopes = scopes; this.scopes = scopes;
} }
@XmlElement(name = "isDefault")
public boolean isDefault() {
return isDefault;
}
public void setDefault(boolean aDefault) {
isDefault = aDefault;
}
} }

View File

@ -62,7 +62,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
for (APIInfo apiInfo : apiList.getList()) { for (APIInfo apiInfo : apiList.getList()) {
if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) { if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) {
api = publisherClient.getApi().apisApiIdPut(apiInfo.getId(), api, CONTENT_TYPE, null, null); 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, publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null,
null); null);
} }
@ -83,7 +83,9 @@ public class APIPublisherServiceImpl implements APIPublisherService {
return false; return false;
} }
for (APIInfo existingApi : apiList.getList()) { 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; return true;
} }
} }
@ -106,7 +108,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
api.setStatus(PUBLISHED_STATUS); api.setStatus(PUBLISHED_STATUS);
api.setResponseCaching("DISABLED"); api.setResponseCaching("DISABLED");
api.setDestinationStatsEnabled("false"); api.setDestinationStatsEnabled("false");
api.isDefaultVersion(true); api.isDefaultVersion(config.isDefault());
List<String> transport = new ArrayList<>(); List<String> transport = new ArrayList<>();
transport.add("https"); transport.add("https");
transport.add("http"); transport.add("http");

View File

@ -55,6 +55,7 @@ public class APIPublisherUtil {
private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints"; private static final String NON_SECURED_RESOURCES = "nonSecuredEndPoints";
private static final String AUTH_TYPE_NON_SECURED = "None"; private static final String AUTH_TYPE_NON_SECURED = "None";
private static final String PARAM_IS_DEFAULT = "isDefault";
public static String getServerBaseUrl() { public static String getServerBaseUrl() {
WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance(); WebappPublisherConfig webappPublisherConfig = WebappPublisherConfig.getInstance();
@ -143,6 +144,13 @@ public class APIPublisherUtil {
apiConfig.setSecured(false); 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); String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) { if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
@ -276,7 +284,7 @@ public class APIPublisherUtil {
if(null != resourcesList) { if(null != resourcesList) {
for (ApiUriTemplate template : templates) { for (ApiUriTemplate template : templates) {
String fullPaath = ""; String fullPaath = "";
if( template.getUriTemplate() != AnnotationProcessor.WILD_CARD ) { if (!template.getUriTemplate().equals(AnnotationProcessor.WILD_CARD)) {
fullPaath = apiConfig.getContext() + template.getUriTemplate(); fullPaath = apiConfig.getContext() + template.getUriTemplate();
} }
else{ else{

View File

@ -23,53 +23,7 @@ public class InvalidConfigurationStateException extends RuntimeException {
private static final long serialVersionUID = -3151279311329070397L; 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) { public InvalidConfigurationStateException(String msg) {
super(msg); super(msg);
setErrorMessage(msg);
} }
public InvalidConfigurationStateException() {
super();
}
public InvalidConfigurationStateException(Throwable cause) {
super(cause);
}
} }

View File

@ -25,20 +25,4 @@ public class WebappPublisherConfigurationFailedException extends Exception {
public WebappPublisherConfigurationFailedException(String msg, Exception nestedEx) { public WebappPublisherConfigurationFailedException(String msg, Exception nestedEx) {
super(msg, 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);
}
} }

View File

@ -35,6 +35,7 @@ public class WebappPublisherUtil {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
try { try {
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
DocumentBuilder docBuilder = factory.newDocumentBuilder(); DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file); return docBuilder.parse(file);

View File

@ -1,38 +1,10 @@
package org.wso2.carbon.apimgt.webapp.publisher.config; package org.wso2.carbon.apimgt.webapp.publisher.config;
public class APIResourceManagementException extends Exception{ public class APIResourceManagementException extends Exception {
private static final long serialVersionUID = -3151279311929070297L; private static final long serialVersionUID = -3151279311929070297L;
private String errorMessage;
public String getErrorMessage() { public APIResourceManagementException(String msg, Exception nestedEx) {
return errorMessage; super(msg, nestedEx);
} }
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);
}
} }

View File

@ -25,24 +25,7 @@ public class APIManagerPublisherException extends Exception {
private static final long serialVersionUID = -8933142342423122660L; 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) { public APIManagerPublisherException(Throwable cause) {
super(cause); super(cause);
} }
} }

View File

@ -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<APIInfo> 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<APIInfo> 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<ApiScope> 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<String, ApiScope> apiScopes = new HashMap<>();
Set<ApiScope> 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);
}
}

View File

@ -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<APIResource> 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<APIResource> 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<APIResource> 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<APIResource> 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<APIResource> 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<ApiUriTemplate> 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();
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}

View File

@ -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<String> 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<Servlet> getServlets() {
return null;
}
@Override
public Enumeration<String> 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<String> getInitParameterNames() {
return null;
}
@Override
public boolean setInitParameter(String s, String s1) {
return false;
}
@Override
public Object getAttribute(String s) {
return null;
}
@Override
public Enumeration<String> 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 extends Servlet> T createServlet(Class<T> aClass) throws ServletException {
return null;
}
@Override
public ServletRegistration getServletRegistration(String s) {
return null;
}
@Override
public Map<String, ? extends ServletRegistration> 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 extends Filter> T createFilter(Class<T> aClass) throws ServletException {
return null;
}
@Override
public FilterRegistration getFilterRegistration(String s) {
return null;
}
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
return null;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
return null;
}
@Override
public void setSessionTrackingModes(Set<SessionTrackingMode> set) throws IllegalStateException, IllegalArgumentException {
}
@Override
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
return null;
}
@Override
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
return null;
}
@Override
public void addListener(String s) {
}
@Override
public <T extends EventListener> void addListener(T t) {
}
@Override
public void addListener(Class<? extends EventListener> aClass) {
}
@Override
public <T extends EventListener> T createListener(Class<T> aClass) throws ServletException {
return null;
}
@Override
public void declareRoles(String... strings) {
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
return null;
}
}

View File

@ -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<ApiUriTemplate> 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);
}
}

View File

@ -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)
);

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This configuration file represents the configuration that are needed
when publishing APIs to API Manager
-->
<WebappPublisherConfigs>
<!-- This host is used to define the host address which is used to publish APIs -->
<Host>https://localhost:9445</Host>
<!-- If it is true, the APIs of this instance will be published to the defined host -->
<PublishAPI>true</PublishAPI>
<!-- If it is true, the APIs of this instance will be updated when the webapps are redeployed -->
<EnabledUpdateApi>true</EnabledUpdateApi>
<!--Webapp will be published only when running below profiles-->
<Profiles>
<Profile>default</Profile>
</Profiles>
</WebappPublisherConfigs>

View File

@ -0,0 +1,50 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2017 WSO2 Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<wso2registry>
<!--
For details on configuring different config & governance registries see;
http://wso2.org/library/tutorials/2010/04/sharing-registry-space-across-multiple-product-instances
-->
<currentDBConfig>wso2registry</currentDBConfig>
<readOnly>false</readOnly>
<enableCache>true</enableCache>
<registryRoot>/</registryRoot>
<dbConfig name="wso2registry">
<url>jdbc:h2:./target/databasetest/CARBON_TEST</url>
<!--userName>sa</userName>
<password>sa</password-->
<driverName>org.h2.Driver</driverName>
<maxActive>80</maxActive>
<maxWait>60000</maxWait>
<minIdle>5</minIdle>
</dbConfig>
<versionResourcesOnChange>false</versionResourcesOnChange>
<!-- NOTE: You can edit the options under "StaticConfiguration" only before the
startup. -->
<staticConfiguration>
<versioningProperties>true</versioningProperties>
<versioningComments>true</versioningComments>
<versioningTags>true</versioningTags>
<versioningRatings>true</versioningRatings>
</staticConfiguration>
</wso2registry>

View File

@ -0,0 +1,29 @@
<!--
~ 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.
-->
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="DeviceManagementExtensions">
<parameter name="useDefaultListeners" value="false"/>
<test name="DeviceType Manager Service Test Cases" preserve-order="true">
<classes>
<class name="org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceTest"/>
</classes>
</test>
</suite>

View File

@ -0,0 +1,80 @@
<!--
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<UserManager>
<Realm>
<Configuration>
<AddAdmin>true</AddAdmin>
<AdminRole>admin</AdminRole>
<AdminUser>
<UserName>admin</UserName>
<Password>admin</Password>
</AdminUser>
<EveryOneRoleName>everyone</EveryOneRoleName>
<ReadOnly>false</ReadOnly>
<MaxUserNameListLength>500</MaxUserNameListLength>
<Property name="url">jdbc:h2:target/databasetest/CARBON_TEST</Property>
<Property name="driverName">org.h2.Driver</Property>
<Property name="maxActive">50</Property>
<Property name="maxWait">60000</Property>
<Property name="minIdle">5</Property>
</Configuration>
<UserStoreManager class="org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager">
<Property name="TenantManager">org.wso2.carbon.user.core.tenant.JDBCTenantManager</Property>
<Property name="ReadOnly">false</Property>
<Property name="MaxUserNameListLength">100</Property>
<Property name="IsEmailUserName">false</Property>
<Property name="DomainCalculation">default</Property>
<Property name="PasswordDigest">SHA-256</Property>
<Property name="StoreSaltedPassword">true</Property>
<Property name="ReadGroups">true</Property>
<Property name="WriteGroups">true</Property>
<Property name="UserNameUniqueAcrossTenants">false</Property>
<Property name="PasswordJavaRegEx">^[\S]{5,30}$</Property>
<Property name="PasswordJavaRegExViolationErrorMsg">Password length should be between 5 to 30 characters
</Property>
<Property name="PasswordJavaScriptRegEx">^[\S]{5,30}$</Property>
<Property name="UsernameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
<Property name="UsernameJavaScriptRegEx">^[\S]{3,30}$</Property>
<Property name="RolenameJavaRegEx">^[^~!#$;%^*+={}\\|\\\\&lt;&gt;,\'\"]{3,30}$</Property>
<Property name="RolenameJavaScriptRegEx">^[\S]{3,30}$</Property>
<Property name="UserRolesCacheEnabled">true</Property>
<Property name="MaxRoleNameListLength">100</Property>
<Property name="MaxUserNameListLength">100</Property>
<Property name="SharedGroupEnabled">false</Property>
<Property name="SCIMEnabled">false</Property>
<Property name="CaseSensitiveUsername">true</Property>
<Property name="MultiAttributeSeparator">,</Property>
<Property name="BulkImportSupported">true</Property>
</UserStoreManager>
<AuthorizationManager
class="org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager">
<Property name="AuthorizationCacheEnabled">true</Property>
</AuthorizationManager>
</Realm>
<SystemPermission>
<Permission>login</Permission>
<Permission>manage-configuration</Permission>
<Permission>manage-security</Permission>
<Permission>upload-services</Permission>
<Permission>manage-services</Permission>
<Permission>manage-lc-configuration</Permission>
<Permission>manage-mediation</Permission>
<Permission>monitor-system</Permission>
<Permission>delegate-identity</Permission>
</SystemPermission>
</UserManager>

View File

@ -22,13 +22,13 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - API Management Extensions Component</name> <name>WSO2 Carbon - API Management Extensions Component</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>

View File

@ -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
);
}

View File

@ -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<Attachment> attachmentList) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
InputStream iconFileStream;
InputStream bannerFileStream;
List<InputStream> 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<Attachment> attachmentList) {
ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
try {
InputStream iconFileStream = null;
InputStream bannerFileStream = null;
List<InputStream> 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<ApplicationRelease> 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<Category> 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);
}
}
}

View File

@ -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<LifecycleState> 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();
}
}

View File

@ -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<Platform> platforms = APIUtil.getPlatformManager().getPlatforms(tenantID);
List<Platform> results;
List<Platform> 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<String> 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);
}
}
}

View File

@ -24,11 +24,11 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
</parent> </parent>
<artifactId>org.wso2.carbon.device.application.mgt.authhandler</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.authhandler</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - Application Management Authentication Handler API</name> <name>WSO2 Carbon - Application Management Authentication Handler API</name>
<description>Proxy Service for Authentication Handling in WSO2 App Manager.</description> <description>Proxy Service for Authentication Handling in WSO2 App Manager.</description>

View File

@ -21,13 +21,13 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.common</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - Application Management Common</name> <name>WSO2 Carbon - Application Management Common</name>
<description>WSO2 Carbon - Application Management Common</description> <description>WSO2 Carbon - Application Management Common</description>
@ -56,6 +56,8 @@
org.apache.commons.logging, org.apache.commons.logging,
javax.xml.*, javax.xml.*,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", 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.w3c.dom,
org.json, org.json,
org.xml.sax, org.xml.sax,
@ -108,6 +110,10 @@
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -20,11 +20,8 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude; import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* Application represents the an Application in Application Store. * Application represents the an Application in Application Store.
@ -34,184 +31,60 @@ public class Application {
@Exclude @Exclude
private int id; private int id;
private String uuid;
private String name; private String name;
private String shortDescription; private String appCategory;
private String description; private String type;
private String videoName; private int isFree;
private List<String> tags; private String paymentCurrency;
private Platform platform; private List<Tag> tags;
private List<Comment> comments;
private Category category;
private Map<String, String> properties;
private Date createdAt;
private Date modifiedAt;
private Payment payment;
private Lifecycle currentLifecycle;
private List<ApplicationRelease> releases;
private Visibility visibility;
private int screenShotCount;
private User user; private User user;
private ImageArtifact icon; private List<UnrestrictedRole> unrestrictedRoles;
private ImageArtifact banner; private int isRestricted;
private List<ImageArtifact> screenShots = new ArrayList<>(); private List<ApplicationRelease> applicationReleases;
// private ApplicationRelease releaseVersion;
private DeviceType devicetype;
public int getId() { public int getId() {
return id; return id;
} }
public List<ApplicationRelease> getReleases() {
return releases;
}
public void setReleases(List<ApplicationRelease> releases) {
this.releases = releases;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(List<Comment> 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) { public void setId(int id) {
this.id = id; this.id = id;
} }
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) { this.name = name; }
this.name = name;
public String getAppCategory() {
return appCategory;
} }
public String getShortDescription() { public void setAppCategory(String appCategory) {
return shortDescription; this.appCategory = appCategory;
} }
public void setShortDescription(String shortDescription) { public List<Tag> getTags() {
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<String> getTags() {
return tags; return tags;
} }
public void setTags(List<String> tags) { public void setTags(List<Tag> tags) {
this.tags = 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<String, String> getProperties() {
return properties;
}
public void setProperties(Map<String, String> 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() { public User getUser() {
return user; return user;
} }
@ -220,33 +93,87 @@ public class Application {
this.user = user; this.user = user;
} }
public void setScreenShotCount(int screenShotCount) { public String uuidOfLatestRelease;
this.screenShotCount = screenShotCount;
public ImageArtifact iconOfLatestRelease;
public List<UnrestrictedRole> getUnrestrictedRoles() {
return unrestrictedRoles;
} }
public int getScreenShotCount() { public void setUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles) {
return screenShotCount; this.unrestrictedRoles = unrestrictedRoles;
} }
public void setIcon(ImageArtifact icon) { // public ApplicationRelease getReleaseVersion() {
this.icon = icon; // return releaseVersion;
// }
//
// public void setReleaseVersion(ApplicationRelease releaseVersion) {
// this.releaseVersion = releaseVersion;
// }
public String getType() {
return type;
} }
public void setBanner(ImageArtifact banner) { public void setType(String type) {
this.banner = banner; this.type = type;
} }
public void addScreenShot(ImageArtifact screenShot) { public int getIsFree() {
this.screenShots.add(screenShot); return isFree;
} }
@Override public void setIsFree(int isFree) {
public String toString() { this.isFree = isFree;
String app = "UUID : " + uuid + "\tName : " + name + "\tShort Description : " }
+ shortDescription;
if (currentLifecycle != null) { public String getPaymentCurrency() {
app += "\tLifecycle State : " + currentLifecycle.getLifecycleState(); return paymentCurrency;
} }
return app;
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<ApplicationRelease> getApplicationReleases() {
return applicationReleases;
}
public void setApplicationReleases(List<ApplicationRelease> applicationReleases) {
this.applicationReleases = applicationReleases;
} }
} }

View File

@ -20,38 +20,65 @@ package org.wso2.carbon.device.application.mgt.common;
import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude; import org.wso2.carbon.device.application.mgt.common.jaxrs.Exclude;
import java.util.Date; import java.sql.Timestamp;
import java.util.Map; import java.util.ArrayList;
import java.util.List;
/** /**
* This class holds the details when releasing an Application to application store. * This class holds the details when releasing an Application to application store.
*/ */
public class ApplicationRelease { public class ApplicationRelease {
private enum Channel {
PRODUCTION, ALPHA, BETA
}
@Exclude @Exclude
private int id; 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<String, String> 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; private int noOfRatedUsers;
@ -73,75 +100,199 @@ public class ApplicationRelease {
this.stars = stars; this.stars = stars;
} }
public int getId() {
return id;
}
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public String getVersionName() { public void setVersion(String version) {
return versionName; this.version = version;
} }
public void setVersionName(String versionName) { public void setTenantId(String tenantId) {
this.versionName = versionName; this.tenantId = tenantId;
} }
public String getResource() { public String getUuid() {
return resource; return uuid;
} }
public void setResource(String resource) { public void setUuid(String uuid) {
this.resource = resource; this.uuid = uuid;
} }
public Channel getReleaseChannel() { public String getReleaseType() {
return releaseChannel; return releaseType;
} }
public void setReleaseChannel(String releaseChannel) { public void setReleaseType(String releaseType) {
this.releaseChannel = Channel.valueOf(releaseChannel); this.releaseType = releaseType;
} }
public String getReleaseDetails() { public void setAppHashValue(String appHashValue) {
return releaseDetails; this.appHashValue = appHashValue;
} }
public void setReleaseDetails(String releaseDetails) { public void setIsSharedWithAllTenants(int isSharedWithAllTenants) { this.isSharedWithAllTenants = isSharedWithAllTenants; }
this.releaseDetails = releaseDetails;
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; return createdAt;
} }
public void setCreatedAt(Date createdAt) { public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt; this.createdAt = createdAt;
} }
public Application getApplication() { public String getPublishedBy() {
return application; return publishedBy;
} }
public void setApplication(Application application) { public void setPublishedBy(String publishedBy) {
this.application = application; this.publishedBy = publishedBy;
} }
public Map<String, String> getProperties() { public Timestamp getPublishedAt() {
return properties; return publishedAt;
} }
public void setProperties(Map<String, String> properties) { public void setPublishedAt(Timestamp publishedAt) {
this.properties = properties; this.publishedAt = publishedAt;
} }
public boolean isDefault() { public String getModifiedBy() {
return isDefault; return modifiedBy;
} }
public void setDefault(boolean aDefault) { public void setModifiedBy(String modifiedBy) {
isDefault = aDefault; 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;
} }
} }

View File

@ -18,39 +18,120 @@
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
import java.util.Date; import java.util.Date;
import java.util.List;
/** /**
* Represents an lifecycle of an {@link Application}. * Represents an lifecycle of an {@link Application}.
*/ */
public class Lifecycle { public class Lifecycle {
private LifecycleState lifecycleState; private int id;
private Date lifecycleStateModifiedAt; private Date createdAt;
private String getLifecycleStateModifiedBy; private String createdBy;
public LifecycleState getLifecycleState() { private int isApproved;
return lifecycleState;
private String approvedBy;
private Date approvedAt;
private int isPublished;
private String publishedBy;
private Date publishedAt;
private int isRetired;
private List<LifecycleStateTransition> lifecycleStateTransition;
public int getId() {
return id;
} }
public void setLifecycleState(LifecycleState lifecycleState) { public void setId(int id) {
this.lifecycleState = lifecycleState; this.id = id;
} }
public Date getLifecycleStateModifiedAt() { public Date getCreatedAt() {
return lifecycleStateModifiedAt; return createdAt;
} }
public void setLifecycleStateModifiedAt(Date lifecycleStateModifiedAt) { public void setCreatedAt(Date createdAt) {
this.lifecycleStateModifiedAt = lifecycleStateModifiedAt; this.createdAt = createdAt;
} }
public String getGetLifecycleStateModifiedBy() { public String getCreatedBy() {
return getLifecycleStateModifiedBy; return createdBy;
} }
public void setGetLifecycleStateModifiedBy(String getLifecycleStateModifiedBy) { public void setCreatedBy(String createdBy) {
this.getLifecycleStateModifiedBy = getLifecycleStateModifiedBy; 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<LifecycleStateTransition> getLifecycleStateTransition() {
return lifecycleStateTransition;
}
public void setLifecycleStateTransition(List<LifecycleStateTransition> lifecycleStateTransition) {
this.lifecycleStateTransition = lifecycleStateTransition;
} }
} }

View File

@ -18,18 +18,25 @@
*/ */
package org.wso2.carbon.device.application.mgt.common; package org.wso2.carbon.device.application.mgt.common;
/** import java.sql.Timestamp;
* Represents a state in {@link Lifecycle}.
*/
public class LifecycleState { public class LifecycleState {
private int id; 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() { public int getId() {
return id; return id;
@ -39,27 +46,60 @@ public class LifecycleState {
this.id = id; this.id = id;
} }
public String getName() { public String getCurrentState() {
return name; return currentState;
} }
public void setName(String name) { public void setCurrentState(String currentState) {
this.name = name; this.currentState = currentState;
} }
public String getIdentifier() { public String getPreviousState() {
return identifier; return previousState;
} }
public void setIdentifier(String identifier) { public void setPreviousState(String previousState) {
this.identifier = identifier; this.previousState = previousState;
} }
public String getDescription() { public String getUpdatedBy() {
return description; return updatedBy;
} }
public void setDescription(String description) { public void setUpdatedBy(String updatedBy) {
this.description = description; 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;
}
} }

View File

@ -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<String> tags;
private List<Property> 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<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> 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;
}
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -18,11 +18,9 @@
*/ */
package org.wso2.carbon.device.application.mgt.common.services; 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.*;
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.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import java.util.List; import java.util.List;
@ -62,6 +60,15 @@ public interface ApplicationManager {
*/ */
ApplicationList getApplications(Filter filter) throws ApplicationManagementException; 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. * To change the lifecycle of the Application.
* *
@ -85,9 +92,48 @@ public interface ApplicationManager {
/** /**
* To get Application with the given UUID. * 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 * @return the Application identified by the UUID
* @throws ApplicationManagementException Application Management Exception. * @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<UnrestrictedRole> 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<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException;
} }

View File

@ -33,11 +33,11 @@ public interface ApplicationReleaseManager {
/** /**
* To create an application release for an Application. * 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. * @param applicationRelease ApplicatonRelease that need to be be created.
* @return the unique id of the application release, if the application release succeeded else -1 * @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; throws ApplicationManagementException;
/** /**
@ -45,19 +45,29 @@ public interface ApplicationReleaseManager {
* *
* @param applicationUuid UUID of the Application. * @param applicationUuid UUID of the Application.
* @param version Version of the ApplicationRelease that need to be retrieved. * @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. * @return ApplicationRelease related with particular Application UUID and version.
* @throws ApplicationManagementException ApplicationManagementException * @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. * 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. * @return the List of the Application releases related with the particular Application.
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
List<ApplicationRelease> getReleases(String applicationUuid) throws ApplicationManagementException; List<ApplicationRelease> getReleases(int applicationId) throws ApplicationManagementException;
/** /**
* To make a particular application release as the default / not default-one * 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. * To update with a new release for an Application.
* *
* @param applicationUuid UUID of the Application * @param appId ID of the Application
* @param applicationRelease ApplicationRelease * @param applicationRelease ApplicationRelease
* @return Updated Application Release. * @return Updated Application Release.
* @throws ApplicationManagementException Application Management Exception. * @throws ApplicationManagementException Application Management Exception.
*/ */
ApplicationRelease updateRelease(String applicationUuid, ApplicationRelease applicationRelease) ApplicationRelease updateRelease(int appId, ApplicationRelease applicationRelease)
throws ApplicationManagementException; throws ApplicationManagementException;
/** /**
@ -87,9 +97,10 @@ public interface ApplicationReleaseManager {
* *
* @param applicationUuid UUID of the Application, in which the ApplicationRelease need to be deleted. * @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 version Version of the ApplicationRelease that need to be deleted.
* @param releaseType Release type of the application.
* @throws ApplicationManagementException Application Management Exception. * @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. * To delete all the application releases related with the the particular application.

View File

@ -19,7 +19,9 @@
package org.wso2.carbon.device.application.mgt.common.services; 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.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.ApplicationStorageManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.ResourceManagementException; 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. * 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 iconFile Icon File input stream
* @param bannerFile Banner File input stream * @param bannerFile Banner File input stream
* @throws ResourceManagementException Resource Management Exception. * @throws ResourceManagementException Resource Management Exception.
*/ */
void uploadImageArtifacts(String applicationUUID, InputStream iconFile, InputStream bannerFile, ApplicationRelease uploadImageArtifacts(ApplicationRelease applicationRelease,
List<InputStream> screenshots) throws ResourceManagementException; InputStream iconFile, InputStream bannerFile, List<InputStream> 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<InputStream> screenshots)
throws ResourceManagementException, ApplicationManagementException;
/** /**
* To upload release artifacts for an Application. * To upload release artifacts for an Application.
* *
* @param applicationUUID UUID of the application related with the release. * @param applicationRelease Application Release Object.
* @param versionName Name of version of the Applcation Release.
* @param binaryFile Binary File for the release. * @param binaryFile Binary File for the release.
* @throws ResourceManagementException Resource Management Exception. * @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; throws ResourceManagementException;
/** /**

View File

@ -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<Category> 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;
}

View File

@ -28,9 +28,9 @@ import java.util.List;
*/ */
public interface LifecycleStateManager { public interface LifecycleStateManager {
List<LifecycleState> getLifecycleStates() throws LifecycleManagementException; List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifecycleManagementException;
void addLifecycleState(LifecycleState state) throws LifecycleManagementException; void addLifecycleState(LifecycleState state) throws LifecycleManagementException;
void deleteLifecycleState(String identifier) throws LifecycleManagementException; void deleteLifecycleState(int identifier) throws LifecycleManagementException;
} }

View File

@ -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<Platform> 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<String> 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<String> getPlatformTags(String name) throws PlatformManagementException;
}

View File

@ -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;
}

View File

@ -18,15 +18,18 @@
package org.wso2.carbon.device.application.mgt.common.services; 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.Visibility;
import org.wso2.carbon.device.application.mgt.common.exception.VisibilityManagementException; 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 interface manages all the operations related with Application Visibility.
* This will be invoking the necessary backend calls for the data bases layer * This will be invoking the necessary backend calls for the data bases layer
* and provide the functional implementation. * and provide the functional implementation.
*/ */
public interface VisibilityManager { public interface UnrestrictedRoleManager {
/** /**
* Add (if there is no visibility configuration for the application) or * 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. * Returns the Visibility configuration of the provided applicationUUID.
* *
* @param applicationID The ID of the application * @param applicationID The ID of the application
* @param tenantId tenant Id
* @return Visibility configuration * @return Visibility configuration
*/ */
Visibility get(int applicationID) throws VisibilityManagementException; List<UnrestrictedRole> getUnrestrictedRoles(int applicationID, int tenantId) throws VisibilityManagementException;
/** /**
* Remove the visibility configuration mapping for the provided application. * Remove the visibility configuration mapping for the provided application.

View File

@ -21,13 +21,13 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.core</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.core</artifactId>
<version>3.0.46-SNAPSHOT</version> <version>3.0.217-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - Application Management Core</name> <name>WSO2 Carbon - Application Management Core</name>
<description>WSO2 Carbon - Application Management Core</description> <description>WSO2 Carbon - Application Management Core</description>
@ -78,7 +78,10 @@
org.wso2.carbon, org.wso2.carbon,
org.apache.commons.io, org.apache.commons.io,
org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}", 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}"
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.application.mgt.core.internal.*, !org.wso2.carbon.device.application.mgt.core.internal.*,

View File

@ -18,12 +18,9 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; 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.*;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
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.core.exception.ApplicationManagementDAOException; import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException;
import java.util.List; import java.util.List;
/** /**
@ -38,7 +35,25 @@ public interface ApplicationDAO {
* @return Created Application. * @return Created Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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<Tag> 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. * To get the applications that satisfy the given criteria.
@ -50,26 +65,54 @@ public interface ApplicationDAO {
*/ */
ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException; 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 * 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 tenantId ID of the tenant.
* @param userName Name of the user. * @param appType Type of the application.
* @return the application * @return the application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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 * 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. * @param tenantId ID of the tenant.
* @return ID of the Application. * @return ID of the Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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. * To edit the given application.
@ -79,16 +122,16 @@ public interface ApplicationDAO {
* @return Updated Application. * @return Updated Application.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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 appId ID of the application.
* @param tenantId ID of tenant which the Application belongs to.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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. * To get the application count that satisfies gives search query.
@ -99,13 +142,6 @@ public interface ApplicationDAO {
*/ */
int getApplicationCount(Filter filter) throws ApplicationManagementDAOException; 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. * To delete the tags of a application.
@ -114,47 +150,5 @@ public interface ApplicationDAO {
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
void deleteTags(int applicationId) throws ApplicationManagementDAOException; 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<LifecycleStateTransition> 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;
} }

View File

@ -35,27 +35,34 @@ public interface ApplicationReleaseDAO {
* @return Unique ID of the relevant release. * @return Unique ID of the relevant release.
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
* To get a release details with the particular version. * 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 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 * @return ApplicationRelease for the particular version of the given application
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @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; ApplicationManagementDAOException;
/** /**
* To get all the releases of a particular application. * 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 * @return list of the application releases
* @throws ApplicationManagementDAOException Application Management DAO Exception. * @throws ApplicationManagementDAOException Application Management DAO Exception.
*/ */
List<ApplicationRelease> getApplicationReleases(String applicationUUID, int tenantId) throws List<ApplicationRelease> getApplicationReleases(String applicationName, String applicationType, int tenantId) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
/** /**
@ -66,6 +73,15 @@ public interface ApplicationReleaseDAO {
*/ */
ApplicationRelease updateRelease(ApplicationRelease applicationRelease) throws ApplicationManagementDAOException; 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. * To delete a particular release.
* *
@ -75,23 +91,4 @@ public interface ApplicationReleaseDAO {
*/ */
void deleteRelease(int id, String version) throws ApplicationManagementDAOException; 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;
} }

View File

@ -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<Category> 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;
}

View File

@ -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.common.LifecycleState;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; 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; import java.util.List;
@ -29,12 +29,12 @@ import java.util.List;
*/ */
public interface LifecycleStateDAO { public interface LifecycleStateDAO {
LifecycleState getLifeCycleStateByIdentifier(String identifier) throws ApplicationManagementDAOException; LifecycleState getLatestLifeCycleStateByReleaseID(int identifier) throws ApplicationManagementDAOException;
List<LifecycleState> getLifecycleStates() throws DAOException; List<LifecycleState> 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;
} }

View File

@ -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<String> platformIdentifiers) throws PlatformManagementDAOException;
void removeMapping(int tenantId, String platformIdentifier) throws PlatformManagementDAOException;
void removeMappingTenants(String platformIdentifier) throws PlatformManagementDAOException;
List<Platform> 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<String> getPlatformTags(String name) throws PlatformManagementDAOException;
}

View File

@ -18,7 +18,7 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao; 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 org.wso2.carbon.device.application.mgt.core.exception.VisibilityManagementDAOException;
import java.util.List; import java.util.List;
@ -30,13 +30,18 @@ import java.util.List;
*/ */
public interface VisibilityDAO { 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<UnrestrictedRole> unrestrictedRoles, int applicationId, int tenantId) throws
VisibilityManagementDAOException;
void add(int applicationID, int visibilityTypeID, List<String> allowedList) List<UnrestrictedRole> getUnrestrictedRoles(int applicationId, int tenantId) throws VisibilityManagementDAOException;
throws VisibilityManagementDAOException;
void delete(int applicationId) throws VisibilityManagementDAOException; void deleteUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles, int applicationId, int tenantId) throws
VisibilityManagementDAOException;
Visibility get(int applicationID) throws VisibilityManagementDAOException;
} }

View File

@ -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.ApplicationMgtDatabaseCreator;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil; 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.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.DeviceTypeDAO;
import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.DeviceTypeDAOImpl;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator; import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.sql.SQLException; 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 * 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 * 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 { public class ApplicationManagementDAOFactory {
private static String databaseEngine; private static String databaseEngine;
private static DataSource dataSource;
private static final Log log = LogFactory.getLog(ApplicationManagementDAOFactory.class); private static final Log log = LogFactory.getLog(ApplicationManagementDAOFactory.class);
public static void init(String datasourceName) { public static void init(String datasourceName) {
ConnectionManagerUtil.resolveDataSource(datasourceName); ConnectionManagerUtil.resolveDataSource(datasourceName);
databaseEngine = ConnectionManagerUtil.getDatabaseType(); 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() { public static ApplicationDAO getApplicationDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
@ -131,7 +109,6 @@ public class ApplicationManagementDAOFactory {
/** /**
* To get the instance of VisibilityDAOImplementation of the particular database engine. * To get the instance of VisibilityDAOImplementation of the particular database engine.
*
* @return specific VisibilityDAOImplementation * @return specific VisibilityDAOImplementation
*/ */
public static VisibilityDAO getVisibilityDAO() { public static VisibilityDAO getVisibilityDAO() {
@ -149,7 +126,6 @@ public class ApplicationManagementDAOFactory {
/** /**
* To get the instance of SubscriptionDAOImplementation of the particular database engine. * To get the instance of SubscriptionDAOImplementation of the particular database engine.
*
* @return GenericSubscriptionDAOImpl * @return GenericSubscriptionDAOImpl
*/ */
public static SubscriptionDAO getSubscriptionDAO() { public static SubscriptionDAO getSubscriptionDAO() {
@ -168,37 +144,31 @@ public class ApplicationManagementDAOFactory {
/** /**
* To get the instance of DeviceTypeDAOImpl of the particular database engine. * To get the instance of DeviceTypeDAOImpl of the particular database engine.
*
* @return DeviceTypeDAOImpl * @return DeviceTypeDAOImpl
*/ */
public static DeviceTypeDAO getDeviceTypeDAO() { public static DeviceTypeDAO getDeviceTypeDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL: case Constants.DataBaseTypes.DB_TYPE_MYSQL:
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new DeviceTypeDAOImpl(); return new DeviceTypeDAOImpl();
default: default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
} }
} }
throw new IllegalStateException("Database engine has not initialized properly."); throw new IllegalStateException("Database engine has not initialized properly.");
} }
/** public static CommentDAO getCommentDAO() {
* To get the instance of LifecycleDAOImplementation of the particular database engine.
*
* @return GenericLifecycleDAOImpl
*/
public static LifecycleStateDAO getLifecycleDAO() {
if (databaseEngine != null) { if (databaseEngine != null) {
switch (databaseEngine) { switch (databaseEngine) {
case Constants.DataBaseTypes.DB_TYPE_H2: case Constants.DataBaseTypes.DB_TYPE_H2:
case Constants.DataBaseTypes.DB_TYPE_MYSQL: case Constants.DataBaseTypes.DB_TYPE_MYSQL:
case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL: case Constants.DataBaseTypes.DB_TYPE_POSTGRESQL:
return new GenericLifecycleStateImpl(); return new CommentDAOImpl();
default: default:
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
} }
} }
throw new IllegalStateException("Database engine has not initialized properly."); 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); "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.");
}
} }

View File

@ -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);
}
}
}

View File

@ -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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; 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.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.PaginationRequest;
import org.wso2.carbon.device.application.mgt.common.exception.CommentManagementException; 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.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* This class is responsible for handling the utils of the Application Management DAO. * 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. * To create application object from the result set retrieved from the Database.
* *
* @param rs ResultSet * @param rs ResultSet
* @param rsProperties Properties resultset. * @return List of Applications that is retrieved from the Database.
* @param rsTags Tags resultset * @throws SQLException SQL Exception
* @throws JSONException JSONException.
*/
public static List<Application> loadApplications(ResultSet rs) throws SQLException, JSONException {
List<Application> 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<Tag> tags = new ArrayList<>();
Tag tag = new Tag();
tag.setTagName(rs.getString("APP_TAG"));
tags.add(tag);
application.setTags(tags);
List<UnrestrictedRole> 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. * @return Application that is retrieved from the Database.
* @throws SQLException SQL Exception * @throws SQLException SQL Exception
* @throws JSONException JSONException. * @throws JSONException JSONException.
*/ */
public static Application loadApplication(ResultSet rs, ResultSet rsProperties, ResultSet rsTags) public static Application loadApplication(ResultSet rs) throws SQLException, JSONException {
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")));
Platform platform = new Platform(); Application application = null;
platform.setName(rs.getString("APL_NAME")); int applicatioId = -1;
platform.setIdentifier(rs.getString("APL_IDENTIFIER")); int iteration = 0;
application.setPlatform(platform);
Map<String, String> properties = new HashMap<>(); while (rs.next()){
while (rsProperties.next()) { if (iteration == 0){
properties.put(rsProperties.getString("PROP_KEY"), rsProperties.getString("PROP_VAL")); 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<String> 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; return application;
}
}
/** /**
* Cleans up the statement and resultset after executing the query * Cleans up the statement and resultset after executing the query
* *

View File

@ -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.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONException; import org.json.JSONException;
import org.wso2.carbon.device.application.mgt.common.Application; import org.wso2.carbon.device.application.mgt.common.*;
import org.wso2.carbon.device.application.mgt.common.ApplicationList; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
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.exception.DBConnectionException; 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.ApplicationDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; 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.dao.impl.AbstractDAOImpl;
import org.wso2.carbon.device.application.mgt.core.exception.ApplicationManagementDAOException; 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.*;
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.util.List; import java.util.List;
import java.util.Map;
/** /**
* This handles ApplicationDAO related operations. * 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); 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()) { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to create an application"); log.debug("Request received in DAO Layer to create an application");
log.debug("Application Details : "); log.debug("Application Details : ");
log.debug("UUID : " + application.getUuid() + " Name : " + application.getName() + " User name : " log.debug("App Name : " + application.getName() + " App Type : "
+ application.getUser().getUserName()); + application.getType() + " User Name : " + application.getUser().getUserName());
} }
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql = "";
String generatedColumns[] = {"ID"};
boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported();
int index = 0; int index = 0;
int applicationId = -1;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql += "INSERT INTO APPM_APPLICATION (UUID, NAME, SHORT_DESCRIPTION, DESCRIPTION, " stmt = conn.prepareStatement("INSERT INTO AP_APP (NAME, TYPE, APP_CATEGORY, "
+ "VIDEO_NAME, SCREEN_SHOT_COUNT, CREATED_BY, CREATED_AT, MODIFIED_AT, " + "IS_FREE, PAYMENT_CURRENCY, RESTRICTED, TENANT_ID) VALUES "
+ "APPLICATION_CATEGORY_ID, PLATFORM_ID, TENANT_ID, LIFECYCLE_STATE_ID, " + "(?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
+ "LIFECYCLE_STATE_MODIFIED_AT, LIFECYCLE_STATE_MODIFIED_BY) VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(sql, generatedColumns);
stmt.setString(++index, application.getUuid());
stmt.setString(++index, application.getName()); stmt.setString(++index, application.getName());
stmt.setString(++index, application.getShortDescription()); stmt.setString(++index, application.getType());
stmt.setString(++index, application.getDescription()); stmt.setString(++index, application.getAppCategory());
stmt.setString(++index, application.getVideoName()); stmt.setInt(++index, application.getIsFree());
stmt.setInt(++index, application.getScreenShotCount()); stmt.setString(++index, application.getPaymentCurrency());
stmt.setString(++index, application.getUser().getUserName()); stmt.setInt(++index, application.getIsRestricted());
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.setInt(++index, application.getUser().getTenantId()); 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(); stmt.executeUpdate();
rs = stmt.getGeneratedKeys(); rs = stmt.getGeneratedKeys();
if (rs.next()) { if (rs.next()) {
application.setId(rs.getInt(1)); applicationId = rs.getInt(1);
} }
insertApplicationTagsAndProperties(application, stmt, conn, isBatchExecutionSupported); return applicationId;
return application;
} catch (DBConnectionException 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 when application creation", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while adding the application", e); throw new ApplicationManagementDAOException("Error occurred while adding the application", e);
} finally { } finally {
@ -105,99 +81,97 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
} }
@Override
public void addTags(List<Tag> 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 @Override
public ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException { public ApplicationList getApplications(Filter filter, int tenantId) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application data from the database"); 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; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql = "";
ApplicationList applicationList = new ApplicationList(); ApplicationList applicationList = new ApplicationList();
List<Application> applications = new ArrayList<>();
Pagination pagination = new Pagination(); 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) { if (filter == null) {
throw new ApplicationManagementDAOException("Filter need to be instantiated"); 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()) { if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
sql += "AND LOWER (APP.NAME) "; sql += " AND LOWER (AP_APP.NAME) ";
if (filter.isFullMatch()) { if (filter.isFullMatch()) {
sql += "= ?"; sql += "= ?";
} else { } 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); pagination.setLimit(filter.getLimit());
stmt.setInt(++index, tenantId); pagination.setOffset(filter.getOffset());
if (!userName.equals("ALL")) { try {
stmt.setString(++index, userName); conn = this.getDBConnection();
} stmt = conn.prepareStatement(sql);
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { stmt.setInt(++index, tenantId);
if (filter.isFullMatch()) {
stmt.setString(++index, filter.getSearchQuery().toLowerCase()); if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
} else { if (filter.isFullMatch()) {
stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%"); 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()); Connection conn;
stmt.setInt(++index, filter.getOffset()); 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 @Override
public int getApplicationCount(Filter filter) throws ApplicationManagementDAOException { public int getApplicationCount(Filter filter) throws ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting application count from the database"); 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; Connection conn;
@ -246,13 +275,10 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql += "SELECT COUNT(APP.ID) AS APP_COUNT "; sql += "SELECT count(APP.ID) AS APP_COUNT FROM AP_APP AS APP WHERE TENANT_ID = ?";
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 ";
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
sql += "WHERE LOWER (APP.NAME) LIKE ? "; sql += " AND LOWER (APP.NAME) LIKE ? ";
} }
sql += ";"; sql += ";";
@ -276,67 +302,38 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public Application getApplication(String uuid, int tenantId, String userName) throws public Application getApplication(String appName, String appType, int tenantId) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()){
log.debug("Getting application with the UUID(" + uuid + ") from the database"); log.debug("Getting application with the type(" + appType + " and Name " + appName +
" ) from the database");
} }
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql = "";
Application application = null;
try { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
sql += "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_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 "
+ "CAT.NAME AS CAT_NAME, LS.NAME AS LS_NAME, LS.IDENTIFIER AS LS_IDENTIFIER, " + "AS APP_CATEGORY, AP_APP.IS_FREE, AP_APP_TAG.TAG, AP_UNRESTRICTED_ROLES.ROLE AS RELESE_ID FROM "
+ "LS.DESCRIPTION AS LS_DESCRIPTION " + "AP_APP, AP_APP_TAG, AP_UNRESTRICTED_ROLES WHERE AP_APP.NAME=? AND AP_APP.TYPE= ? "
+ "FROM APPM_APPLICATION APP " + "AND AP_APP.TENANT_ID=?;";
+ "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 = ? ";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, uuid); stmt.setString(1, appName);
stmt.setInt(2, tenantId); stmt.setString(2, appType);
stmt.setInt(3, tenantId);
if (!userName.equals("ALL")) {
sql += "AND APP.CREATED_BY = ?";
stmt.setString(3, userName);
}
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (log.isDebugEnabled()) { 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()) { return Util.loadApplication(rs);
//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();
application = Util.loadApplication(rs, rsProperties, rsTags);
Util.cleanupResources(null, rsProperties);
Util.cleanupResources(null, rsTags);
}
return application;
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Error occurred while getting application details with UUID " + uuid + " While executing query " "Error occurred while getting application details with app name " + appName + " While executing query ", e);
+ sql, e);
} catch (JSONException e) { } catch (JSONException e) {
throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e); throw new ApplicationManagementDAOException("Error occurred while parsing JSON", e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
@ -347,198 +344,136 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public void changeLifecycle(String applicationUUID, String lifecycleIdentifier, String userName, int tenantId) public Application getApplicationById(int applicationId, int tenantId) throws
throws ApplicationManagementDAOException { ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()){
log.debug("Change Life cycle status change " + lifecycleIdentifier + "request received to the DAO " log.debug("Getting application with the id (" + applicationId + ") from the database");
+ "level for the application with " + "the UUID '" + applicationUUID + "' from the user "
+ userName);
} }
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<LifecycleStateTransition> 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<LifecycleStateTransition> 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; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
String sql = "SELECT * FROM APPM_APPLICATION WHERE APPLICATION_CATEGORY_ID = (SELECT ID FROM "
+ "APPM_APPLICATION_CATEGORY WHERE NAME = ?)";
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, categoryName); stmt.setInt(1, applicationId);
stmt.setInt(2, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
return rs.next();
} catch (DBConnectionException e) { if (log.isDebugEnabled()) {
throw new ApplicationManagementDAOException( log.debug("Successfully retrieved basic details of the application with the id "
"Database Connection Exception while trying to check the " + "applications for teh category " + applicationId);
+ categoryName, e); }
return Util.loadApplication(rs);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"SQL Exception while trying to get the application related with categories, while executing " + sql, "Error occurred while getting application details with app id " + applicationId + " While executing query ", e);
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 { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @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; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
String sql = ""; ResultSet rs = null;
boolean isBatchExecutionSupported = ConnectionManagerUtil.isBatchQuerySupported(); 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 { try {
conn = this.getDBConnection(); conn = this.getDBConnection();
int index = 0; int index = 0;
sql += "UPDATE APPM_APPLICATION SET NAME = COALESCE (?, NAME), SHORT_DESCRIPTION = COALESCE " String sql = "UPDATE AP_APP SET ";
+ "(?, SHORT_DESCRIPTION), DESCRIPTION = COALESCE (?, DESCRIPTION), SCREEN_SHOT_COUNT = "
+ "COALESCE (?, SCREEN_SHOT_COUNT), VIDEO_NAME = COALESCE (?, VIDEO_NAME), MODIFIED_AT = COALESCE "
+ "(?, MODIFIED_AT), ";
if (application.getPayment() != null) {
sql += " IS_FREE = COALESCE (?, IS_FREE), "; if (application.getName() != null && !application.getName().equals(existingApplication.getName())) {
if (application.getPayment().getPaymentCurrency() != null) { sql += "NAME = ?, ";
sql += "PAYMENT_CURRENCY = COALESCE (?, PAYMENT_CURRENCY), ";
}
sql += "PAYMENT_PRICE = COALESCE (?, PAYMENT_PRICE), ";
} }
if (application.getCategory() != null && application.getCategory().getId() != 0) { if (application.getType() != null && !application.getType().equals(existingApplication.getType())){
sql += "APPLICATION_CATEGORY_ID = COALESCE (?, APPLICATION_CATEGORY_ID), "; sql += "TYPE = ?, ";
} }
if (application.getPlatform() != null && application.getPlatform().getId() != 0) { if (application.getAppCategory() != null && !application.getAppCategory().equals(existingApplication.getAppCategory())){
sql += "PLATFORM_ID = COALESCE (?, PLATFORM_ID), "; 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 = conn.prepareStatement(sql);
stmt.setString(++index, application.getName()); if (application.getName() != null && !application.getName().equals(existingApplication.getName())) {
stmt.setString(++index, application.getShortDescription()); stmt.setString(++index, application.getName());
stmt.setString(++index, application.getDescription()); }
stmt.setInt(++index, application.getScreenShotCount()); if (application.getType() != null && !application.getType().equals(existingApplication.getType())){
stmt.setString(++index, application.getVideoName()); stmt.setString(++index, application.getType());
stmt.setDate(++index, new Date(application.getModifiedAt().getTime())); }
if (application.getPayment() != null) { if (application.getAppCategory() != null && !application.getAppCategory().equals(existingApplication.getAppCategory())){
stmt.setBoolean(++index, application.getPayment().isFreeApp()); stmt.setString(++index, application.getAppCategory());
if (application.getPayment().getPaymentCurrency() != null) { }
stmt.setString(++index, application.getPayment().getPaymentCurrency()); if (application.getIsRestricted() != existingApplication.getIsRestricted()){
} stmt.setInt(++index, application.getIsRestricted());
stmt.setFloat(++index, application.getPayment().getPaymentPrice()); }
if (application.getIsFree() != existingApplication.getIsFree()){
stmt.setInt(++index, application.getIsFree());
} }
if (application.getCategory() != null && application.getCategory().getId() != 0) { stmt.setInt(++index, application.getId());
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.executeUpdate(); 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; return application;
} catch (DBConnectionException 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.", 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<String, String> 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 @Override
public void deleteApplication(String uuid, int tenantId) throws ApplicationManagementDAOException { public void deleteApplication(int appId) throws ApplicationManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, uuid); stmt.setInt(1, appId);
stmt.setInt(2, tenantId);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (DBConnectionException 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.", e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while deleting the application: " + uuid, e); throw new ApplicationManagementDAOException("Error occurred while deleting the application: " , 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);
} finally { } finally {
Util.cleanupResources(stmt, null); Util.cleanupResources(stmt, null);
} }
@ -644,7 +510,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setInt(1, applicationId); stmt.setInt(1, applicationId);
stmt.executeUpdate(); stmt.executeUpdate();
@ -660,7 +526,7 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
@Override @Override
public int getApplicationId(String uuid, int tenantId) throws ApplicationManagementDAOException { public int getApplicationId(String appName, String appType, int tenantId) throws ApplicationManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
@ -668,10 +534,11 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
int id = -1; int id = -1;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, uuid); stmt.setString(1, appName);
stmt.setInt(2, tenantId); stmt.setString(2, appType);
stmt.setInt(3, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
if (rs.next()) { if (rs.next()) {
id = rs.getInt(1); id = rs.getInt(1);
@ -685,5 +552,4 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
} }
return id; return id;
} }
} }

View File

@ -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.ApplicationRelease;
import org.wso2.carbon.device.application.mgt.common.exception.DBConnectionException; 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.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.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; 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.ApplicationManagementDAOException;
import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import java.sql.Connection; import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* GenericApplicationReleaseDAOImpl holds the implementation of ApplicationRelease related DAO operations. * GenericApplicationReleaseDAOImpl holds the implementation of ApplicationRelease related DAO operations.
*/ */
public class GenericApplicationReleaseDAOImpl extends AbstractDAOImpl implements ApplicationReleaseDAO { 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 @Override
public ApplicationRelease createRelease(ApplicationRelease applicationRelease) throws public ApplicationRelease createRelease(ApplicationRelease applicationRelease, int appId) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = 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; int index = 0;
String generatedColumns[] = {"ID"}; String generatedColumns[] = {"ID"};
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql, generatedColumns); statement = connection.prepareStatement(sql, generatedColumns);
statement.setString(++index, applicationRelease.getVersionName()); statement.setString(++index, applicationRelease.getVersion());
statement.setString(++index, applicationRelease.getResource()); statement.setString(++index, applicationRelease.getTenantId());
statement.setString(++index, String.valueOf(applicationRelease.getReleaseChannel())); statement.setString(++index, applicationRelease.getUuid());
statement.setString(++index, applicationRelease.getReleaseDetails()); statement.setString(++index, String.valueOf(applicationRelease.getReleaseType()));
statement.setDate(++index, new Date(applicationRelease.getCreatedAt().getTime())); statement.setDouble(++index, applicationRelease.getPrice());
statement.setInt(++index, applicationRelease.getApplication().getId()); statement.setString(++index, applicationRelease.getAppStoredLoc());
statement.setBoolean(++index, applicationRelease.isDefault()); 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(); statement.executeUpdate();
resultSet = statement.getGeneratedKeys(); resultSet = statement.getGeneratedKeys();
if (resultSet.next()) { if (resultSet.next()) {
applicationRelease.setId(resultSet.getInt(1)); applicationRelease.setId(resultSet.getInt(1));
} }
insertApplicationReleaseProperties(connection, applicationRelease);
return applicationRelease; return applicationRelease;
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"SQL Exception while trying to release an application (UUID : " + applicationRelease "SQL Exception while trying to release an application by executing the query " + sql, e);
.getApplication().getUuid() + "), by executing the query " + sql, e);
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException( throw new ApplicationManagementDAOException(
"Database Connection Exception while trying to release the " + "applcation with UUID " "Database Connection Exception while trying to release a new version" , e);
+ applicationRelease.getApplication().getUuid(), e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); 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 @Override
public ApplicationRelease getRelease(String applicationUuid, String versionName, int tenantId) public ApplicationRelease getRelease(String applicationName, String applicationType, String versionName,
throws ApplicationManagementDAOException { String releaseType, int tenantId) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = 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; 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 { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, versionName); statement.setString(1, applicationName);
statement.setString(2, applicationUuid); statement.setString(2, applicationType);
statement.setInt(3, tenantId); statement.setInt(3, tenantId);
statement.setString(4, versionName);
statement.setString(5, releaseType);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
if (resultSet.next()) { if (resultSet.next()) {
applicationRelease = new ApplicationRelease(); applicationRelease = new ApplicationRelease();
applicationRelease.setVersionName(versionName); applicationRelease.setId(resultSet.getInt("RELEASE_ID"));
applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT")); applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT")); applicationRelease.setUuid(resultSet.getString("UUID"));
applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL")); applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS")); applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE")); applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION"));
applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION"));
sql = "SELECT * FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID=?"; applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1"));
statement = connection.prepareStatement(sql); applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2"));
statement.setInt(1, resultSet.getInt("ID")); applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3"));
rsProperties = statement.executeQuery(); applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
Map<String, String> properties = new HashMap<>(); applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
while (rsProperties.next()) { applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
properties.put(rsProperties.getString("PROP_KEY"), applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
rsProperties.getString("PROP_VAL")); applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
} applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
applicationRelease.setProperties(properties); 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; return applicationRelease;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the " 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); versionName, e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error while getting release details of the application " + 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 { } finally {
Util.cleanupResources(statement, resultSet); 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 @Override
public List<ApplicationRelease> getApplicationReleases(String applicationUUID, int tenantId) public List<ApplicationRelease> getApplicationReleases(String applicationName, String applicationType, int tenantId)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
ResultSet resultSet = 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<ApplicationRelease> applicationReleases = new ArrayList<>(); List<ApplicationRelease> 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 { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, applicationUUID); statement.setString(1, applicationName);
statement.setInt(2, tenantId); statement.setString(2, applicationType);
statement.setInt(3, tenantId);
statement.setInt(4, tenantId);
resultSet = statement.executeQuery(); resultSet = statement.executeQuery();
while (resultSet.next()) { while (resultSet.next()) {
ApplicationRelease applicationRelease = new ApplicationRelease(); ApplicationRelease applicationRelease = new ApplicationRelease();
applicationRelease.setVersionName(resultSet.getString("VERSION_NAME")); applicationRelease.setId(resultSet.getInt("RELESE_ID"));
applicationRelease.setDefault(resultSet.getBoolean("IS_DEFAULT")); applicationRelease.setVersion(resultSet.getString("RELEASE_VERSION"));
applicationRelease.setCreatedAt(resultSet.getDate("CREATED_AT")); applicationRelease.setUuid(resultSet.getString("UUID"));
applicationRelease.setReleaseChannel(resultSet.getString("RELEASE_CHANNEL")); applicationRelease.setReleaseType(resultSet.getString("RELEASE_TYPE"));
applicationRelease.setReleaseDetails(resultSet.getString("RELEASE_DETAILS")); applicationRelease.setPrice(resultSet.getDouble("APP_PRICE"));
applicationRelease.setResource(resultSet.getString("RELEASE_RESOURCE")); applicationRelease.setAppStoredLoc(resultSet.getString("STORED_LOCATION"));
applicationRelease.setBannerLoc(resultSet.getString("BANNER_LOCATION"));
sql = "SELECT * FROM APPM_RELEASE_PROPERTY WHERE APPLICATION_RELEASE_ID= ?"; applicationRelease.setScreenshotLoc1(resultSet.getString("SCREEN_SHOT_1"));
statement = connection.prepareStatement(sql); applicationRelease.setScreenshotLoc2(resultSet.getString("SCREEN_SHOT_2"));
statement.setInt(1, resultSet.getInt("ID")); applicationRelease.setScreenshotLoc3(resultSet.getString("SCREEN_SHOT_3"));
rsProperties = statement.executeQuery(); applicationRelease.setAppHashValue(resultSet.getString("HASH_VALUE"));
applicationRelease.setIsSharedWithAllTenants(resultSet.getInt("SHARED"));
Map<String, String> properties = new HashMap<>(); applicationRelease.setMetaData(resultSet.getString("APP_META_INFO"));
while (rsProperties.next()) { applicationRelease.setApplicationCreator(resultSet.getString("CREATED_BY"));
properties.put(rsProperties.getString("PROP_KEY"), rsProperties.getString("PROP_VAL")); applicationRelease.setCreatedAt(resultSet.getTimestamp("CREATED_AT"));
} applicationRelease.setPublishedBy(resultSet.getString("PUBLISHED_BY"));
applicationRelease.setProperties(properties); applicationRelease.setPublishedAt(resultSet.getTimestamp("PUBLISHED_AT"));
applicationRelease.setStars(resultSet.getInt("STARS"));
applicationReleases.add(applicationRelease); applicationReleases.add(applicationRelease);
} }
return applicationReleases; return applicationReleases;
} catch (DBConnectionException e) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to get the " 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) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( 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); + ", while executing the query " + sql, e);
} finally { } finally {
Util.cleanupResources(statement, resultSet); 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 @Override
public ApplicationRelease updateRelease(ApplicationRelease applicationRelease) public void updateStars(int id, int stars) throws ApplicationManagementDAOException {
throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; PreparedStatement statement = null;
String sql = "UPDATE APPM_APPLICATION_RELEASE SET RELEASE_RESOURCE = IFNULL (?, RELEASE_RESOURCE)," + String sql = "UPDATE AP_APP_RELEASE SET STARS = ? WHERE ID = ?;";
" RELEASE_CHANNEL = IFNULL (?, RELEASE_CHANNEL), RELEASE_DETAILS = IFNULL (?, RELEASE_DETAILS), " +
"IS_DEFAULT = IFNULL (?, IS_DEFAULT) WHERE APPM_APPLICATION_ID = ? AND VERSION_NAME = ?";
try { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); statement = connection.prepareStatement(sql);
statement.setString(1, applicationRelease.getResource()); statement.setInt(1, stars);
statement.setString(2, String.valueOf(applicationRelease.getReleaseChannel())); statement.setInt(2, id);
statement.setString(3, applicationRelease.getReleaseDetails());
statement.setBoolean(4, applicationRelease.isDefault());
statement.setInt(5, applicationRelease.getApplication().getId());
statement.setString(6, applicationRelease.getVersionName());
statement.executeUpdate(); 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) { } catch (DBConnectionException e) {
throw new ApplicationManagementDAOException("Database connection exception while trying to update the " throw new ApplicationManagementDAOException(
+ "Application release for the application with UUID " + applicationRelease.getApplication() "Database connection exception while trying to update the application release", e);
.getUuid() + " for the version " + applicationRelease.getVersionName(), e);
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException( 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 { } finally {
Util.cleanupResources(statement, null); 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 @Override
public void deleteRelease(int id, String version) throws ApplicationManagementDAOException { public void deleteRelease(int id, String version) throws ApplicationManagementDAOException {
Connection connection; Connection connection;
PreparedStatement statement = null; 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 { try {
connection = this.getDBConnection(); connection = this.getDBConnection();
statement = connection.prepareStatement(sql); 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<String, String> 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);
}
}
} }

View File

@ -31,46 +31,46 @@ import java.sql.SQLException;
*/ */
public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl { public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl {
@Override // @Override
protected PreparedStatement generateGetApplicationsStatement(Filter filter, Connection conn, // protected PreparedStatement generateGetApplicationsStatement(Filter filter, Connection conn,
int tenantId) throws SQLException { // int tenantId) throws SQLException {
int index = 0; // int index = 0;
String sql = "SELECT APP.*, APL.NAME AS APL_NAME, APL.IDENTIFIER AS APL_IDENTIFIER, CAT.ID AS CAT_ID, " // 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, " // + "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 " // + "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.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.APPLICATION_CATEGORY_ID = CAT.ID " + "INNER JOIN APPM_LIFECYCLE_STATE LS "
+ "ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE APP.TENANT_ID = ? "; // + "ON APP.LIFECYCLE_STATE_ID = LS.ID WHERE APP.TENANT_ID = ? ";
//
String userName = filter.getUserName(); // String userName = filter.getUserName();
if (!userName.equals("ALL")) { // if (!userName.equals("ALL")) {
sql += " AND APP.CREATED_BY = ? "; // sql += " AND APP.CREATED_BY = ? ";
} // }
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { // if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
sql += "AND LOWER (APP.NAME) "; // sql += "AND LOWER (APP.NAME) ";
if (filter.isFullMatch()) { // if (filter.isFullMatch()) {
sql += "= ?"; // sql += "= ?";
} else { // } else {
sql += "LIKE ?"; // sql += "LIKE ?";
} // }
} // }
sql += " ORDER BY APP.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; // sql += " ORDER BY APP.ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
PreparedStatement stmt = conn.prepareStatement(sql); // PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(++index, tenantId); // stmt.setInt(++index, tenantId);
//
if (!userName.equals("ALL")) { // if (!userName.equals("ALL")) {
stmt.setString(++index, userName); // stmt.setString(++index, userName);
} // }
if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) { // if (filter.getSearchQuery() != null && !filter.getSearchQuery().isEmpty()) {
if (filter.isFullMatch()) { // if (filter.isFullMatch()) {
stmt.setString(++index, filter.getSearchQuery().toLowerCase()); // stmt.setString(++index, filter.getSearchQuery().toLowerCase());
} else { // } else {
stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%"); // stmt.setString(++index, "%" + filter.getSearchQuery().toLowerCase() + "%");
} // }
} // }
stmt.setInt(++index, filter.getOffset()); // stmt.setInt(++index, filter.getOffset());
stmt.setInt(++index, filter.getLimit()); // stmt.setInt(++index, filter.getLimit());
return stmt; // return stmt;
} // }
} }

View File

@ -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<Category> getCategories() throws ApplicationManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "SELECT * FROM APPM_APPLICATION_CATEGORY";
List<Category> 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);
}
}
}

View File

@ -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.common.Util;
import org.wso2.carbon.device.application.mgt.core.dao.impl.AbstractDAOImpl; 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.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.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -39,61 +39,70 @@ import java.util.List;
public class GenericLifecycleStateImpl extends AbstractDAOImpl implements LifecycleStateDAO { public class GenericLifecycleStateImpl extends AbstractDAOImpl implements LifecycleStateDAO {
@Override @Override
public LifecycleState getLifeCycleStateByIdentifier(String identifier) throws ApplicationManagementDAOException { public LifecycleState getLatestLifeCycleStateByReleaseID(int identifier) throws ApplicationManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, identifier); stmt.setInt(1, identifier);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
LifecycleState lifecycleState = null; LifecycleState lifecycleState = null;
if (rs.next()) { if (rs.next()) {
lifecycleState = new LifecycleState(); lifecycleState = new LifecycleState();
lifecycleState.setId(rs.getInt("ID")); lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setName(rs.getString("NAME")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setIdentifier(rs.getString("IDENTIFIER")); lifecycleState.setPreviousState(rs.getString("PREVIOUSE_STATE"));
lifecycleState.setDescription(rs.getString("DESCRIPTION")); lifecycleState.setUpdatedAt(rs.getTimestamp("UPDATED_AT"));
lifecycleState.setUpdatedBy(rs.getString("UPDATED_BY"));
} }
return lifecycleState; return lifecycleState;
} catch (SQLException e) { } catch (SQLException e) {
throw new ApplicationManagementDAOException("Error occurred while getting application List", e); throw new ApplicationManagementDAOException("Error occurred while getting application List", e);
} catch (DBConnectionException 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 { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public List<LifecycleState> getLifecycleStates() throws DAOException { public List<LifecycleState> getLifecycleStates(int appReleaseId) throws LifeCycleManagementDAOException {
List<LifecycleState> lifecycleStates = new ArrayList<>(); List<LifecycleState> lifecycleStates = new ArrayList<>();
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int index = 0;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setInt(++index,appReleaseId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
while (rs.next()) { while (rs.next()) {
LifecycleState lifecycleState = new LifecycleState(); LifecycleState lifecycleState = new LifecycleState();
lifecycleState.setIdentifier(rs.getString("IDENTIFIER")); lifecycleState.setId(rs.getInt("ID"));
lifecycleState.setName(rs.getString("NAME")); lifecycleState.setCurrentState(rs.getString("CURRENT_STATE"));
lifecycleState.setDescription(rs.getString("DESCRIPTION")); 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); lifecycleStates.add(lifecycleState);
} }
} catch (DBConnectionException e) { } 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) { } catch (SQLException e) {
throw new DAOException("Error occurred while retrieving lifecycle states.", e); throw new LifeCycleManagementDAOException("Error occurred while retrieving lifecycle states.", e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }
@ -101,44 +110,47 @@ public class GenericLifecycleStateImpl extends AbstractDAOImpl implements Lifecy
} }
@Override @Override
public void addLifecycleState(LifecycleState state) throws DAOException { public void addLifecycleState(LifecycleState state) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, state.getName()); stmt.setString(1, state.getCurrentState());
stmt.setString(2, state.getIdentifier()); stmt.setString(2, state.getPreviousState());
stmt.setString(3, state.getDescription()); stmt.setInt(3, state.getTenantId());
stmt.setString(4, state.getUpdatedBy());
stmt.setInt(5, state.getReleaseId());
stmt.setInt(6, state.getAppId());
stmt.executeUpdate(); stmt.executeUpdate();
} catch (DBConnectionException e) { } 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) { } 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 { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, null);
} }
} }
@Override @Override
public void deleteLifecycleState(String identifier) throws DAOException { public void deleteLifecycleState(int identifier) throws LifeCycleManagementDAOException {
Connection conn = null; Connection conn = null;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
conn = this.getDBConnection(); 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 = conn.prepareStatement(sql);
stmt.setString(1, identifier); stmt.setInt(1, identifier);
stmt.executeUpdate(); stmt.executeUpdate();
} catch (DBConnectionException e) { } 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) { } catch (SQLException e) {
throw new DAOException("Error occurred while deleting lifecycle: " + identifier, e); throw new LifeCycleManagementDAOException("Error occurred while deleting lifecycle: " + identifier, e);
} finally { } finally {
Util.cleanupResources(stmt, rs); Util.cleanupResources(stmt, rs);
} }

View File

@ -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<String> 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<Platform> 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<Platform> 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<Platform.Property> 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<String> 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<String> getPlatformTags(String name) throws PlatformManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
String sql = "";
List<String> 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);
}
}
}

View File

@ -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<String> 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<Platform> 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);
}
}

View File

@ -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 = ?";
}

View File

@ -17,7 +17,9 @@
*/ */
package org.wso2.carbon.device.application.mgt.core.dao.impl.visibility; 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.common.exception.DBConnectionException;
import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO; import org.wso2.carbon.device.application.mgt.core.dao.VisibilityDAO;
import org.wso2.carbon.device.application.mgt.core.dao.common.Util; 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 { public class GenericVisibilityDAOImpl extends AbstractDAOImpl implements VisibilityDAO {
private static final Log log = LogFactory.getLog(GenericVisibilityDAOImpl.class);
@Override @Override
public int getVisibilityID(Visibility.Type visibilityType) throws VisibilityManagementDAOException { public void addUnrestrictedRoles(List<UnrestrictedRole> 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; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet rs = null;
try { int index = 0;
Connection connection = getDBConnection(); String sql = "INSERT INTO AP_UNRESTRICTED_ROLES (ROLE, TENANT_ID, AP_APP_ID) VALUES (?, ?, ?)";
String sql = "SELECT ID FROM APPM_RESOURCE_TYPE WHERE NAME = ?"; try{
stmt = connection.prepareStatement(sql); conn = this.getDBConnection();
stmt.setString(1, visibilityType.toString().toUpperCase()); conn.setAutoCommit(false);
resultSet = stmt.executeQuery(); stmt = conn.prepareStatement(sql);
if (resultSet.next()) { for (UnrestrictedRole role : unrestrictedRoles) {
return resultSet.getInt("ID"); stmt.setString(++index, role.getRole());
stmt.setInt(++index, tenantId);
stmt.setInt(++index, applicationId);
stmt.addBatch();
} }
return -1; stmt.executeBatch();
} catch (DBConnectionException e) {
throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " + }catch (DBConnectionException e) {
"for the visibility management of applications", e); throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
} catch (SQLException e) { }catch (SQLException e) {
throw new VisibilityManagementDAOException("Error occurred when trying to get the ID of the" + throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
" visibility type - " + visibilityType.toString(), e);
} finally { } finally {
Util.cleanupResources(stmt, resultSet); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public void add(int applicationID, int visibilityTypeID, List<String> allowedList) public List<UnrestrictedRole> getUnrestrictedRoles(int applicationId, int tenantId) throws VisibilityManagementDAOException {
throws VisibilityManagementDAOException { if (log.isDebugEnabled()) {
log.debug("Request received in DAO Layer to get unrestricted roles");
}
Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
try { ResultSet rs = null;
Connection connection = getDBConnection(); List<UnrestrictedRole> unrestrictedRoles = new ArrayList<>();
String sql = "INSERT INTO APPM_VISIBILITY (VALUE, RESOURCE_TYPE_ID, APPLICATION_ID) VALUES (?, ?, ?)"; UnrestrictedRole unrestrictedRole = null;
stmt = connection.prepareStatement(sql); int index = 0;
if (allowedList == null) { String sql = "SELECT ID, ROLE FROM AP_UNRESTRICTED_ROLES WHERE AP_APP_ID = ? AND TENANT_ID = ?;";
stmt.setString(1, null); try{
stmt.setInt(2, visibilityTypeID); conn = this.getDBConnection();
stmt.setInt(3, applicationID); conn.setAutoCommit(false);
stmt.execute(); stmt = conn.prepareStatement(sql);
} else { stmt.setInt(++index, applicationId);
for (String allowed : allowedList) { stmt.setInt(++index, tenantId);
stmt.setString(1, allowed); rs = stmt.executeQuery();
stmt.setInt(2, visibilityTypeID);
stmt.setInt(3, applicationID); while (rs.next()){
stmt.addBatch(); unrestrictedRole = new UnrestrictedRole();
} unrestrictedRole.setId(rs.getInt("ID"));
stmt.executeBatch(); unrestrictedRole.setRole(rs.getString("ROLE"));
unrestrictedRoles.add(unrestrictedRole);
} }
} catch (DBConnectionException e) { return unrestrictedRoles;
throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " +
"for adding the visibility mapping for the application ID - " + applicationID, e); }catch (DBConnectionException e) {
} catch (SQLException e) { throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
throw new VisibilityManagementDAOException("Error occurred while adding the visibility mapping " + }catch (SQLException e) {
"for the application ID - " + applicationID, e); throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
} finally { } finally {
Util.cleanupResources(stmt, null); Util.cleanupResources(stmt, rs);
} }
} }
@Override @Override
public void delete(int applicationId) throws VisibilityManagementDAOException { public void deleteUnrestrictedRoles(List<UnrestrictedRole> unrestrictedRoles, int applicationId, int tenantId) throws VisibilityManagementDAOException {
PreparedStatement stmt = null; if (log.isDebugEnabled()) {
try { log.debug("Request received in DAO Layer to delete unrestricted roles");
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);
} }
} Connection conn;
public Visibility get(int applicationId) throws VisibilityManagementDAOException {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet resultSet = null; ResultSet rs = null;
final String visibilityTypeColumn = "VISIBILITY_TYPE"; int index = 0;
final String allowedValColumn = "ALLOWED_VAL"; String sql = "DELETE FROM AP_UNRESTRICTED_ROLES WHERE AP_APP_ID = 1 AND ROLE = 'role1' AND TENANT_ID = -1234;";
try { try{
Connection connection = getDBConnection(); conn = this.getDBConnection();
String sql = "SELECT APPM_VISIBILITY.VALUE as " + allowedValColumn + ", APPM_RESOURCE_TYPE.NAME AS " + conn.setAutoCommit(false);
visibilityTypeColumn + " FROM APPM_VISIBILITY JOIN APPM_RESOURCE_TYPE " + stmt = conn.prepareStatement(sql);
"ON APPM_VISIBILITY.RESOURCE_TYPE_ID = APPM_RESOURCE_TYPE.ID " +
"WHERE APPM_VISIBILITY.APPLICATION_ID = ?"; for (UnrestrictedRole role : unrestrictedRoles) {
stmt = connection.prepareStatement(sql); stmt.setInt(++index, applicationId);
stmt.setInt(1, applicationId); stmt.setString(++index, role.getRole());
resultSet = stmt.executeQuery(); stmt.setInt(++index, role.getTenantId());
Visibility visibility = new Visibility(); stmt.addBatch();
List<String> 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);
}
} }
if (!allowedVal.isEmpty()) { stmt.executeBatch();
visibility.setAllowedList(allowedVal);
} }catch (DBConnectionException e) {
return visibility; throw new VisibilityManagementDAOException("Error occurred while obtaining the DB connection when adding roles", e);
} catch (DBConnectionException e) { }catch (SQLException e) {
throw new VisibilityManagementDAOException("Error occurred while obtaining the connection " + throw new VisibilityManagementDAOException("Error occurred while adding unrestricted roles", e);
"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);
} finally { } finally {
Util.cleanupResources(stmt, resultSet); Util.cleanupResources(stmt, rs);
} }
} }
} }

View File

@ -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<Property> 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<Property> getProperties() {
return properties;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setProperties(List<Property> 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;
}
}

View File

@ -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 <IOT_HOME>/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<org.wso2.carbon.device.application.mgt.common.Platform.Property> 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) {
}
}

Some files were not shown because too many files have changed in this diff Show More