diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml
new file mode 100644
index 00000000000..6715d66cbef
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml
@@ -0,0 +1,94 @@
+
+
+
+
+
+
+ apimgt-extensions
+ org.wso2.carbon.devicemgt
+ 1.1.0-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ org.wso2.carbon.apimgt.annotations
+ 1.1.0-SNAPSHOT
+ bundle
+ WSO2 Carbon - API Management Annotations
+ WSO2 Carbon - API Management Custom Annotation Module
+ http://wso2.org
+
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi.services
+
+
+ org.wso2.carbon
+ org.wso2.carbon.logging
+
+
+ javax.ws.rs
+ jsr311-api
+
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 1.4.0
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ API Management Extentions - Custom Annotations
+
+ org.wso2.carbon.apimgt.annotations.*
+
+
+ org.osgi.framework,
+ org.osgi.service.component,
+ org.apache.commons.logging,
+ javax.servlet,
+ javax.xml.*,
+ org.apache.commons.lang,
+
+
+ scribe;scope=compile|runtime;inline=false;
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java
new file mode 100644
index 00000000000..04ecd9ed708
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/API.java
@@ -0,0 +1,36 @@
+/*
+ * 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.apimgt.annotations.api;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface API {
+
+ String name();
+
+ String version();
+
+ String context();
+
+ String[] tags();
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
new file mode 100644
index 00000000000..bfe5a9177ba
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
@@ -0,0 +1,171 @@
+
+
+
+
+
+ apimgt-extensions
+ org.wso2.carbon.devicemgt
+ 1.1.0-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ 1.1.0-SNAPSHOT
+ org.wso2.carbon.apimgt.application.extension.api
+ war
+ WSO2 Carbon - API Application Management API
+ This module provides capability to create api manager application.
+ http://wso2.org
+
+
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxws
+ provided
+
+
+ org.apache.cxf
+ cxf-rt-frontend-jaxrs
+ provided
+
+
+ org.apache.cxf
+ cxf-rt-transports-http
+ provided
+
+
+
+
+ org.codehaus.jackson
+ jackson-core-asl
+
+
+ org.codehaus.jackson
+ jackson-jaxrs
+
+
+ javax
+ javaee-web-api
+ provided
+
+
+ javax.ws.rs
+ jsr311-api
+ provided
+
+
+ commons-httpclient.wso2
+ commons-httpclient
+ provided
+
+
+
+ org.wso2.carbon
+ org.wso2.carbon.utils
+ provided
+
+
+ org.bouncycastle.wso2
+ bcprov-jdk15on
+
+
+ org.wso2.carbon
+ org.wso2.carbon.user.api
+
+
+ org.wso2.carbon
+ org.wso2.carbon.queuing
+
+
+ org.wso2.carbon
+ org.wso2.carbon.base
+
+
+ org.apache.axis2.wso2
+ axis2
+
+
+ org.igniterealtime.smack.wso2
+ smack
+
+
+ org.igniterealtime.smack.wso2
+ smackx
+
+
+ jaxen
+ jaxen
+
+
+ commons-fileupload.wso2
+ commons-fileupload
+
+
+ org.apache.ant.wso2
+ ant
+
+
+ org.apache.ant.wso2
+ ant
+
+
+ commons-httpclient.wso2
+ commons-httpclient
+
+
+ org.eclipse.equinox
+ javax.servlet
+
+
+ org.wso2.carbon
+ org.wso2.carbon.registry.api
+
+
+
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.apimgt.application.extension
+ provided
+
+
+
+
+
+
+ maven-compiler-plugin
+
+ UTF-8
+
+ ${wso2.maven.compiler.target}
+
+
+
+ maven-war-plugin
+ 2.2
+
+ ${project.artifactId}
+
+
+
+
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java
new file mode 100644
index 00000000000..f6404de2d65
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java
@@ -0,0 +1,58 @@
+/*
+ * 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.apimgt.application.extension.api;
+
+import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.POST;
+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;
+
+/**
+ * This is the application registration service that exposed for apimApplicationRegistration
+ */
+public interface ApiApplicationRegistrationService {
+
+ /**
+ * This method is used to register an APIM application for tenant domain.
+ */
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @Consumes(MediaType.APPLICATION_JSON)
+ Response register(@PathParam("tenantDomain") String tenantDomain,
+ @QueryParam("applicationName") String applicationName);
+
+ /**
+ * This method is used to register api application
+ *
+ * @param registrationProfile contains the necessary attributes that are needed in order to register an app.
+ */
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @Consumes(MediaType.APPLICATION_JSON)
+ Response register(RegistrationProfile registrationProfile);
+
+ @DELETE
+ Response unregister(@QueryParam("applicationName") String applicationName);
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java
new file mode 100644
index 00000000000..00f537c0863
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java
@@ -0,0 +1,129 @@
+/*
+ * 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.apimgt.application.extension.api;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.json.simple.JSONObject;
+import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
+import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile;
+import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
+import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
+import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil;
+import org.wso2.carbon.user.api.UserStoreException;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Response;
+
+
+public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegistrationService {
+ private static final Log log = LogFactory.getLog(ApiApplicationRegistrationServiceImpl.class);
+
+ @Path("register/tenants/{tenantDomain}")
+ @POST
+ public Response register(@PathParam("tenantDomain") String tenantDomain,
+ @QueryParam("applicationName") String applicationName) {
+ Response response;
+ try {
+ PrivilegedCarbonContext.startTenantFlow();
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
+ if (PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId() == -1) {
+ String msg = "Invalid tenant domain : " + tenantDomain;
+ response = Response.status(Response.Status.NOT_ACCEPTABLE).entity(msg).build();
+ }
+ String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
+ .getRealmConfiguration().getAdminUserName();
+ PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(username);
+ APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
+ ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
+ applicationName, ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false);
+ return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
+ } catch (APIManagerException e) {
+ String msg = "Error occurred while registering an application '" + applicationName + "'";
+ log.error(msg, e);
+ response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ } catch (UserStoreException e) {
+ String msg = "Failed to retrieve the tenant" + tenantDomain + "'";
+ log.error(msg, e);
+ response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ } finally {
+ PrivilegedCarbonContext.endTenantFlow();
+ }
+ return response;
+ }
+
+ @Path("register")
+ @POST
+ public Response register(RegistrationProfile registrationProfile) {
+ Response response;
+ try {
+ String username = APIUtil.getAuthenticatedUser();
+ APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
+ if (registrationProfile.isMappingAnExistingOAuthApp()) {
+ JSONObject jsonStringObject = new JSONObject();
+ jsonStringObject.put(ApiApplicationConstants.JSONSTRING_USERNAME_TAG, username);
+ jsonStringObject.put(ApiApplicationConstants.JSONSTRING_KEY_TYPE_TAG,
+ ApiApplicationConstants.DEFAULT_TOKEN_TYPE);
+ jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_ID, registrationProfile.getConsumerKey());
+ jsonStringObject.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET,
+ registrationProfile.getConsumerSecret());
+ jsonStringObject.put(ApiApplicationConstants.JSONSTRING_VALIDITY_PERIOD_TAG,
+ ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD);
+ apiManagementProviderService.registerExistingOAuthApplicationToAPIApplication(
+ jsonStringObject.toJSONString(), registrationProfile.getApplicationName(),
+ registrationProfile.getConsumerKey(), username, registrationProfile.isAllowedToAllDomains());
+ return Response.status(Response.Status.ACCEPTED).entity("OAuth App is mapped as APIM App").build();
+ } else {
+ ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
+ registrationProfile.getApplicationName(), registrationProfile.getTags(),
+ ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, false);
+ return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
+ }
+ } catch (APIManagerException e) {
+ String msg = "Error occurred while registering an application '"
+ + registrationProfile.getApplicationName() + "'";
+ log.error(msg, e);
+ response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ return response;
+ }
+
+ @Path("unregister")
+ @DELETE
+ public Response unregister(@QueryParam("applicationName") String applicationName) {
+ Response response;
+ try {
+ String username = APIUtil.getAuthenticatedUser();
+ APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
+ apiManagementProviderService.removeAPIApplication(applicationName, username);
+ return Response.status(Response.Status.ACCEPTED).build();
+ } catch (APIManagerException e) {
+ String msg = "Error occurred while removing the application '" + applicationName;
+ log.error(msg, e);
+ response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ return response;
+ }
+}
\ No newline at end of file
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java
new file mode 100644
index 00000000000..b15bcd1944f
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/APIUtil.java
@@ -0,0 +1,60 @@
+/*
+ * 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.apimgt.application.extension.api.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+
+/**
+ * This class provides utility functions used by REST-API.
+ */
+public class APIUtil {
+
+ private static Log log = LogFactory.getLog(APIUtil.class);
+
+ public static String getAuthenticatedUser() {
+ PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ String username = threadLocalCarbonContext.getUsername();
+ String tenantDomain = threadLocalCarbonContext.getTenantDomain();
+ if (username.endsWith(tenantDomain)) {
+ return username.substring(0, username.lastIndexOf("@"));
+ }
+ return username;
+ }
+
+ public static String getTenantDomainOftheUser() {
+ PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ String tenantDomain = threadLocalCarbonContext.getTenantDomain();
+ return tenantDomain;
+ }
+
+ public static APIManagementProviderService getAPIManagementProviderService() {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ APIManagementProviderService apiManagementProviderService =
+ (APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
+ if (apiManagementProviderService == null) {
+ String msg = "API management provider service has not initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ return apiManagementProviderService;
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java
new file mode 100644
index 00000000000..c0d231039c3
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/util/RegistrationProfile.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.apimgt.application.extension.api.util;
+
+import org.codehaus.jackson.annotate.JsonIgnoreProperties;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * DTO class to be used when registering an ApiM application.
+ */
+@XmlRootElement
+
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class RegistrationProfile {
+
+ @XmlElement(required = true)
+ private String applicationName;
+ @XmlElement(required = true)
+ private String tags[];
+ @XmlElement(required = true)
+ private boolean isAllowedToAllDomains;
+ @XmlElement(required = true)
+ private boolean isMappingAnExistingOAuthApp;
+ private String consumerKey;
+ private String consumerSecret;
+
+ public String getApplicationName() {
+ return applicationName;
+ }
+
+ public void setApiApplicationName(String apiApplicationName) {
+ this.applicationName = apiApplicationName;
+ }
+
+ public String[] getTags() {
+ return tags;
+ }
+
+ public void setTags(String[] tags) {
+ this.tags = tags;
+ }
+
+ public boolean isAllowedToAllDomains() {
+ return isAllowedToAllDomains;
+ }
+
+ public void setIsAllowedToAllDomains(boolean isAllowedToAllDomains) {
+ this.isAllowedToAllDomains = isAllowedToAllDomains;
+ }
+
+ public boolean isMappingAnExistingOAuthApp() {
+ return isMappingAnExistingOAuthApp;
+ }
+
+ public void setIsMappingAnExistingOAuthApp(boolean isMappingAnExistingOAuthApp) {
+ this.isMappingAnExistingOAuthApp = isMappingAnExistingOAuthApp;
+ }
+
+ public String getConsumerKey() {
+ return consumerKey;
+ }
+
+ public void setConsumerKey(String consumerKey) {
+ this.consumerKey = consumerKey;
+ }
+
+ public String getConsumerSecret() {
+ return consumerSecret;
+ }
+
+ public void setConsumerSecret(String consumerSecret) {
+ this.consumerSecret = consumerSecret;
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml
new file mode 100644
index 00000000000..104c34fe3ee
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/permissions.xml
@@ -0,0 +1,52 @@
+
+
+
+
+
+
+
+
+
+ Register tenant specific application
+ /permission/super admin
+ /register/tenants/*
+ POST
+ super_admin_user
+
+
+ Register application
+ /device-mgt/api/application/add
+ /register
+ POST
+ application_user
+
+
+ Delete application
+ /device-mgt/api/application/remove
+ /unregister
+ DELETE
+ application_user
+
+
\ No newline at end of file
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml
new file mode 100644
index 00000000000..b410b426700
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/META-INF/webapp-classloading.xml
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+ false
+
+
+ CXF,Carbon
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml
new file mode 100644
index 00000000000..c9c72c4ad61
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 00000000000..7aaaf3002db
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,52 @@
+
+
+
+
+ WSO2 IoT Server
+ WSO2 IoT Server
+
+
+ CXFServlet
+ org.apache.cxf.transport.servlet.CXFServlet
+ 1
+
+
+
+ CXFServlet
+ /*
+
+
+ isAdminService
+ false
+
+
+ doAuthentication
+ true
+
+
+
+
+ managed-api-enabled
+ false
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml
new file mode 100644
index 00000000000..3e2d879c8b2
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml
@@ -0,0 +1,118 @@
+
+
+
+
+
+
+ apimgt-extensions
+ org.wso2.carbon.devicemgt
+ 1.1.0-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ 1.1.0-SNAPSHOT
+ org.wso2.carbon.apimgt.application.extension
+ bundle
+ WSO2 Carbon - API Application Management
+ This module provides capability to create api manager application.
+ http://wso2.org
+
+
+
+ org.wso2.carbon
+ org.wso2.carbon.registry.core
+
+
+ org.wso2.carbon
+ org.wso2.carbon.core
+
+
+ org.wso2.carbon
+ org.wso2.carbon.utils
+
+
+ org.wso2.carbon
+ org.wso2.carbon.logging
+
+
+ org.wso2.carbon.apimgt
+ org.wso2.carbon.apimgt.impl
+
+
+ org.wso2.carbon.apimgt
+ org.wso2.carbon.apimgt.api
+
+
+ com.googlecode.json-simple.wso2
+ json-simple
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/Abstract*
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ API Management Application Bundle
+ org.wso2.carbon.apimgt.application.extension.internal
+
+ org.osgi.framework,
+ org.osgi.service.component,
+ org.apache.commons.logging.*,
+ org.wso2.carbon.user.core.*,
+ org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}",
+ org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}",
+ org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}",
+ org.wso2.carbon.user.api,
+ org.wso2.carbon.utils.multitenancy,
+ org.json.simple,
+ org.wso2.carbon.context
+
+
+ !org.wso2.carbon.apimgt.application.extension.internal,
+ org.wso2.carbon.apimgt.application.extension.*
+
+
+
+
+
+
+
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java
new file mode 100644
index 00000000000..643d66c23d9
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderService.java
@@ -0,0 +1,70 @@
+/*
+ * 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.apimgt.application.extension;
+
+
+import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
+import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
+
+/**
+ * This comprise on operation that is been done with api manager from CDMF. This service needs to be implemented in APIM.
+ */
+public interface APIManagementProviderService {
+
+ /**
+ * Generate and retreive application keys. if the application does exist then
+ * create it and subscribe to apis that are grouped with the tags.
+ *
+ * @param apiApplicationName name of the application.
+ * @param tags tags of the apis that application needs to be subscribed.
+ * @param keyType of the application.
+ * @param username to whom the application is created
+ * @return consumerkey and secrete of the created application.
+ * @throws APIManagerException
+ */
+ ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[],
+ String keyType, String username, boolean isAllowedAllDomains)
+ throws APIManagerException;
+
+ /**
+ * Generate and retreive application keys. if the application does exist then
+ * create it and subscribe to all apis.
+ *
+ * @param apiApplicationName name of the application.
+ * @param keyType of the application.
+ * @param username to whom the application is created
+ * @return consumerkey and secrete of the created application.
+ * @throws APIManagerException
+ */
+ ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String keyType,
+ String username, boolean isAllowedAllDomains)
+ throws APIManagerException;
+
+ /**
+ * Register existing Oauth application as apim application.
+ */
+ void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName, String clientId,
+ String username, boolean isAllowedAllDomains)
+ throws APIManagerException;
+
+ /**
+ * Remove APIM Application.
+ */
+ void removeAPIApplication(String applicationName, String username) throws APIManagerException;
+
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java
new file mode 100644
index 00000000000..7a2af128d88
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java
@@ -0,0 +1,406 @@
+/*
+ * 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.apimgt.application.extension;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.json.simple.JSONObject;
+import org.wso2.carbon.apimgt.api.APIConsumer;
+import org.wso2.carbon.apimgt.api.APIManagementException;
+import org.wso2.carbon.apimgt.api.model.API;
+import org.wso2.carbon.apimgt.api.model.APIIdentifier;
+import org.wso2.carbon.apimgt.api.model.APIKey;
+import org.wso2.carbon.apimgt.api.model.Application;
+import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
+import org.wso2.carbon.apimgt.api.model.Subscriber;
+import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
+import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
+import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
+import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil;
+import org.wso2.carbon.apimgt.impl.APIConstants;
+import org.wso2.carbon.apimgt.impl.APIManagerFactory;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
+
+import java.util.Date;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This class represents an implementation of APIManagementProviderService.
+ */
+public class APIManagementProviderServiceImpl implements APIManagementProviderService {
+
+ private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class);
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String keyType,
+ String username, boolean isAllowedAllDomains)
+ throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ int applicationId = createApplicationAndSubscribeToAllAPIs(apiApplicationName, username);
+ Application[] applications = apiConsumer.getApplications(apiConsumer.getSubscriber(username), groupId);
+ Application application = null;
+ for (Application app : applications) {
+ if (app.getId() == applicationId) {
+ application = app;
+ }
+ }
+ if (application == null) {
+ throw new APIManagerException("Api application creation failed for " + apiApplicationName +
+ " to the user " + username);
+ }
+ APIKey retrievedApiApplicationKey = null;
+ for (APIKey apiKey : application.getKeys()) {
+ String applicationKeyType = apiKey.getType();
+ if (applicationKeyType != null && applicationKeyType.equals(keyType)) {
+ retrievedApiApplicationKey = apiKey;
+ break;
+ }
+ }
+ if (retrievedApiApplicationKey != null) {
+ ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
+ apiApplicationKey.setConsumerKey(retrievedApiApplicationKey.getConsumerKey());
+ apiApplicationKey.setConsumerSecret(retrievedApiApplicationKey.getConsumerSecret());
+ return apiApplicationKey;
+ }
+ String[] allowedDomains = new String[1];
+ if (isAllowedAllDomains) {
+ allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS;
+ } else {
+ allowedDomains[0] = APIManagerUtil.getTenantDomain();
+ }
+ JSONObject jsonObject = new JSONObject();
+ jsonObject.put(ApiApplicationConstants.JSONSTRING_USERNAME_TAG, username);
+ String ownerJsonString = jsonObject.toJSONString();
+ Map keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username,
+ apiApplicationName,
+ keyType, "",
+ allowedDomains,
+ ApiApplicationConstants.DEFAULT_VALIDITY_PERIOD,
+ "null", groupId,
+ ownerJsonString);
+ ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
+ apiApplicationKey.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames
+ .CONSUMER_KEY));
+ apiApplicationKey.setConsumerSecret((String) keyDetails.get(
+ APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
+ return apiApplicationKey;
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to register a api application : " + apiApplicationName, e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public void registerExistingOAuthApplicationToAPIApplication(String jsonString, String applicationName,
+ String clientId, String username,
+ boolean isAllowedAllDomains)
+ throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ if (apiConsumer != null) {
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ createApplication(apiConsumer, applicationName, username, groupId);
+ String[] allowedDomains = new String[1];
+ if (isAllowedAllDomains) {
+ allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS;
+ } else {
+ allowedDomains[0] = APIManagerUtil.getTenantDomain();
+ }
+ apiConsumer.mapExistingOAuthClient(jsonString, username, clientId, applicationName,
+ ApiApplicationConstants.DEFAULT_TOKEN_TYPE, allowedDomains);
+ }
+ } catch (APIManagementException e) {
+ throw new APIManagerException(
+ "Failed registering the OAuth app [ clientId " + clientId + " ] with api manager application", e);
+ }
+ }
+
+ @Override
+ public void removeAPIApplication(String applicationName, String username) throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ if (apiConsumer != null) {
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ Application[] applications = apiConsumer.getApplications(new Subscriber(username), groupId);
+ for (Application application : applications) {
+ if (application.getName().equals(applicationName)) {
+ apiConsumer.removeApplication(application);
+ break;
+ }
+ }
+ }
+ } catch (APIManagementException e) {
+ throw new APIManagerException(
+ "Failed to remove the application [ application name " + applicationName + " ]", e);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName, String tags[],
+ String keyType, String username,
+ boolean isAllowedAllDomains)
+ throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ int applicationId = createApplicationAndSubscribeToAPIs(apiApplicationName, tags, username);
+ Application[] applications = apiConsumer.getApplications(apiConsumer.getSubscriber(username), groupId);
+ Application application = null;
+ for (Application app : applications) {
+ if (app.getId() == applicationId) {
+ application = app;
+ }
+ }
+ if (application == null) {
+ throw new APIManagerException(
+ "Api application creation failed for " + apiApplicationName + " to the user " + username);
+ }
+
+ APIKey retrievedApiApplicationKey = null;
+ for (APIKey apiKey : application.getKeys()) {
+ String applicationKeyType = apiKey.getType();
+ if (applicationKeyType != null && applicationKeyType.equals(keyType)) {
+ retrievedApiApplicationKey = apiKey;
+ break;
+ }
+ }
+ if (retrievedApiApplicationKey != null) {
+ ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
+ apiApplicationKey.setConsumerKey(retrievedApiApplicationKey.getConsumerKey());
+ apiApplicationKey.setConsumerSecret(retrievedApiApplicationKey.getConsumerSecret());
+ return apiApplicationKey;
+ }
+ String[] allowedDomains = new String[1];
+ if (isAllowedAllDomains) {
+ allowedDomains[0] = ApiApplicationConstants.ALLOWED_DOMAINS;
+ } else {
+ allowedDomains[0] = APIManagerUtil.getTenantDomain();
+ }
+ String validityTime = "3600";
+ String ownerJsonString = "{\"username\":\"" + username + "\"}";
+ Map keyDetails = apiConsumer.requestApprovalForApplicationRegistration(username,
+ apiApplicationName,
+ keyType, "",
+ allowedDomains,
+ validityTime,
+ "null",
+ groupId,
+ ownerJsonString);
+ ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
+ apiApplicationKey.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames
+ .CONSUMER_KEY));
+ apiApplicationKey.setConsumerSecret((String) keyDetails.get(
+ APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
+ return apiApplicationKey;
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to register a api application : " + apiApplicationName, e);
+ }
+ }
+
+ private int createApplication(APIConsumer apiConsumer, String applicationName, String username, String groupId)
+ throws APIManagerException {
+ try {
+ if (apiConsumer != null) {
+ if (apiConsumer.getSubscriber(username) == null) {
+ String tenantDomain = MultitenantUtils.getTenantDomain(username);
+ addSubscriber(username, "", groupId, APIManagerUtil.getTenantId(tenantDomain));
+ }
+ Application application = apiConsumer.getApplicationsByName(username, applicationName, groupId);
+ if (application == null) {
+ Subscriber subscriber = apiConsumer.getSubscriber(username);
+ application = new Application(applicationName, subscriber);
+ application.setTier(ApiApplicationConstants.DEFAULT_TIER);
+ application.setGroupId(groupId);
+ return apiConsumer.addApplication(application, username);
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Application [" + applicationName + "] already exists for Subscriber [" + username +
+ "]");
+ }
+ return application.getId();
+ }
+ } else {
+ throw new APIManagerException("Failed to retrieve the api consumer for username" + username);
+ }
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to create application [name:" + applicationName + " , username:"
+ + username + ", " + "groupId:" + groupId, e);
+ }
+ }
+
+ private void addSubscription(APIConsumer apiConsumer, APIIdentifier apiId, int applicationId, String username)
+ throws APIManagerException {
+ try {
+ if (apiConsumer != null) {
+ APIIdentifier apiIdentifier = new APIIdentifier(apiId.getProviderName(), apiId.getApiName(),
+ apiId.getVersion());
+ apiIdentifier.setTier(ApiApplicationConstants.DEFAULT_TIER);
+ apiConsumer.addSubscription(apiIdentifier, username, applicationId);
+ if (log.isDebugEnabled()) {
+ log.debug("Successfully created subscription for API : " + apiId + " from application : " +
+ applicationId);
+ }
+ } else {
+ throw new APIManagerException("API provider configured for the given API configuration is null. " +
+ "Thus, the API is not published");
+ }
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to create subscription for api name : " + apiId.getApiName(), e);
+ }
+ }
+
+
+ private void addSubscriber(String subscriberName, String subscriberEmail, String groupId, int tenantId)
+ throws APIManagerException {
+ if (log.isDebugEnabled()) {
+ log.debug("Creating subscriber with name " + subscriberName);
+ }
+ try {
+ APIConsumer consumer = APIManagerFactory.getInstance().getAPIConsumer(subscriberName);
+ if (consumer != null) {
+ Subscriber subscriber = new Subscriber(subscriberName);
+ subscriber.setSubscribedDate(new Date());
+ subscriber.setEmail(subscriberEmail);
+ subscriber.setTenantId(tenantId);
+ consumer.addSubscriber(subscriber, groupId);
+ if (log.isDebugEnabled()) {
+ log.debug("Successfully created subscriber with name : " + subscriberName + " with groupID : " +
+ groupId);
+ }
+ } else {
+ throw new APIManagerException("API provider configured for the given API configuration is null. " +
+ "Thus, the API is not published");
+ }
+ } catch (APIManagementException e) {
+ throw new APIManagerException("API provider configured for the given API configuration is null. " +
+ "Thus, the API is not published", e);
+ }
+ }
+
+ /**
+ * This method registers an api application and then subscribe the application to the api.
+ *
+ * @param apiApplicationName name of the application.
+ * @param tags are used subscribe the apis with the tag.
+ * @param username subscription is created for the user.
+ * @throws APIManagerException
+ */
+ private int createApplicationAndSubscribeToAPIs(String apiApplicationName, String tags[], String username)
+ throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId);
+ Subscriber subscriber = apiConsumer.getSubscriber(username);
+ Set userVisibleAPIs = null;
+ for (String tag : tags) {
+ Set tagAPIs = apiConsumer.getAPIsWithTag(tag);
+ if (userVisibleAPIs == null) {
+ userVisibleAPIs = tagAPIs;
+ } else {
+ userVisibleAPIs.addAll(tagAPIs);
+ }
+ }
+ if (userVisibleAPIs != null) {
+ Set subscribedAPIs = apiConsumer.getSubscribedAPIs(subscriber, apiApplicationName,
+ groupId);
+ for (API userVisbleAPI : userVisibleAPIs) {
+ APIIdentifier apiIdentifier = userVisbleAPI.getId();
+ boolean isSubscribed = false;
+ if (subscribedAPIs != null) {
+ for (SubscribedAPI subscribedAPI : subscribedAPIs) {
+ if (subscribedAPI.getApiId().equals(apiIdentifier)) {
+ isSubscribed = true;
+ }
+ }
+ }
+ if (!isSubscribed) {
+ addSubscription(apiConsumer, apiIdentifier, applicationId, username);
+ }
+ }
+ }
+ return applicationId;
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to fetch device apis information for the user " + username, e);
+ }
+ }
+
+ /**
+ * This method registers an api application and then subscribe the application to the api.
+ *
+ * @param username subscription is created for the user.
+ * @throws APIManagerException
+ */
+ private int createApplicationAndSubscribeToAllAPIs(String apiApplicationName, String username)
+ throws APIManagerException {
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ String groupId = getLoggedInUserGroupId(username, APIManagerUtil.getTenantDomain());
+ int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId);
+ String tenantDomain = MultitenantUtils.getTenantDomain(username);
+ Set userVisibleAPIs = apiConsumer.getAllPublishedAPIs(tenantDomain);
+ Subscriber subscriber = apiConsumer.getSubscriber(username);
+ Set subscribedAPIs = apiConsumer.getSubscribedAPIs(subscriber);
+ for (API visibleApi : userVisibleAPIs) {
+ APIIdentifier apiIdentifier = visibleApi.getId();
+ boolean isSubscribed = false;
+ for (SubscribedAPI subscribedAPI : subscribedAPIs) {
+ if (subscribedAPI.getApiId().equals(apiIdentifier)) {
+ isSubscribed = true;
+ }
+ }
+ if (!isSubscribed) {
+ addSubscription(apiConsumer, apiIdentifier, applicationId, username);
+ }
+ }
+ return applicationId;
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Failed to fetch device apis information for the user " + username, e);
+ }
+ }
+
+ private String getLoggedInUserGroupId(String username, String tenantDomain) throws APIManagerException {
+ JSONObject loginInfoJsonObj = new JSONObject();
+ try {
+ APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
+ loginInfoJsonObj.put("user", username);
+ if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+ loginInfoJsonObj.put("isSuperTenant", true);
+ } else {
+ loginInfoJsonObj.put("isSuperTenant", false);
+ }
+ String loginInfoString = loginInfoJsonObj.toString();
+ return apiConsumer.getGroupIds(loginInfoString);
+ } catch (APIManagementException e) {
+ throw new APIManagerException("Unable to get groupIds of user " + username, e);
+ }
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java
new file mode 100644
index 00000000000..821256a2af4
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/constants/ApiApplicationConstants.java
@@ -0,0 +1,31 @@
+/*
+ * 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.apimgt.application.extension.constants;
+
+public class ApiApplicationConstants {
+ public static final String DEFAULT_TOKEN_TYPE = "PRODUCTION";
+ public static final String DEFAULT_TIER = "Unlimited";
+ public static final String ALLOWED_DOMAINS = "ALL";
+ public static final String OAUTH_CLIENT_ID = "client_id";
+ public static final String OAUTH_CLIENT_SECRET = "client_secret";
+ public static final String DEFAULT_VALIDITY_PERIOD = "3600";
+ public static final String JSONSTRING_USERNAME_TAG = "username";
+ public static final String JSONSTRING_KEY_TYPE_TAG = "key_type";
+ public static final String JSONSTRING_VALIDITY_PERIOD_TAG = "validityPeriod";
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java
new file mode 100644
index 00000000000..58e3b713e13
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/dto/ApiApplicationKey.java
@@ -0,0 +1,53 @@
+/*
+ * 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.apimgt.application.extension.dto;
+
+import org.json.simple.JSONObject;
+import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
+
+/**
+ * This holds api application consumer key and secret.
+ */
+public class ApiApplicationKey {
+ private String consumerKey;
+ private String consumerSecret;
+
+ public String getConsumerKey() {
+ return this.consumerKey;
+ }
+
+ public void setConsumerKey(String consumerKey) {
+ this.consumerKey = consumerKey;
+ }
+
+ public String getConsumerSecret() {
+ return this.consumerSecret;
+ }
+
+ public void setConsumerSecret(String consumerSecret) {
+ this.consumerSecret = consumerSecret;
+ }
+
+ public String toString() {
+ JSONObject obj = new JSONObject();
+ obj.put(ApiApplicationConstants.OAUTH_CLIENT_ID, this.getConsumerKey());
+ obj.put(ApiApplicationConstants.OAUTH_CLIENT_SECRET, this.getConsumerSecret());
+ return obj.toString();
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java
new file mode 100644
index 00000000000..b77bb584f4a
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/exception/APIManagerException.java
@@ -0,0 +1,60 @@
+/*
+ * 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.apimgt.application.extension.exception;
+
+/**
+ * Handles the exceptions related to API management.
+ */
+public class APIManagerException extends Exception {
+
+ private static final long serialVersionUID = -8933142342423122660L;
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public APIManagerException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public APIManagerException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public APIManagerException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public APIManagerException() {
+ super();
+ }
+
+ public APIManagerException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java
new file mode 100644
index 00000000000..6f360ae6492
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionDataHolder.java
@@ -0,0 +1,69 @@
+/*
+ * 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.apimgt.application.extension.internal;
+
+import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
+import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.user.core.tenant.TenantManager;
+
+public class APIApplicationManagerExtensionDataHolder {
+ private static APIApplicationManagerExtensionDataHolder thisInstance = new APIApplicationManagerExtensionDataHolder();
+ private APIManagementProviderService apiManagementProviderService;
+ private RealmService realmService;
+ private TenantManager tenantManager;
+
+ private APIApplicationManagerExtensionDataHolder() {
+ }
+
+
+ public static APIApplicationManagerExtensionDataHolder getInstance() {
+ return thisInstance;
+ }
+
+ public APIManagementProviderService getAPIManagementProviderService() {
+ return apiManagementProviderService;
+ }
+
+ public void setAPIManagementProviderService(
+ APIManagementProviderService apiManagementProviderService) {
+ this.apiManagementProviderService = apiManagementProviderService;
+ }
+
+ public RealmService getRealmService() {
+ if (realmService == null) {
+ throw new IllegalStateException("Realm service is not initialized properly");
+ }
+ return realmService;
+ }
+
+ public void setRealmService(RealmService realmService) {
+ this.realmService = realmService;
+ this.setTenantManager(realmService);
+ }
+
+ private void setTenantManager(RealmService realmService) {
+ if (realmService == null) {
+ throw new IllegalStateException("Realm service is not initialized properly");
+ }
+ this.tenantManager = realmService.getTenantManager();
+ }
+
+ public TenantManager getTenantManager() {
+ return tenantManager;
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java
new file mode 100644
index 00000000000..557d47aa110
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/internal/APIApplicationManagerExtensionServiceComponent.java
@@ -0,0 +1,79 @@
+/*
+ * 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.apimgt.application.extension.internal;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleContext;
+import org.osgi.service.component.ComponentContext;;
+import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
+import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl;
+import org.wso2.carbon.user.core.service.RealmService;
+
+/**
+ * @scr.component name="org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionServiceComponent"
+ * @scr.reference name="realm.service"
+ * immediate="true"
+ * interface="org.wso2.carbon.user.core.service.RealmService"
+ * cardinality="1..1"
+ * policy="dynamic"
+ * bind="setRealmService"
+ * unbind="unsetRealmService"
+ */
+public class APIApplicationManagerExtensionServiceComponent {
+
+ private static Log log = LogFactory.getLog(APIApplicationManagerExtensionServiceComponent.class);
+
+ protected void activate(ComponentContext componentContext) {
+ if (log.isDebugEnabled()) {
+ log.debug("Initializing device extension bundle");
+ }
+ APIManagementProviderService apiManagementProviderService = new APIManagementProviderServiceImpl();
+ APIApplicationManagerExtensionDataHolder.getInstance().setAPIManagementProviderService(apiManagementProviderService);
+ BundleContext bundleContext = componentContext.getBundleContext();
+ bundleContext.registerService(APIManagementProviderService.class.getName(), apiManagementProviderService, null);
+ }
+
+ protected void deactivate(ComponentContext componentContext) {
+ //do nothing
+ }
+
+ /**
+ * Sets Realm Service.
+ *
+ * @param realmService An instance of RealmService
+ */
+ protected void setRealmService(RealmService realmService) {
+ if (log.isDebugEnabled()) {
+ log.debug("Setting Realm Service");
+ }
+ APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(realmService);
+ }
+
+ /**
+ * Unsets Realm Service.
+ *
+ * @param realmService An instance of RealmService
+ */
+ protected void unsetRealmService(RealmService realmService) {
+ if (log.isDebugEnabled()) {
+ log.debug("Unsetting Realm Service");
+ }
+ APIApplicationManagerExtensionDataHolder.getInstance().setRealmService(null);
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java
new file mode 100644
index 00000000000..96dba4cfb4d
--- /dev/null
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java
@@ -0,0 +1,55 @@
+/*
+ * 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.apimgt.application.extension.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
+import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
+import org.wso2.carbon.base.MultitenantConstants;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.user.api.TenantManager;
+import org.wso2.carbon.user.api.UserStoreException;
+
+public final class APIManagerUtil {
+
+ private static final Log log = LogFactory.getLog(APIManagerUtil.class);
+
+ /**
+ * returns the tenant Id of the specific tenant Domain
+ */
+ public static int getTenantId(String tenantDomain) throws APIManagerException {
+ try {
+ if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
+ return MultitenantConstants.SUPER_TENANT_ID;
+ }
+ TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager();
+ int tenantId = tenantManager.getTenantId(tenantDomain);
+ if (tenantId == -1) {
+ throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
+ }
+ return tenantId;
+ } catch (UserStoreException e) {
+ throw new APIManagerException("invalid tenant Domain :" + tenantDomain);
+ }
+ }
+
+ public static String getTenantDomain() {
+ return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
+ }
+}
diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml
index 2ff22c9086b..c17a81051c4 100644
--- a/components/apimgt-extensions/pom.xml
+++ b/components/apimgt-extensions/pom.xml
@@ -1,21 +1,21 @@
+ ~ 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.
+ -->
@@ -27,7 +27,6 @@
4.0.0
- org.wso2.carbon.devicemgt
apimgt-extensions
1.1.0-SNAPSHOT
pom
@@ -36,6 +35,9 @@
org.wso2.carbon.apimgt.webapp.publisher
+ org.wso2.carbon.apimgt.application.extension
+ org.wso2.carbon.apimgt.application.extension.api
+ org.wso2.carbon.apimgt.annotations
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java
index a2dd9062202..375b8d45628 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Feature.java
@@ -1,22 +1,23 @@
/*
- * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 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
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
+ * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.common;
+import javax.xml.bind.annotation.XmlElement;
import java.io.Serializable;
import java.util.List;
@@ -27,8 +28,11 @@ public class Feature implements Serializable {
private String name;
private String description;
private String deviceType;
+ private String method;
+ private String type;
private List metadataEntries;
+ @XmlElement
public int getId() {
return id;
}
@@ -37,6 +41,7 @@ public class Feature implements Serializable {
this.id = id;
}
+ @XmlElement
public String getCode() {
return code;
}
@@ -45,6 +50,7 @@ public class Feature implements Serializable {
this.code = code;
}
+ @XmlElement
public String getName() {
return name;
}
@@ -61,6 +67,7 @@ public class Feature implements Serializable {
this.metadataEntries = metadataEntries;
}
+ @XmlElement
public String getDeviceType() {
return deviceType;
}
@@ -69,6 +76,7 @@ public class Feature implements Serializable {
this.deviceType = deviceType;
}
+ @XmlElement
public String getDescription() {
return description;
}
@@ -77,6 +85,24 @@ public class Feature implements Serializable {
this.description = description;
}
+ @XmlElement
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ @XmlElement
+ public String getMethod() {
+ return method;
+ }
+
+ public void setMethod(String method) {
+ this.method = method;
+ }
+
public static class MetadataEntry implements Serializable {
private int id;
@@ -98,5 +124,4 @@ public class Feature implements Serializable {
this.value = value;
}
}
-
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java
index 0be33284e6f..2c106da8295 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroup.java
@@ -29,6 +29,7 @@ import java.util.List;
@XmlRootElement
public class DeviceGroup implements Serializable {
+ private int id;
private String description;
private String name;
private Long dateOfCreation;
@@ -37,6 +38,15 @@ public class DeviceGroup implements Serializable {
private List users;
private List roles;
+ @XmlElement
+ public int getId() {
+ return id;
+ }
+
+ protected void setId(int id) {
+ this.id = id;
+ }
+
@XmlElement
public String getDescription() {
return description;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java
index 99098ad07ec..b2409b2d70e 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/DeviceGroupBuilder.java
@@ -34,6 +34,7 @@ public class DeviceGroupBuilder extends DeviceGroup {
* @param deviceGroup to decorate
*/
public DeviceGroupBuilder(DeviceGroup deviceGroup) {
+ this.setId(deviceGroup.getId());
this.setDescription(deviceGroup.getDescription());
this.setName(deviceGroup.getName());
this.setDateOfCreation(deviceGroup.getDateOfCreation());
@@ -43,6 +44,11 @@ public class DeviceGroupBuilder extends DeviceGroup {
this.setRoles(deviceGroup.getRoles());
}
+ @Override
+ public void setId(int id) {
+ super.setId(id);
+ }
+
@Override
public void setUsers(List users) {
super.setUsers(users);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java
index dbb98c2e74e..a353ff25c66 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAO.java
@@ -19,83 +19,149 @@
package org.wso2.carbon.device.mgt.core.group.mgt.dao;
import org.wso2.carbon.device.mgt.common.Device;
-import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.List;
-import java.util.Set;
/**
* This interface represents the key operations associated with persisting group related information.
*/
public interface GroupDAO {
/**
- * Add new Device Group
+ * Add new Device Group.
*
- * @param deviceGroup to be added
- * @param tenantId of the group
- * @return sql execution result
+ * @param deviceGroup to be added.
+ * @param tenantId of the group.
+ * @return sql execution result.
* @throws GroupManagementDAOException
*/
int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException;
/**
- * Update an existing Device Group
+ * Update an existing Device Group.
*
- * @param deviceGroup group to update
+ * @param deviceGroup group to update.
* @throws GroupManagementDAOException
*/
void updateGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException;
/**
- * Delete an existing Device Group
+ * Delete an existing Device Group.
*
- * @param groupName group Id to delete
+ * @param groupId to be deleted.
* @throws GroupManagementDAOException
*/
- void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException;
+ void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/**
- * Get device group by Id
+ * Get device group by id.
*
- * @param groupName id of Device Group
- * @return Device Group
+ * @param groupId of Device Group.
+ * @return Device Group in tenant with specified name.
* @throws GroupManagementDAOException
*/
- DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException;
+ DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant.
*
- * @param tenantId of user's tenant
+ * @param request for pagination.
+ * @param tenantId of user's tenant.
* @return List of all Device Groups in tenant.
* @throws GroupManagementDAOException
*/
- List getGroups(int tenantId) throws GroupManagementDAOException;
+ List getGroups(PaginationRequest request, int tenantId) throws GroupManagementDAOException;
+
+
+ /**
+ * Get count of Device Groups in tenant.
+ *
+ * @param tenantId of user's tenant.
+ * @return List of all Device Groups in tenant.
+ * @throws GroupManagementDAOException
+ */
+ int getGroupCount(int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Groups that matches with the given DeviceGroup name.
*
- * @param groupName name of the Device Group.
- * @param tenantId of user's tenant
+ * @param groupName of the Device Group.
+ * @param tenantId of user's tenant.
* @return List of DeviceGroup that matches with the given DeviceGroup name.
* @throws GroupManagementDAOException
*/
- List getGroups(String groupName, int tenantId) throws GroupManagementDAOException;
+ List findInGroups(String groupName, int tenantId) throws GroupManagementDAOException;
+ /**
+ * Check group already existed with given name.
+ *
+ * @param groupName of the Device Group.
+ * @param tenantId of user's tenant.
+ * @return existence of group with name
+ * @throws GroupManagementDAOException
+ */
boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException;
- void addDeviceToGroup(String groupName, Device device, int tenantId) throws GroupManagementDAOException;
+ /**
+ * Add device to a given Device Group.
+ *
+ * @param groupId of the Device Group.
+ * @param deviceId of the device.
+ * @param tenantId of user's tenant.
+ * @throws GroupManagementDAOException
+ */
+ void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
- void addDevicesToGroup(String groupName, Set devices, int tenantId) throws GroupManagementDAOException;
+ /**
+ * Remove device from the Device Group.
+ *
+ * @param groupId of the Device Group.
+ * @param deviceId of the device.
+ * @param tenantId of user's tenant.
+ * @throws GroupManagementDAOException
+ */
+ void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
- void removeDeviceFromGroup(String groupName, DeviceIdentifier id,
- int tenantId) throws GroupManagementDAOException;
+ /**
+ * Check device is belonging to a Device Group.
+ *
+ * @param groupId of the Device Group.
+ * @param deviceId of the device.
+ * @param tenantId of user's tenant.
+ * @throws GroupManagementDAOException
+ */
+ boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException;
- boolean isDeviceMappedToGroup(String groupName, DeviceIdentifier id,
- int tenantId) throws GroupManagementDAOException;
+ /**
+ * Get count of devices in a Device Group.
+ *
+ * @param groupId of the Device Group.
+ * @param tenantId of user's tenant.
+ * @return device count.
+ * @throws GroupManagementDAOException
+ */
+ int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException;
- int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException;
+ /**
+ * Get all devices of a given tenant and device group.
+ *
+ * @param groupId of the group.
+ * @param tenantId of user's tenant.
+ * @return list of device in group
+ * @throws GroupManagementDAOException
+ */
+ List getDevices(int groupId, int tenantId) throws GroupManagementDAOException;
+ /**
+ * Get all devices of a given tenant and device group.
+ *
+ * @param groupId of the group.
+ * @param request for pagination.
+ * @param tenantId of user's tenant.
+ * @return list of device in group
+ * @throws GroupManagementDAOException
+ */
+ List getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java
index 767e6ef367f..702e20c44ac 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupDAOImpl.java
@@ -19,8 +19,9 @@
package org.wso2.carbon.device.mgt.core.group.mgt.dao;
import org.wso2.carbon.device.mgt.common.Device;
-import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.sql.Connection;
@@ -30,7 +31,6 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-import java.util.Set;
/**
* This class represents implementation of GroupDAO
@@ -44,9 +44,9 @@ public class GroupDAOImpl implements GroupDAO {
int groupId = -1;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
- String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, "
+ String sql = "INSERT INTO DM_GROUP(DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, "
+ "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)";
- stmt = conn.prepareStatement(sql, new String[]{"id"});
+ stmt = conn.prepareStatement(sql, new String[]{"ID"});
stmt.setString(1, deviceGroup.getDescription());
stmt.setString(2, deviceGroup.getName());
stmt.setLong(3, new Date().getTime());
@@ -73,13 +73,13 @@ public class GroupDAOImpl implements GroupDAO {
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "UPDATE DM_GROUP SET DESCRIPTION = ?, GROUP_NAME = ?, DATE_OF_LAST_UPDATE = ?, OWNER = ? "
- + "WHERE NAME = ? AND TENANT_ID = ?";
+ + "WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, deviceGroup.getDescription());
stmt.setString(2, deviceGroup.getName());
stmt.setLong(3, deviceGroup.getDateOfLastUpdate());
stmt.setString(4, deviceGroup.getOwner());
- stmt.setString(5, deviceGroup.getName());
+ stmt.setInt(5, deviceGroup.getId());
stmt.setInt(6, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
@@ -91,33 +91,46 @@ public class GroupDAOImpl implements GroupDAO {
}
@Override
- public void deleteGroup(String groupName, int tenantId) throws GroupManagementDAOException {
+ public void deleteGroup(int groupId, int tenantId) throws GroupManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
try {
conn = GroupManagementDAOFactory.getConnection();
- String sql = "DELETE FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?";
+ String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, groupName);
+ stmt.setInt(1, groupId);
+ stmt.setInt(2, tenantId);
+ stmt.executeUpdate();
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while removing mappings for group '" + groupId + "'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, null);
+ }
+
+ try {
+ conn = GroupManagementDAOFactory.getConnection();
+ String sql = "DELETE FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
stmt.executeUpdate();
} catch (SQLException e) {
- throw new GroupManagementDAOException("Error occurred while deleting group '" + groupName + "'", e);
+ throw new GroupManagementDAOException("Error occurred while deleting group '" + groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, null);
}
}
@Override
- public DeviceGroupBuilder getGroup(String groupName, int tenantId) throws GroupManagementDAOException {
+ public DeviceGroupBuilder getGroup(int groupId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
- String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER "
- + "FROM DM_GROUP WHERE NAME = ? AND TENANT_ID = ?";
+ String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ + "FROM DM_GROUP WHERE ID = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
- stmt.setString(1, groupName);
+ stmt.setInt(1, groupId);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
@@ -127,23 +140,28 @@ public class GroupDAOImpl implements GroupDAO {
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while obtaining information of Device Group '" +
- groupName + "'", e);
+ groupId + "'", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
- public List getGroups(int tenantId) throws GroupManagementDAOException {
+ public List getGroups(PaginationRequest request, int tenantId)
+ throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List deviceGroupList = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
- String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER "
- + "FROM DM_GROUP WHERE TENANT_ID = ?";
+ String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ + "FROM DM_GROUP WHERE TENANT_ID = ? LIMIT ?, ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
+ //noinspection JpaQueryApiInspection
+ stmt.setInt(2, request.getStartIndex());
+ //noinspection JpaQueryApiInspection
+ stmt.setInt(3, request.getRowCount());
resultSet = stmt.executeQuery();
deviceGroupList = new ArrayList<>();
while (resultSet.next()) {
@@ -158,14 +176,36 @@ public class GroupDAOImpl implements GroupDAO {
}
@Override
- public List getGroups(String groupName, int tenantId)
+ public int getGroupCount(int tenantId) throws GroupManagementDAOException {
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ Connection conn = GroupManagementDAOFactory.getConnection();
+ String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, tenantId);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("DEVICE_COUNT");
+ } else {
+ return 0;
+ }
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while getting group count'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
+ }
+ }
+
+ @Override
+ public List findInGroups(String groupName, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List deviceGroups = new ArrayList<>();
try {
Connection conn = GroupManagementDAOFactory.getConnection();
- String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, OWNER "
+ String sql = "SELECT ID, DESCRIPTION, GROUP_NAME, DATE_OF_CREATE, DATE_OF_LAST_UPDATE, OWNER "
+ "FROM DM_GROUP WHERE GROUP_NAME LIKE ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + groupName + "%");
@@ -186,49 +226,185 @@ public class GroupDAOImpl implements GroupDAO {
@Override
public boolean isGroupExist(String groupName, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
- ResultSet rst = null;
+ ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT ID FROM DM_GROUP WHERE GROUP_NAME = ? AND TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName);
stmt.setInt(2, tenantId);
- rst = stmt.executeQuery();
- return rst.next();
+ resultSet = stmt.executeQuery();
+ return resultSet.next();
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
groupName + "'", e);
} finally {
- GroupManagementDAOUtil.cleanupResources(stmt, rst);
+ GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
}
@Override
- public void addDeviceToGroup(String group, Device device, int tenantId) throws GroupManagementDAOException {
-
+ public void addDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException {
+ PreparedStatement stmt = null;
+ try {
+ Connection conn = GroupManagementDAOFactory.getConnection();
+ String sql = "INSERT INTO DM_DEVICE_GROUP_MAP(DEVICE_ID, GROUP_ID, TENANT_ID) VALUES (?, ?, ?)";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, deviceId);
+ stmt.setInt(2, groupId);
+ stmt.setInt(3, tenantId);
+ stmt.executeUpdate();
+ stmt.getGeneratedKeys();
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while adding device to Group '" + groupId + "'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, null);
+ }
}
@Override
- public void addDevicesToGroup(String group, Set devices,
- int tenantId) throws GroupManagementDAOException {
-
+ public void removeDevice(int groupId, int deviceId, int tenantId) throws GroupManagementDAOException {
+ PreparedStatement stmt = null;
+ try {
+ Connection conn = GroupManagementDAOFactory.getConnection();
+ String sql = "DELETE FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, deviceId);
+ stmt.setInt(2, groupId);
+ stmt.setInt(3, tenantId);
+ stmt.executeUpdate();
+ stmt.getGeneratedKeys();
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while removing device from Group '" +
+ groupId + "'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, null);
+ }
}
@Override
- public void removeDeviceFromGroup(String group, DeviceIdentifier id,
- int tenantId) throws GroupManagementDAOException {
+ public boolean isDeviceMappedToGroup(int groupId, int deviceId, int tenantId)
+ throws GroupManagementDAOException {
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ Connection conn = GroupManagementDAOFactory.getConnection();
+ String sql = "SELECT ID FROM DM_DEVICE_GROUP_MAP WHERE DEVICE_ID = ? AND GROUP_ID = ? AND TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, deviceId);
+ stmt.setInt(2, groupId);
+ stmt.setInt(3, tenantId);
+ resultSet = stmt.executeQuery();
+ return resultSet.next();
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
+ groupId + "'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
+ }
+ }
+ @Override
+ public int getDeviceCount(int groupId, int tenantId) throws GroupManagementDAOException {
+ PreparedStatement stmt = null;
+ ResultSet resultSet = null;
+ try {
+ Connection conn = GroupManagementDAOFactory.getConnection();
+ String sql = "SELECT COUNT(ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP WHERE GROUP_ID = ? " +
+ "AND TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, groupId);
+ stmt.setInt(2, tenantId);
+ resultSet = stmt.executeQuery();
+ if (resultSet.next()) {
+ return resultSet.getInt("DEVICE_COUNT");
+ } else {
+ return 0;
+ }
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while group Id listing by group name '" +
+ groupId + "'", e);
+ } finally {
+ GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
+ }
}
@Override
- public boolean isDeviceMappedToGroup(String group, DeviceIdentifier id,
- int tenantId) throws GroupManagementDAOException {
- return false;
+ public List getDevices(int groupId, int tenantId) throws GroupManagementDAOException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ List devices = null;
+ try {
+ conn = GroupManagementDAOFactory.getConnection();
+ String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
+ "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " +
+ "gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
+ "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " +
+ "d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " +
+ "AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " +
+ "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, groupId);
+ stmt.setInt(2, tenantId);
+ stmt.setInt(3, tenantId);
+ rs = stmt.executeQuery();
+ devices = new ArrayList<>();
+ while (rs.next()) {
+ Device device = DeviceManagementDAOUtil.loadDevice(rs);
+ devices.add(device);
+ }
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while retrieving information of all " +
+ "registered devices", e);
+ } finally {
+ DeviceManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+ return devices;
}
+ @SuppressWarnings("JpaQueryApiInspection")
@Override
- public int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException {
- return 0;
+ public List getDevices(int groupId, PaginationRequest request, int tenantId)
+ throws GroupManagementDAOException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ List devices = null;
+ try {
+ conn = GroupManagementDAOFactory.getConnection();
+ String sql = "SELECT d1.DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " +
+ "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " +
+ "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT gd.DEVICE_ID, " +
+ "gd.DESCRIPTION, gd.NAME, gd.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " +
+ "FROM (SELECT d.ID AS DEVICE_ID, d.DESCRIPTION, d.NAME, d.DEVICE_IDENTIFICATION, " +
+ "d.DEVICE_TYPE_ID FROM DM_DEVICE d, DM_DEVICE_GROUP_MAP dgm WHERE dgm.GROUP_ID = ? " +
+ "AND d.ID = dgm.DEVICE_ID AND d.TENANT_ID = ?) gd, DM_DEVICE_TYPE t " +
+ "WHERE gd.DEVICE_TYPE_ID = t.ID) d1 WHERE d1.DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? " +
+ "LIMIT ?, ?";
+
+ stmt = conn.prepareStatement(sql);
+ stmt.setInt(1, groupId);
+ stmt.setInt(2, tenantId);
+ stmt.setInt(3, tenantId);
+ //noinspection JpaQueryApiInspection
+ stmt.setInt(4, request.getStartIndex());
+ //noinspection JpaQueryApiInspection
+ stmt.setInt(5, request.getRowCount());
+ rs = stmt.executeQuery();
+ devices = new ArrayList<>();
+ while (rs.next()) {
+ Device device = DeviceManagementDAOUtil.loadDevice(rs);
+ devices.add(device);
+ }
+ } catch (SQLException e) {
+ throw new GroupManagementDAOException("Error occurred while retrieving information of all " +
+ "registered devices", e);
+ } finally {
+ DeviceManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+ return devices;
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java
index fa3e52c4361..a48af760b53 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/group/mgt/dao/GroupManagementDAOUtil.java
@@ -82,9 +82,10 @@ public final class GroupManagementDAOUtil {
public static DeviceGroupBuilder loadGroup(ResultSet resultSet) throws SQLException {
DeviceGroupBuilder group = new DeviceGroupBuilder(new DeviceGroup());
+ group.setId(resultSet.getInt("ID"));
group.setDescription(resultSet.getString("DESCRIPTION"));
group.setName(resultSet.getString("GROUP_NAME"));
- group.setDateOfCreation(resultSet.getLong("DATE_OF_ENROLLMENT"));
+ group.setDateOfCreation(resultSet.getLong("DATE_OF_CREATE"));
group.setDateOfLastUpdate(resultSet.getLong("DATE_OF_LAST_UPDATE"));
group.setOwner(resultSet.getString("OWNER"));
return group;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
index 96d9e8d9735..129bd30c6e9 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
@@ -50,6 +50,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOF
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
+import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
+import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.util.DeviceManagementSchemaInitializer;
import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
@@ -181,6 +183,10 @@ public class DeviceManagementServiceComponent {
DeviceManagementDataHolder.getInstance().setDeviceManagementProvider(deviceManagementProvider);
bundleContext.registerService(DeviceManagementProviderService.class.getName(), deviceManagementProvider, null);
+ /* Registering Group Management Service */
+ GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl();
+ bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null);
+
/* Registering Tenant Configuration Management Service */
TenantConfigurationManagementService
tenantConfiguration = new TenantConfigurationManagementServiceImpl();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
similarity index 62%
rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
index 7d81ad7657b..b202917b6d2 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProvider.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
@@ -1,27 +1,26 @@
/*
- * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 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
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
+
package org.wso2.carbon.device.mgt.core.service;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
-import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
@@ -31,7 +30,7 @@ import java.util.List;
/**
* Interface for Group Management Services
*/
-public interface GroupManagementServiceProvider {
+public interface GroupManagementProviderService {
/**
* Add new device group and create default role with default permissions
@@ -56,19 +55,19 @@ public interface GroupManagementServiceProvider {
/**
* Delete existing device group
*
- * @param groupName of the group to delete
+ * @param groupId of the group to delete
* @throws GroupManagementException
*/
- boolean deleteGroup(String groupName) throws GroupManagementException;
+ boolean deleteGroup(int groupId) throws GroupManagementException;
/**
* Get device group specified by groupId
*
- * @param groupName of the group of the group
+ * @param groupId of the group of the group
* @return group
* @throws GroupManagementException
*/
- DeviceGroup getGroup(String groupName) throws GroupManagementException;
+ DeviceGroup getGroup(int groupId) throws GroupManagementException;
/**
* Get list of device groups matched with %groupName%
@@ -78,7 +77,23 @@ public interface GroupManagementServiceProvider {
* @return List of Groups that matches with the given DeviceGroup name.
* @throws GroupManagementException
*/
- List findGroups(String groupName, String username) throws GroupManagementException;
+ List findInGroups(String groupName, String username) throws GroupManagementException;
+
+ /**
+ * Get all device groups in tenant
+ *
+ * @return list of groups
+ * @throws GroupManagementException
+ */
+ List getGroups(PaginationRequest request) throws GroupManagementException;
+
+ /**
+ * Get all device group count in tenant
+ *
+ * @return group count
+ * @throws GroupManagementException
+ */
+ int getGroupCount() throws GroupManagementException;
/**
* Get device groups of user
@@ -102,134 +117,134 @@ public interface GroupManagementServiceProvider {
* Share device group with user specified by role
*
* @param username of the user
- * @param groupName of the group of the group
+ * @param groupId of the group of the group
* @param sharingRole to be shared
* @return is group shared
* @throws GroupManagementException
*/
- boolean shareGroup(String username, String groupName, String sharingRole)
+ boolean shareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException;
/**
* Un share existing group sharing with user specified by role
*
* @param userName of the user
- * @param groupName of the group of the group
+ * @param groupId of the group of the group
* @param sharingRole to be un shared
* @return is group un shared
* @throws GroupManagementException
*/
- boolean unshareGroup(String userName, String groupName, String sharingRole)
+ boolean unshareGroup(String userName, int groupId, String sharingRole)
throws GroupManagementException;
/**
* Add new sharing role for device group
*
* @param userName of the user
- * @param groupName of the group
+ * @param groupId of the group
* @param roleName to add
* @param permissions to bind with role
* @return is role added
* @throws GroupManagementException
*/
- boolean addGroupSharingRole(String userName, String groupName, String roleName, String[] permissions)
+ boolean addGroupSharingRole(String userName, int groupId, String roleName, String[] permissions)
throws GroupManagementException;
/**
* Remove existing sharing role for device group
*
- * @param groupName of the group
+ * @param groupId of the group
* @param roleName to remove
* @return is role removed
* @throws GroupManagementException
*/
- boolean removeGroupSharingRole(String groupName, String roleName) throws GroupManagementException;
+ boolean removeGroupSharingRole(int groupId, String roleName) throws GroupManagementException;
/**
* Get all sharing roles for device group
*
- * @param groupName of the group
+ * @param groupId of the group
* @return list of roles
* @throws GroupManagementException
*/
- List getRoles(String groupName) throws GroupManagementException;
+ List getRoles(int groupId) throws GroupManagementException;
/**
* Get specific device group sharing roles for user
*
* @param userName of the user
- * @param groupName of the group
+ * @param groupId of the group
* @return list of roles
* @throws GroupManagementException
*/
- List getRoles(String userName, String groupName) throws GroupManagementException;
+ List getRoles(String userName, int groupId) throws GroupManagementException;
/**
* Get device group users
*
- * @param groupName of the group
+ * @param groupId of the group
* @return list of group users
* @throws GroupManagementException
*/
- List getUsers(String groupName) throws GroupManagementException;
+ List getUsers(int groupId) throws GroupManagementException;
/**
* Get all devices in device group
*
- * @param groupName of the group
+ * @param groupId of the group
* @return list of group devices
* @throws GroupManagementException
*/
- List getDevices(String groupName) throws GroupManagementException;
+ List getDevices(int groupId) throws GroupManagementException;
/**
* Get all devices in device group
*
- * @param groupName of the group
+ * @param groupId of the group
* @param request PaginationRequest object holding the data for pagination
* @return list of group devices
* @throws GroupManagementException
*/
- PaginationResult getDevices(String groupName, PaginationRequest request) throws GroupManagementException;
+ List getDevices(int groupId, PaginationRequest request) throws GroupManagementException;
/**
* This method is used to retrieve the device count of a given group.
*
- * @param groupName Name of the group
+ * @param groupId Name of the group
* @return returns the device count.
* @throws GroupManagementException
*/
- int getDeviceCount(String groupName) throws GroupManagementException;
+ int getDeviceCount(int groupId) throws GroupManagementException;
/**
* Add device to device group
*
* @param deviceId of the device
- * @param groupName of the group
+ * @param groupId of the group
* @return is device added
* @throws GroupManagementException
*/
- boolean addDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException;
+ boolean addDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException;
/**
* Remove device from device group
*
* @param deviceId of the device
- * @param groupName of the group
+ * @param groupId of the group
* @return is device removed
* @throws GroupManagementException
*/
- boolean removeDevice(DeviceIdentifier deviceId, String groupName) throws GroupManagementException;
+ boolean removeDevice(DeviceIdentifier deviceId, int groupId) throws GroupManagementException;
/**
* Get device group permissions of user
*
* @param username of the user
- * @param groupName of the group
+ * @param groupId of the group
* @return array of permissions
* @throws GroupManagementException
*/
- String[] getPermissions(String username, String groupName) throws GroupManagementException;
+ String[] getPermissions(String username, int groupId) throws GroupManagementException;
/**
* Get device groups of user with permission
@@ -245,11 +260,11 @@ public interface GroupManagementServiceProvider {
* Check user is authorized for specific permission of device group
*
* @param username of the user
- * @param groupName to authorize
+ * @param groupId to authorize
* @param permission to authorize
* @return is user authorized for permission
* @throws GroupManagementException
*/
- boolean isAuthorized(String username, String groupName, String permission) throws GroupManagementException;
+ boolean isAuthorized(String username, int groupId, String permission) throws GroupManagementException;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
similarity index 63%
rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
index 2923ee944a8..02788d78ace 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementServiceProviderImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
@@ -1,28 +1,32 @@
/*
- * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * 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
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
*
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
*/
+
package org.wso2.carbon.device.mgt.core.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
-import org.wso2.carbon.device.mgt.common.*;
+import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
@@ -38,18 +42,21 @@ import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.util.UserCoreUtil;
import java.sql.SQLException;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
-public class GroupManagementServiceProviderImpl implements GroupManagementServiceProvider {
+public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
- private static Log log = LogFactory.getLog(GroupManagementServiceProviderImpl.class);
+ private static Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
private GroupDAO groupDAO;
/**
* Set groupDAO from GroupManagementDAOFactory when class instantiate.
*/
- public GroupManagementServiceProviderImpl() {
+ public GroupManagementProviderServiceImpl() {
this.groupDAO = GroupManagementDAOFactory.getGroupDAO();
}
@@ -71,6 +78,10 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
if (!nameIsExists) {
groupId = this.groupDAO.addGroup(groupBroker, tenantId);
GroupManagementDAOFactory.commitTransaction();
+ if (groupId < 0) {
+ return -1;
+ }
+ groupBroker.setId(groupId);
} else {
return -2;
}
@@ -83,10 +94,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} finally {
GroupManagementDAOFactory.closeConnection();
}
- if (groupId == -1) {
- return -1;
- }
- addGroupSharingRole(groupBroker.getOwner(), deviceGroup.getName(), defaultRole, defaultPermissions);
+
+ addGroupSharingRole(groupBroker.getOwner(), groupId, defaultRole, defaultPermissions);
if (log.isDebugEnabled()) {
log.debug("DeviceGroup added: " + groupBroker.getName());
}
@@ -120,30 +129,22 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean deleteGroup(String groupName) throws GroupManagementException {
+ public boolean deleteGroup(int groupId) throws GroupManagementException {
String roleName;
- DeviceGroup deviceGroup = getGroup(groupName);
+ DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
return false;
}
- List groupRoles = getRoles(groupName);
+ List groupRoles = getRoles(groupId);
for (String role : groupRoles) {
if (role != null) {
- roleName = role.replace("Internal/group-" + groupName + "-", "");
- removeGroupSharingRole(groupName, roleName);
+ roleName = role.replace("Internal/group-" + groupId + "-", "");
+ removeGroupSharingRole(groupId, roleName);
}
}
- List groupDevices = getDevices(groupName);
- try {
- for (Device device : groupDevices) {
- DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device);
- }
- } catch (DeviceManagementException e) {
- throw new GroupManagementException("Error occurred while removing device from group.", e);
- }
try {
GroupManagementDAOFactory.beginTransaction();
- this.groupDAO.deleteGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId());
+ this.groupDAO.deleteGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
GroupManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("DeviceGroup " + deviceGroup.getName() + " removed.");
@@ -152,7 +153,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
} catch (GroupManagementDAOException e) {
GroupManagementDAOFactory.rollbackTransaction();
throw new GroupManagementException("Error occurred while removing group " +
- "'" + groupName + "' data.", e);
+ "'" + groupId + "' data.", e);
} catch (TransactionManagementException e) {
throw new GroupManagementException("Error occurred while initiating transaction.", e);
} finally {
@@ -164,21 +165,21 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public DeviceGroup getGroup(String groupName) throws GroupManagementException {
+ public DeviceGroup getGroup(int groupId) throws GroupManagementException {
DeviceGroupBuilder groupBroker;
try {
GroupManagementDAOFactory.openConnection();
- groupBroker = this.groupDAO.getGroup(groupName, CarbonContext.getThreadLocalCarbonContext().getTenantId());
+ groupBroker = this.groupDAO.getGroup(groupId, CarbonContext.getThreadLocalCarbonContext().getTenantId());
} catch (GroupManagementDAOException e) {
- throw new GroupManagementException("Error occurred while obtaining group " + groupName, e);
+ throw new GroupManagementException("Error occurred while obtaining group " + groupId, e);
} catch (SQLException e) {
throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
if (groupBroker != null) {
- groupBroker.setUsers(this.getUsers(groupName));
- groupBroker.setRoles(this.getRoles(groupName));
+ groupBroker.setUsers(this.getUsers(groupId));
+ groupBroker.setRoles(this.getRoles(groupId));
return groupBroker.getGroup();
} else {
return null;
@@ -189,12 +190,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public List findGroups(String groupName, String owner) throws GroupManagementException {
+ public List findInGroups(String groupName, String owner) throws GroupManagementException {
List deviceGroups = new ArrayList<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
GroupManagementDAOFactory.openConnection();
- deviceGroups = this.groupDAO.getGroups(groupName, tenantId);
+ deviceGroups = this.groupDAO.findInGroups(groupName, tenantId);
} catch (GroupManagementDAOException e) {
throw new GroupManagementException("Error occurred while finding group " + groupName, e);
} catch (SQLException e) {
@@ -204,13 +205,53 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
}
List groupsWithData = new ArrayList<>();
for (DeviceGroupBuilder groupBroker : deviceGroups) {
- groupBroker.setUsers(this.getUsers(groupBroker.getName()));
- groupBroker.setRoles(this.getRoles(groupBroker.getName()));
+ groupBroker.setUsers(this.getUsers(groupBroker.getId()));
+ groupBroker.setRoles(this.getRoles(groupBroker.getId()));
groupsWithData.add(groupBroker.getGroup());
}
return groupsWithData;
}
+ @Override
+ public List getGroups(PaginationRequest request) throws GroupManagementException {
+ List deviceGroups = new ArrayList<>();
+ try {
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ GroupManagementDAOFactory.openConnection();
+ deviceGroups = this.groupDAO.getGroups(request, tenantId);
+ } catch (GroupManagementDAOException e) {
+ throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ List groupsWithData = new ArrayList<>();
+ for (DeviceGroupBuilder groupBroker : deviceGroups) {
+ groupBroker.setUsers(this.getUsers(groupBroker.getId()));
+ groupBroker.setRoles(this.getRoles(groupBroker.getId()));
+ groupsWithData.add(groupBroker.getGroup());
+ }
+ return groupsWithData;
+ }
+
+ @Override
+ public int getGroupCount() throws GroupManagementException {
+ try {
+ int count;
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ GroupManagementDAOFactory.openConnection();
+ count = groupDAO.getGroupCount(tenantId);
+ return count;
+ } catch (GroupManagementDAOException e) {
+ throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
+
/**
* {@inheritDoc}
*/
@@ -222,13 +263,12 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username);
- Map groups = new HashMap<>();
+ Map groups = new HashMap<>();
for (String role : roleList) {
if (role != null && role.contains("Internal/group-")) {
- String groupName = role.split("-")[1];
- if (!groups.containsKey(groupName)) {
- DeviceGroup deviceGroup = getGroup(groupName);
- groups.put(groupName, deviceGroup);
+ DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role);
+ if (deviceGroup != null) {
+ groups.put(deviceGroup.getId(), deviceGroup);
}
}
}
@@ -250,66 +290,39 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean shareGroup(String username, String groupName, String sharingRole)
+ public boolean shareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException {
- return modifyGroupShare(username, groupName, sharingRole, true);
+ return modifyGroupShare(username, groupId, sharingRole, true);
}
/**
* {@inheritDoc}
*/
@Override
- public boolean unshareGroup(String username, String groupName, String sharingRole)
+ public boolean unshareGroup(String username, int groupId, String sharingRole)
throws GroupManagementException {
- return modifyGroupShare(username, groupName, sharingRole, false);
- }
-
- private boolean modifyGroupShare(String username, String groupName, String sharingRole,
- boolean isAddNew)
- throws GroupManagementException {
- UserStoreManager userStoreManager;
- String[] roles = new String[1];
- try {
- DeviceGroup deviceGroup = getGroup(groupName);
- if (deviceGroup == null) {
- return false;
- }
- int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- userStoreManager =
- DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
- tenantId).getUserStoreManager();
- roles[0] = "Internal/group-" + groupName + "-" + sharingRole;
- if (isAddNew) {
- userStoreManager.updateRoleListOfUser(username, null, roles);
- } else {
- userStoreManager.updateRoleListOfUser(username, roles, null);
- }
- return true;
- } catch (UserStoreException e) {
- throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
- groupName, e);
- }
+ return modifyGroupShare(username, groupId, sharingRole, false);
}
/**
* {@inheritDoc}
*/
@Override
- public boolean addGroupSharingRole(String username, String groupName, String roleName,
+ public boolean addGroupSharingRole(String username, int groupId, String roleName,
String[] permissions)
throws GroupManagementException {
UserStoreManager userStoreManager;
String role;
String[] userNames = new String[1];
try {
- DeviceGroup deviceGroup = getGroup(groupName);
+ DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
- role = "Internal/group-" + groupName + "-" + roleName;
+ role = "Internal/group-" + groupId + "-" + roleName;
userNames[0] = username;
Permission[] carbonPermissions = new Permission[permissions.length];
for (int i = 0; i < permissions.length; i++) {
@@ -318,8 +331,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
userStoreManager.addRole(role, userNames, carbonPermissions);
return true;
} catch (UserStoreException e) {
- String errorMsg = "User store error in adding role to group id:" + groupName;
- log.error(errorMsg, e);
+ String errorMsg = "User store error in adding role to group id:" + groupId;
throw new GroupManagementException(errorMsg, e);
}
}
@@ -328,23 +340,23 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean removeGroupSharingRole(String groupName, String roleName)
+ public boolean removeGroupSharingRole(int groupId, String roleName)
throws GroupManagementException {
UserStoreManager userStoreManager;
String role;
try {
- DeviceGroup deviceGroup = getGroup(groupName);
+ DeviceGroup deviceGroup = getGroup(groupId);
if (deviceGroup == null) {
return false;
}
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
- role = "Internal/group-" + groupName + "-" + roleName;
+ role = "Internal/group-" + groupId + "-" + roleName;
userStoreManager.deleteRole(role);
return true;
} catch (UserStoreException userStoreEx) {
- String errorMsg = "User store error in adding role to group id:" + groupName;
+ String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx);
}
@@ -354,7 +366,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public List getRoles(String groupName) throws GroupManagementException {
+ public List getRoles(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
String[] roles;
List groupRoles;
@@ -365,13 +377,13 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
roles = userStoreManager.getRoleNames();
groupRoles = new ArrayList<>();
for (String r : roles) {
- if (r != null && r.contains("Internal/group-" + groupName + "-")) {
- groupRoles.add(r.replace("Internal/group-" + groupName + "-", ""));
+ if (r != null && r.contains("Internal/group-" + groupId + "-")) {
+ groupRoles.add(r.replace("Internal/group-" + groupId + "-", ""));
}
}
return groupRoles;
} catch (UserStoreException userStoreEx) {
- String errorMsg = "User store error in adding role to group id:" + groupName;
+ String errorMsg = "User store error in adding role to group id:" + groupId;
log.error(errorMsg, userStoreEx);
throw new GroupManagementException(errorMsg, userStoreEx);
}
@@ -381,7 +393,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public List getRoles(String username, String groupName) throws GroupManagementException {
+ public List getRoles(String username, int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
List groupRoleList = new ArrayList<>();
try {
@@ -390,8 +402,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
.getUserStoreManager();
String[] roleList = userStoreManager.getRoleListOfUser(username);
for (String role : roleList) {
- if (role != null && role.contains("Internal/group-" + groupName)) {
- String roleName = role.replace("Internal/group-" + groupName + "-", "");
+ if (role != null && role.contains("Internal/group-" + groupId)) {
+ String roleName = role.replace("Internal/group-" + groupId + "-", "");
groupRoleList.add(roleName);
}
}
@@ -405,16 +417,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public List getUsers(String groupName) throws GroupManagementException {
+ public List getUsers(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
Map groupUserHashMap = new HashMap<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
- List rolesForGroup = this.getRoles(groupName);
+ List rolesForGroup = this.getRoles(groupId);
for (String role : rolesForGroup) {
- String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupName + "-" + role);
+ String[] users = userStoreManager.getUserListOfRole("Internal/group-" + groupId + "-" + role);
for (String user : users) {
GroupUser groupUser;
if (groupUserHashMap.containsKey(user)) {
@@ -431,7 +443,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
}
return new ArrayList<>(groupUserHashMap.values());
} catch (UserStoreException e) {
- String errorMsg = "User store error in fetching user list for group id:" + groupName;
+ String errorMsg = "User store error in fetching user list for group id:" + groupId;
log.error(errorMsg, e);
throw new GroupManagementException(errorMsg, e);
}
@@ -441,55 +453,54 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public List getDevices(String groupName) throws GroupManagementException {
- return Collections.emptyList();
- //TODO: Add a method that returns a collection of devices in a particular group to GroupDAO
-// try {
-// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName);
-// } catch (DeviceManagementException e) {
-// throw new GroupManagementException("Error occurred while getting devices in group.", e);
-// }
+ public List getDevices(int groupId) throws GroupManagementException {
+ try {
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ GroupManagementDAOFactory.getConnection();
+ return this.groupDAO.getDevices(groupId, tenantId);
+ } catch (GroupManagementDAOException e) {
+ throw new GroupManagementException("Error occurred while getting devices in group.", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
}
/**
* {@inheritDoc}
*/
@Override
- public PaginationResult getDevices(String groupName, PaginationRequest request)
+ public List getDevices(int groupId, PaginationRequest request)
throws GroupManagementException {
- return null;
- //TODO: Add a method that returns a collection of devices in a particular group to GroupDAO
-// try {
-// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName);
-// } catch (DeviceManagementException e) {
-// throw new GroupManagementException("Error occurred while getting devices in group.", e);
-// }
-// try {
-// return DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevices(groupName,
-// request);
-// } catch (DeviceManagementException e) {
-// throw new GroupManagementException("Error occurred while getting devices in group.", e);
-// }
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ try {
+ GroupManagementDAOFactory.getConnection();
+ return this.groupDAO.getDevices(groupId, request, tenantId);
+ } catch (GroupManagementDAOException e) {
+ throw new GroupManagementException("Error occurred while getting devices in group.", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
}
/**
* {@inheritDoc}
*/
@Override
- public int getDeviceCount(String groupName) throws GroupManagementException {
+ public int getDeviceCount(int groupId) throws GroupManagementException {
try {
int count;
- GroupManagementDAOFactory.beginTransaction();
- count = groupDAO.getDeviceCount(groupName,
- CarbonContext.getThreadLocalCarbonContext().getTenantId());
- GroupManagementDAOFactory.commitTransaction();
+ GroupManagementDAOFactory.getConnection();
+ count = groupDAO.getDeviceCount(groupId,
+ CarbonContext.getThreadLocalCarbonContext().getTenantId());
return count;
} catch (GroupManagementDAOException e) {
- GroupManagementDAOFactory.rollbackTransaction();
- throw new GroupManagementException("Error occurred while retrieving device count of group " +
- "'" + groupName + "'.", e);
- } catch (TransactionManagementException e) {
- throw new GroupManagementException("Error occurred while initiating transaction.", e);
+ throw new GroupManagementException("Error occurred while retrieving all groups in tenant", e);
+ } catch (SQLException e) {
+ throw new GroupManagementException("Error occurred while opening a connection to the data source.", e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
@@ -499,19 +510,29 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean addDevice(DeviceIdentifier deviceId, String groupName)
+ public boolean addDevice(DeviceIdentifier deviceIdentifier, int groupId)
throws GroupManagementException {
Device device;
DeviceGroup deviceGroup;
try {
- device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId);
- deviceGroup = this.getGroup(groupName);
+ device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
+ deviceGroup = this.getGroup(groupId);
if (device == null || deviceGroup == null) {
return false;
}
- DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device);
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ GroupManagementDAOFactory.beginTransaction();
+ this.groupDAO.addDevice(groupId, device.getId(), tenantId);
+ GroupManagementDAOFactory.commitTransaction();
} catch (DeviceManagementException e) {
- throw new GroupManagementException("Error occurred while adding device in to deviceGroup.", e);
+ throw new GroupManagementException("Error occurred while retrieving device.", e);
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e);
+ } catch (TransactionManagementException e) {
+ throw new GroupManagementException("Error occurred while initiating transaction.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
}
return true;
}
@@ -520,19 +541,29 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean removeDevice(DeviceIdentifier deviceId, String groupName)
+ public boolean removeDevice(DeviceIdentifier deviceIdentifier, int groupId)
throws GroupManagementException {
Device device;
DeviceGroup deviceGroup;
try {
- device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceId);
- deviceGroup = this.getGroup(groupName);
+ device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().getDevice(deviceIdentifier);
+ deviceGroup = this.getGroup(groupId);
if (device == null || deviceGroup == null) {
return false;
}
- DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device);
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ GroupManagementDAOFactory.beginTransaction();
+ this.groupDAO.removeDevice(groupId, device.getId(), tenantId);
+ GroupManagementDAOFactory.commitTransaction();
} catch (DeviceManagementException e) {
- throw new GroupManagementException("Error occurred while removing device from deviceGroup.", e);
+ throw new GroupManagementException("Error occurred while retrieving device.", e);
+ } catch (TransactionManagementException e) {
+ throw new GroupManagementException("Error occurred while initiating transaction.", e);
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ throw new GroupManagementException("Error occurred while adding device to group '" + groupId + "'.", e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
}
return true;
}
@@ -541,9 +572,9 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public String[] getPermissions(String username, String groupName) throws GroupManagementException {
+ public String[] getPermissions(String username, int groupId) throws GroupManagementException {
UserRealm userRealm;
- List roles = getRoles(username, groupName);
+ List roles = getRoles(username, groupId);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
@@ -553,8 +584,8 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
for (String resourceId : resourceIds) {
for (String roleName : roles) {
if (userRealm.getAuthorizationManager().
- isRoleAuthorized("Internal/group-" + groupName + "-" + roleName, resourceId,
- CarbonConstants.UI_PERMISSION_ACTION)) {
+ isRoleAuthorized("Internal/group-" + groupId + "-" + roleName, resourceId,
+ CarbonConstants.UI_PERMISSION_ACTION)) {
lstPermissions.add(resourceId);
}
}
@@ -575,17 +606,16 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
throws GroupManagementException {
UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- Map groups = new HashMap<>();
+ Map groups = new HashMap<>();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
String[] roles = userRealm.getUserStoreManager().getRoleListOfUser(username);
for (String role : roles) {
if (role != null && role.contains("Internal/group-") && userRealm.getAuthorizationManager()
.isRoleAuthorized(role, permission, CarbonConstants.UI_PERMISSION_ACTION)) {
- String groupName = role.split("-")[1];
- if (!groups.containsKey(groupName)) {
- DeviceGroup deviceGroup = getGroup(groupName);
- groups.put(groupName, deviceGroup);
+ DeviceGroup deviceGroup = extractNewGroupFromRole(groups, role);
+ if (deviceGroup != null) {
+ groups.put(deviceGroup.getId(), deviceGroup);
}
}
}
@@ -599,17 +629,17 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
* {@inheritDoc}
*/
@Override
- public boolean isAuthorized(String username, String groupName, String permission)
+ public boolean isAuthorized(String username, int groupId, String permission)
throws GroupManagementException {
UserRealm userRealm;
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
- List roles = this.getRoles(username, groupName);
+ List roles = this.getRoles(username, groupId);
for (String role : roles) {
if (userRealm.getAuthorizationManager()
- .isRoleAuthorized("Internal/group-" + groupName + "-" + role, permission,
- CarbonConstants.UI_PERMISSION_ACTION)) {
+ .isRoleAuthorized("Internal/group-" + groupId + "-" + role, permission,
+ CarbonConstants.UI_PERMISSION_ACTION)) {
return true;
}
}
@@ -619,4 +649,44 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
}
}
+ private boolean modifyGroupShare(String username, int groupId, String sharingRole,
+ boolean isAddNew)
+ throws GroupManagementException {
+ UserStoreManager userStoreManager;
+ String[] roles = new String[1];
+ try {
+ DeviceGroup deviceGroup = getGroup(groupId);
+ if (deviceGroup == null) {
+ return false;
+ }
+ int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+ userStoreManager =
+ DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
+ tenantId).getUserStoreManager();
+ roles[0] = "Internal/group-" + groupId + "-" + sharingRole;
+ if (isAddNew) {
+ userStoreManager.updateRoleListOfUser(username, null, roles);
+ } else {
+ userStoreManager.updateRoleListOfUser(username, roles, null);
+ }
+ return true;
+ } catch (UserStoreException e) {
+ throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
+ groupId, e);
+ }
+ }
+
+ private DeviceGroup extractNewGroupFromRole(Map groups, String role)
+ throws GroupManagementException {
+ try {
+ int groupId = Integer.parseInt(role.split("-")[1]);
+ if (!groups.containsKey(groupId)) {
+ return getGroup(groupId);
+ }
+ } catch (NumberFormatException e) {
+ log.error("Unable to extract groupId from role " + role, e);
+ }
+ return null;
+ }
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
index a270659ca3b..5405338116c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/BaseDeviceManagementTest.java
@@ -31,6 +31,7 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.TestUtils;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import javax.sql.DataSource;
@@ -58,6 +59,7 @@ public abstract class BaseDeviceManagementTest {
public void initDataSource() throws Exception {
this.dataSource = this.getDataSource(this.readDataSourceConfig());
DeviceManagementDAOFactory.init(dataSource);
+ GroupManagementDAOFactory.init(dataSource);
}
@BeforeClass
@@ -135,6 +137,7 @@ public abstract class BaseDeviceManagementTest {
// this.cleanApplicationData(conn);
// this.cleanupDeviceData(conn);
// this.cleanupDeviceTypeData(conn);
+ this.cleanupGroupData(conn);
conn.commit();
} catch (SQLException e) {
@@ -190,6 +193,12 @@ public abstract class BaseDeviceManagementTest {
}
}
+ private void cleanupGroupData(Connection conn) throws SQLException {
+ try (PreparedStatement stmt = conn.prepareStatement("DELETE FROM DM_GROUP")) {
+ stmt.execute();
+ }
+ }
+
public DataSource getDataSource() {
return dataSource;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java
index 1d381abf1ed..423fc6666ef 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/common/TestDataHolder.java
@@ -18,7 +18,9 @@ package org.wso2.carbon.device.mgt.core.common;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
+import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
import java.util.Date;
import java.util.Properties;
@@ -30,6 +32,7 @@ public class TestDataHolder {
public static String TEST_DEVICE_TYPE = "Test";
public static Integer SUPER_TENANT_ID = -1234;
public static String initialDeviceIdentifier = "12345";
+ public static String OWNER = "admin";
public static Device generateDummyDeviceData(String deviceType){
@@ -37,12 +40,12 @@ public class TestDataHolder {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
- enrolmentInfo.setOwner("admin");
+ enrolmentInfo.setOwner(OWNER);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
enrolmentInfo.setStatus(EnrolmentInfo.Status.CREATED);
device.setEnrolmentInfo(enrolmentInfo);
device.setDescription("Test Description");
- device.setDeviceIdentifier("12345");
+ device.setDeviceIdentifier(initialDeviceIdentifier);
device.setType(deviceType);
return device;
}
@@ -70,4 +73,15 @@ public class TestDataHolder {
return application;
}
+
+ public static DeviceGroup generateDummyGroupData() {
+ DeviceGroup deviceGroup = new DeviceGroup();
+ deviceGroup.setName("Test device group");
+ deviceGroup.setDescription("Test description");
+ deviceGroup.setDateOfCreation(new Date().getTime());
+ deviceGroup.setDateOfLastUpdate(new Date().getTime());
+ deviceGroup.setOwner(OWNER);
+ DeviceGroupBuilder broker = new DeviceGroupBuilder(deviceGroup);
+ return broker.getGroup();
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java
new file mode 100644
index 00000000000..29bfa22a5da
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/GroupPersistTests.java
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.dao;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.testng.Assert;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.Test;
+import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.core.common.BaseDeviceManagementTest;
+import org.wso2.carbon.device.mgt.core.common.TestDataHolder;
+import org.wso2.carbon.device.mgt.core.group.mgt.DeviceGroupBuilder;
+import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupDAO;
+import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOException;
+import org.wso2.carbon.device.mgt.core.group.mgt.dao.GroupManagementDAOFactory;
+
+import java.sql.SQLException;
+import java.util.Date;
+import java.util.List;
+
+public class GroupPersistTests extends BaseDeviceManagementTest {
+
+ private static final Log log = LogFactory.getLog(GroupPersistTests.class);
+ int groupId = -1;
+ private GroupDAO groupDAO;
+
+ @BeforeClass
+ @Override
+ public void init() throws Exception {
+ initDataSource();
+ groupDAO = GroupManagementDAOFactory.getGroupDAO();
+ }
+
+ @Test
+ public void testAddGroupTest() {
+ DeviceGroup deviceGroup = TestDataHolder.generateDummyGroupData();
+ try {
+ GroupManagementDAOFactory.beginTransaction();
+ groupId = groupDAO.addGroup(deviceGroup, TestDataHolder.SUPER_TENANT_ID);
+ GroupManagementDAOFactory.commitTransaction();
+ log.debug("Group added to database.");
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while adding device type '" + deviceGroup.getName() + "'.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+
+ DeviceGroup group = getGroupById(groupId);
+ Assert.assertNotNull(group, "Group is null");
+ log.debug("Group name: " + group.getName());
+ }
+
+ public DeviceGroup getGroupById(int groupId) {
+ try {
+ GroupManagementDAOFactory.openConnection();
+ return groupDAO.getGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
+ } catch (GroupManagementDAOException e) {
+ String msg = "Error occurred while retrieving group details.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ return null;
+ }
+
+ @Test(dependsOnMethods = {"testAddGroupTest"})
+ public void updateGroupTest() {
+ long time = new Date().getTime();
+ String name = "Test Updated";
+ String desc = "Desc updated";
+ DeviceGroup group = getGroupById(groupId);
+ Assert.assertNotNull(group, "Group is null");
+ group.setDateOfLastUpdate(time);
+ group.setName(name);
+ group.setDescription(desc);
+ try {
+ GroupManagementDAOFactory.beginTransaction();
+ groupDAO.updateGroup(group, TestDataHolder.SUPER_TENANT_ID);
+ GroupManagementDAOFactory.commitTransaction();
+ log.debug("Group updated");
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while updating group details.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+
+ group = getGroupById(group.getId());
+ Assert.assertNotNull(group, "Group is null");
+ Assert.assertEquals(group.getName(), name, "Group name");
+ Assert.assertEquals(group.getDescription(), desc, "Group description");
+ Assert.assertEquals((long) group.getDateOfLastUpdate(), time, "Update time");
+ }
+
+ @Test(dependsOnMethods = {"testAddGroupTest"})
+ public void findGroupTest() {
+ try {
+ GroupManagementDAOFactory.openConnection();
+ List groups = groupDAO.findInGroups("Test", TestDataHolder.SUPER_TENANT_ID);
+ Assert.assertNotEquals(groups.size(), 0, "No groups found");
+ Assert.assertNotNull(groups.get(0), "Group is null");
+ log.debug("Group found: " + groups.get(0).getName());
+ } catch (GroupManagementDAOException e) {
+ String msg = "Error occurred while find group by name.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
+
+ @Test(dependsOnMethods = {"testAddGroupTest"})
+ public void getGroupTest() {
+ try {
+ GroupManagementDAOFactory.openConnection();
+ PaginationRequest paginationRequest = new PaginationRequest(0, 1000);
+ List groups = groupDAO.getGroups(paginationRequest, TestDataHolder.SUPER_TENANT_ID);
+ Assert.assertNotEquals(groups.size(), 0, "No groups found");
+ Assert.assertNotNull(groups.get(0), "Group is null");
+ log.debug("No of Groups found: " + groups.size());
+ } catch (GroupManagementDAOException e) {
+ String msg = "Error occurred while find group by name.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
+
+ @Test(dependsOnMethods = {"updateGroupTest"})
+ public void addDeviceToGroupTest() {
+ Device initialTestDevice = TestDataHolder.initialTestDevice;
+ try {
+ GroupManagementDAOFactory.beginTransaction();
+ groupDAO.addDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
+ GroupManagementDAOFactory.commitTransaction();
+ log.debug("Device added to group.");
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+
+ try {
+ GroupManagementDAOFactory.openConnection();
+ List groupedDevices = groupDAO.getDevices(groupId, TestDataHolder.SUPER_TENANT_ID);
+ Assert.assertNotEquals(groupedDevices.size(), 0, "No device found");
+ Assert.assertNotNull(groupedDevices.get(0), "Device is null");
+ Assert.assertEquals(groupedDevices.get(0).getId(), initialTestDevice.getId(), "Device ids not matched");
+ } catch (GroupManagementDAOException e) {
+ String msg = "Error occurred while retrieving group details.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
+
+ @Test(dependsOnMethods = {"addDeviceToGroupTest"})
+ public void removeDeviceFromGroupTest() {
+ Device initialTestDevice = TestDataHolder.initialTestDevice;
+ try {
+ GroupManagementDAOFactory.beginTransaction();
+ groupDAO.removeDevice(groupId, initialTestDevice.getId(), TestDataHolder.SUPER_TENANT_ID);
+ GroupManagementDAOFactory.commitTransaction();
+ log.debug("Group added to database.");
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while adding device '" + initialTestDevice.getName() + "'.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ }
+
+ @Test(dependsOnMethods = {"removeDeviceFromGroupTest"})
+ public void deleteGroupTest() {
+ DeviceGroup group = getGroupById(groupId);
+ int groupId = 0;
+ try {
+ Assert.assertNotNull(group, "Group is null");
+ groupId = group.getId();
+ GroupManagementDAOFactory.beginTransaction();
+ groupDAO.deleteGroup(groupId, TestDataHolder.SUPER_TENANT_ID);
+ GroupManagementDAOFactory.commitTransaction();
+ log.debug("Group deleted");
+ } catch (GroupManagementDAOException e) {
+ GroupManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while updating group details.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while initiating transaction.";
+ log.error(msg, e);
+ Assert.fail(msg, e);
+ } finally {
+ GroupManagementDAOFactory.closeConnection();
+ }
+ group = getGroupById(groupId);
+ Assert.assertNull(group, "Group not deleted");
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties
index dc3d465fc0c..e415fd607d3 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/log4j.properties
@@ -1,29 +1,31 @@
#
-# Copyright 2009 WSO2, Inc. (http://wso2.com)
+# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
+# WSO2 Inc. licenses this file to you under the Apache License,
+# Version 2.0 (the "License"); you may not use this file except
+# in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
#
#
# This is the log4j configuration file used by WSO2 Carbon
#
# IMPORTANT : Please do not remove or change the names of any
-# of the Appenders defined here. The layout pattern & log file
+# of the Appender defined here. The layout pattern & log file
# can be changed using the WSO2 Carbon Management Console, and those
# settings will override the settings in this file.
#
-log4j.rootLogger=INFO, STD_OUT
+log4j.rootLogger=DEBUG, STD_OUT
# Redirect log messages to console
log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
index 09a41be82f8..ebacfbfd905 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
@@ -4,6 +4,17 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
PRIMARY KEY (ID)
);
+CREATE TABLE IF NOT EXISTS DM_GROUP (
+ ID INTEGER AUTO_INCREMENT NOT NULL,
+ GROUP_NAME VARCHAR(100) DEFAULT NULL,
+ DESCRIPTION TEXT DEFAULT NULL,
+ DATE_OF_CREATE BIGINT DEFAULT NULL,
+ DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
+ OWNER VARCHAR(45) DEFAULT NULL,
+ TENANT_ID INTEGER DEFAULT 0,
+ PRIMARY KEY (ID)
+);
+
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
ID INTEGER auto_increment NOT NULL,
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
@@ -23,6 +34,18 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE (
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
);
+CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP (
+ ID INTEGER AUTO_INCREMENT NOT NULL,
+ DEVICE_ID INTEGER DEFAULT NULL,
+ GROUP_ID INTEGER DEFAULT NULL,
+ TENANT_ID INTEGER DEFAULT 0,
+ PRIMARY KEY (ID),
+ CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
+ REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
+ CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
+ REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
+);
+
CREATE TABLE IF NOT EXISTS DM_OPERATION (
ID INTEGER AUTO_INCREMENT NOT NULL,
TYPE VARCHAR(50) NOT NULL,
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
index 5195f7e39cf..d050c5ada7e 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/testng.xml
@@ -33,7 +33,8 @@
-
+
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
index 3a891675255..2eb681d9460 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
@@ -1,4 +1,22 @@
+
+
@@ -40,6 +58,38 @@
org.wso2.carbon
org.wso2.carbon.utils
+
+ org.wso2.orbit.org.scannotation
+ scannotation
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi.services
+
+
+ org.wso2.tomcat
+ tomcat
+
+
+ org.wso2.tomcat
+ tomcat-servlet-api
+
+
+ javax.ws.rs
+ jsr311-api
+
+
+ org.apache.axis2.wso2
+ axis2
+
+
+ commons-lang.wso2
+ commons-lang
+
@@ -59,7 +109,7 @@
org.wso2.carbon.governance.api.*,
- javax.xml.namespace,
+ javax.xml.namespace;resolution:=optional,
org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.common.license.mgt,
@@ -69,7 +119,14 @@
org.wso2.carbon.registry.core.session,
javax.xml.bind,
org.wso2.carbon.utils,
- org.apache.commons.logging
+ org.apache.commons.logging,
+ org.apache.catalina,
+ org.apache.catalina.core,
+ javax.servlet;resolution:=optional,
+ javax.xml.*;resolution:=optional,
+ org.apache.commons.lang,
+ javax.ws.rs;resolution:=optional,
+ org.scannotation
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java
new file mode 100644
index 00000000000..2da33945424
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/GenericFeatureManager.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.extensions.feature.mgt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.Feature;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * This stores the features for device types that are mentioned through the annotations.
+ */
+public class GenericFeatureManager {
+
+ private static final Log log = LogFactory.getLog(GenericFeatureManager.class);
+ private static Map> featureSet = new HashMap<>();
+ private static GenericFeatureManager instance = new GenericFeatureManager();
+
+ private GenericFeatureManager() {
+ }
+
+ public static GenericFeatureManager getInstance() {
+ return instance;
+ }
+
+ /**
+ * @param deviceTypeFeatures feature list for each device type.
+ */
+ public void addFeatures(Map> deviceTypeFeatures) {
+ this.featureSet.putAll(deviceTypeFeatures);
+ }
+
+ /**
+ * @param deviceType
+ * @param featureName
+ * @return the extracted feature for the which matches the feature name and device type.
+ */
+ public Feature getFeature(String deviceType, String featureName) {
+ Feature extractedFeature = null;
+ List deviceFeatureList = featureSet.get(deviceType);
+ for (Feature feature : deviceFeatureList) {
+ if (feature.getName().equalsIgnoreCase(featureName)) {
+ extractedFeature = feature;
+ }
+ }
+ return extractedFeature;
+ }
+
+ /**
+ * @param deviceType returns the features for the device type.
+ * @return
+ */
+ public List getFeatures(String deviceType) {
+ return featureSet.get(deviceType);
+ }
+
+}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java
new file mode 100644
index 00000000000..7c7d6358897
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/DeviceType.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface DeviceType {
+ String value();
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java
new file mode 100644
index 00000000000..da0040f9820
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/annotations/Feature.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Feature {
+
+ String code();
+
+ String name();
+
+ String description();
+
+ String type();
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java
new file mode 100644
index 00000000000..57ae592ee65
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/lifecycle/listener/FeatureManagementLifecycleListener.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.extensions.feature.mgt.lifecycle.listener;
+
+import org.apache.catalina.Lifecycle;
+import org.apache.catalina.LifecycleEvent;
+import org.apache.catalina.LifecycleListener;
+import org.apache.catalina.core.StandardContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.Feature;
+import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
+import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
+import org.wso2.carbon.device.mgt.extensions.feature.mgt.util.AnnotationUtil;
+
+import javax.servlet.ServletContext;
+import java.io.IOException;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+@SuppressWarnings("unused")
+public class FeatureManagementLifecycleListener implements LifecycleListener {
+
+ private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
+
+ private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
+
+ private static final Log log = LogFactory.getLog(FeatureManagementLifecycleListener.class);
+ private static final String UNLIMITED = "Unlimited";
+
+ @Override
+ public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
+ if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
+ StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
+ ServletContext servletContext = context.getServletContext();
+ String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
+ boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
+ if (isManagedApi) {
+ try {
+ AnnotationUtil annotationUtil = new AnnotationUtil(context);
+ Set annotatedAPIClasses = annotationUtil.scanStandardContext(DeviceType.class.getName());
+ Map> features = annotationUtil.extractFeatures(annotatedAPIClasses);
+ if (features != null && !features.isEmpty()) {
+ GenericFeatureManager.getInstance().addFeatures(features);
+ }
+ } catch (IOException e) {
+ log.error("Error enconterd while discovering annotated classes.", e);
+ } catch (ClassNotFoundException e) {
+ log.error("Error while scanning class for annotations.", e);
+ }
+ }
+ }
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java
new file mode 100644
index 00000000000..621de443721
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/src/main/java/org/wso2/carbon/device/mgt/extensions/feature/mgt/util/AnnotationUtil.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.extensions.feature.mgt.util;
+
+import org.apache.catalina.core.StandardContext;
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.scannotation.AnnotationDB;
+import org.scannotation.WarUrlFinder;
+import org.wso2.carbon.device.mgt.common.Feature;
+import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
+
+import javax.servlet.ServletContext;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.OPTIONS;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * This has the utility function to extract feature information.
+ */
+public class AnnotationUtil {
+
+ private static final Log log = LogFactory.getLog(AnnotationUtil.class);
+
+ private static final String PACKAGE_ORG_APACHE = "org.apache";
+ private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
+ private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
+ public static final String STRING_ARR = "string_arr";
+ public static final String STRING = "string";
+ private Class featureClazz;
+ private ClassLoader classLoader;
+ private ServletContext servletContext;
+
+
+ public AnnotationUtil(final StandardContext context) {
+ servletContext = context.getServletContext();
+ classLoader = servletContext.getClassLoader();
+ }
+
+ /**
+ * Scan the context for classes with annotations
+ */
+ public Set scanStandardContext(String className) throws IOException {
+ AnnotationDB db = new AnnotationDB();
+ db.addIgnoredPackages(PACKAGE_ORG_APACHE);
+ db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS);
+ db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK);
+ URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext);
+ URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext);
+ URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath);
+ db.scanArchives(urls);
+
+ //Returns a list of classes with given Annotation
+ return db.getAnnotationIndex().get(className);
+ }
+
+ /**
+ * Method identifies the URL templates and context by reading the annotations of a class
+ */
+ public Map> extractFeatures(Set entityClasses) throws ClassNotFoundException {
+ Map> features = null;
+ if (entityClasses != null && !entityClasses.isEmpty()) {
+ features = new HashMap<>();
+ for (final String className : entityClasses) {
+ final Map> featureMap =
+ AccessController.doPrivileged(new PrivilegedAction