Merge pull request #201 from charithag/master

Add missing parts in group management
merge-requests/7/head
Ruwan 9 years ago
commit 51e27b8dc5

@ -0,0 +1,94 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>1.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>1.1.0-SNAPSHOT</version>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>API Management Extentions - Custom Annotations</Bundle-Description>
<Export-Package>
org.wso2.carbon.apimgt.annotations.*
</Export-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.servlet,
javax.xml.*,
org.apache.commons.lang,
</Import-Package>
<Embed-Dependency>
scribe;scope=compile|runtime;inline=false;
</Embed-Dependency>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

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

@ -0,0 +1,171 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>1.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.1.0-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name>
<description>This module provides capability to create api manager application.</description>
<url>http://wso2.org</url>
<dependencies>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.2</version>
<configuration>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

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

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

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

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

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Register tenant specific application</name>
<path>/permission/super admin</path>
<url>/register/tenants/*</url>
<method>POST</method>
<scope>super_admin_user</scope>
</Permission>
<Permission>
<name>Register application</name>
<path>/device-mgt/api/application/add</path>
<url>/register</url>
<method>POST</method>
<scope>application_user</scope>
</Permission>
<Permission>
<name>Delete application</name>
<path>/device-mgt/api/application/remove</path>
<url>/unregister</url>
<method>DELETE</method>
<scope>application_user</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ApiApplicationRegistration" address="/">
<jaxrs:serviceBeans>
<bean id="ApiApplicationRegistrationService"
class="org.wso2.carbon.apimgt.application.extension.api.ApiApplicationRegistrationServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
</web-app>

@ -0,0 +1,118 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId>
<version>1.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.1.0-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name>
<description>This module provides capability to create api manager application.</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<excludes>
<exclude>**/Abstract*</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.apimgt.application.extension.internal</Private-Package>
<Import-Package>
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
</Import-Package>
<Export-Package>
!org.wso2.carbon.apimgt.application.extension.internal,
org.wso2.carbon.apimgt.application.extension.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>

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

@ -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<String, Object> 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<String, Object> 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<API> userVisibleAPIs = null;
for (String tag : tags) {
Set<API> tagAPIs = apiConsumer.getAPIsWithTag(tag);
if (userVisibleAPIs == null) {
userVisibleAPIs = tagAPIs;
} else {
userVisibleAPIs.addAll(tagAPIs);
}
}
if (userVisibleAPIs != null) {
Set<SubscribedAPI> 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<API> userVisibleAPIs = apiConsumer.getAllPublishedAPIs(tenantDomain);
Subscriber subscriber = apiConsumer.getSubscriber(username);
Set<SubscribedAPI> 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);
}
}
}

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

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

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

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

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

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

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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
@ -27,7 +27,6 @@
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>apimgt-extensions</artifactId>
<version>1.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
@ -36,6 +35,9 @@
<modules>
<module>org.wso2.carbon.apimgt.webapp.publisher</module>
<module>org.wso2.carbon.apimgt.application.extension</module>
<module>org.wso2.carbon.apimgt.application.extension.api</module>
<module>org.wso2.carbon.apimgt.annotations</module>
</modules>
<build>

@ -1,10 +1,10 @@
/*
* 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
*
@ -17,6 +17,7 @@
*/
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<MetadataEntry> 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;
}
}
}

@ -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<GroupUser> users;
private List<String> roles;
@XmlElement
public int getId() {
return id;
}
protected void setId(int id) {
this.id = id;
}
@XmlElement
public String getDescription() {
return description;

@ -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<GroupUser> users) {
super.setUsers(users);

@ -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<DeviceGroupBuilder> getGroups(int tenantId) throws GroupManagementDAOException;
List<DeviceGroupBuilder> 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<DeviceGroupBuilder> getGroups(String groupName, int tenantId) throws GroupManagementDAOException;
List<DeviceGroupBuilder> 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<Device> 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<Device> 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<Device> getDevices(int groupId, PaginationRequest request, int tenantId) throws GroupManagementDAOException;
}

@ -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<DeviceGroupBuilder> getGroups(int tenantId) throws GroupManagementDAOException {
public List<DeviceGroupBuilder> getGroups(PaginationRequest request, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroupBuilder> 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<DeviceGroupBuilder> 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<DeviceGroupBuilder> findInGroups(String groupName, int tenantId)
throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroupBuilder> 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<Device> 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<Device> getDevices(int groupId, int tenantId) throws GroupManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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<Device> getDevices(int groupId, PaginationRequest request, int tenantId)
throws GroupManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Device> 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;
}
}

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

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

@ -14,14 +14,13 @@
* 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<DeviceGroup> findGroups(String groupName, String username) throws GroupManagementException;
List<DeviceGroup> findInGroups(String groupName, String username) throws GroupManagementException;
/**
* Get all device groups in tenant
*
* @return list of groups
* @throws GroupManagementException
*/
List<DeviceGroup> 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<String> getRoles(String groupName) throws GroupManagementException;
List<String> 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<String> getRoles(String userName, String groupName) throws GroupManagementException;
List<String> 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<GroupUser> getUsers(String groupName) throws GroupManagementException;
List<GroupUser> 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<Device> getDevices(String groupName) throws GroupManagementException;
List<Device> 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<Device> 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;
}

@ -14,15 +14,19 @@
* 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<String> groupRoles = getRoles(groupName);
List<String> groupRoles = getRoles(groupId);
for (String role : groupRoles) {
if (role != null) {
roleName = role.replace("Internal/group-" + groupName + "-", "");
removeGroupSharingRole(groupName, roleName);
}
}
List<Device> groupDevices = getDevices(groupName);
try {
for (Device device : groupDevices) {
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().modifyEnrollment(device);
roleName = role.replace("Internal/group-" + groupId + "-", "");
removeGroupSharingRole(groupId, roleName);
}
} 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<DeviceGroup> findGroups(String groupName, String owner) throws GroupManagementException {
public List<DeviceGroup> findInGroups(String groupName, String owner) throws GroupManagementException {
List<DeviceGroupBuilder> 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<DeviceGroup> 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<DeviceGroup> getGroups(PaginationRequest request) throws GroupManagementException {
List<DeviceGroupBuilder> 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<DeviceGroup> 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<String, DeviceGroup> groups = new HashMap<>();
Map<Integer, DeviceGroup> 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<String> getRoles(String groupName) throws GroupManagementException {
public List<String> getRoles(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
String[] roles;
List<String> 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<String> getRoles(String username, String groupName) throws GroupManagementException {
public List<String> getRoles(String username, int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
List<String> 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<GroupUser> getUsers(String groupName) throws GroupManagementException {
public List<GroupUser> getUsers(int groupId) throws GroupManagementException {
UserStoreManager userStoreManager;
Map<String, GroupUser> groupUserHashMap = new HashMap<>();
try {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
.getUserStoreManager();
List<String> rolesForGroup = this.getRoles(groupName);
List<String> 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<Device> 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<Device> 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<Device> 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,
GroupManagementDAOFactory.getConnection();
count = groupDAO.getDeviceCount(groupId,
CarbonContext.getThreadLocalCarbonContext().getTenantId());
GroupManagementDAOFactory.commitTransaction();
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<String> roles = getRoles(username, groupName);
List<String> roles = getRoles(username, groupId);
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
@ -553,7 +584,7 @@ public class GroupManagementServiceProviderImpl implements GroupManagementServic
for (String resourceId : resourceIds) {
for (String roleName : roles) {
if (userRealm.getAuthorizationManager().
isRoleAuthorized("Internal/group-" + groupName + "-" + roleName, resourceId,
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<String, DeviceGroup> groups = new HashMap<>();
Map<Integer, DeviceGroup> 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,16 +629,16 @@ 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<String> roles = this.getRoles(username, groupName);
List<String> roles = this.getRoles(username, groupId);
for (String role : roles) {
if (userRealm.getAuthorizationManager()
.isRoleAuthorized("Internal/group-" + groupName + "-" + role, permission,
.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<Integer, DeviceGroup> 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;
}
}

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

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

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

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

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

@ -33,6 +33,7 @@
<class name="org.wso2.carbon.device.mgt.core.dao.ApplicationPersistenceTests"/>
<class name="org.wso2.carbon.device.mgt.core.search.DeviceDetails"/>
<class name="org.wso2.carbon.device.mgt.core.search.SearchDevice"/>
<class name="org.wso2.carbon.device.mgt.core.dao.GroupPersistTests"/>
</classes>
</test>
<test name="Service Unit Tests" preserve-order="true">

@ -1,4 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
@ -40,6 +58,38 @@
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.tomcat</groupId>
<artifactId>tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.tomcat</groupId>
<artifactId>tomcat-servlet-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
<dependency>
<groupId>commons-lang.wso2</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
</dependencies>
<build>
@ -59,7 +109,7 @@
</Export-Package>
<Import-Package>
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
</Import-Package>
</instructions>
</configuration>

@ -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<String, List<Feature>> 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<String, List<Feature>> 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<Feature> 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<Feature> getFeatures(String deviceType) {
return featureSet.get(deviceType);
}
}

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

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

@ -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<String> annotatedAPIClasses = annotationUtil.scanStandardContext(DeviceType.class.getName());
Map<String, List<Feature>> 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);
}
}
}
}
}

@ -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<org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature> 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<String> 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<String, List<Feature>> extractFeatures(Set<String> entityClasses) throws ClassNotFoundException {
Map<String, List<Feature>> features = null;
if (entityClasses != null && !entityClasses.isEmpty()) {
features = new HashMap<>();
for (final String className : entityClasses) {
final Map<String, List<Feature>> featureMap =
AccessController.doPrivileged(new PrivilegedAction<Map<String, List<Feature>>>() {
public Map<String, List<Feature>> run() {
Map<String, List<Feature>> featureMap = new HashMap<>();
try {
Class<?> clazz = classLoader.loadClass(className);
Class<DeviceType> deviceTypeClazz = (Class<DeviceType>) classLoader.loadClass(
DeviceType.class.getName());
Annotation deviceTypeAnno = clazz.getAnnotation(deviceTypeClazz);
if (deviceTypeAnno != null) {
Method[] deviceTypeMethod = deviceTypeClazz.getMethods();
String deviceType = invokeMethod(deviceTypeMethod[0], deviceTypeAnno, STRING);
featureClazz =
(Class<org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations
.Feature>) classLoader.loadClass(
org.wso2.carbon.device.mgt.extensions.feature.mgt
.annotations.Feature.class.getName());
List<Feature> featureList = getFeatures(clazz.getDeclaredMethods());
featureMap.put(deviceType, featureList);
}
} catch (Throwable e) {
log.error("Failed to load the annotation from the features in the " +
"class " + className, e);
}
return featureMap;
}
});
features.putAll(featureMap);
}
}
return features;
}
private List<Feature> getFeatures(Method[] annotatedMethods) throws Throwable {
List<Feature> featureList = new ArrayList<>();
for (Method method : annotatedMethods) {
Annotation methodAnnotation = method.getAnnotation(featureClazz);
if (methodAnnotation != null) {
Annotation[] annotations = method.getDeclaredAnnotations();
for (int i = 0; i < annotations.length; i++) {
if (annotations[i].annotationType().getName().equals(
org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature.class.getName())) {
Feature feature = new Feature();
Method[] featureAnnoMethods = featureClazz.getMethods();
Annotation featureAnno = method.getAnnotation(featureClazz);
for (int k = 0; k < featureAnnoMethods.length; k++) {
switch (featureAnnoMethods[k].getName()) {
case "name":
feature.setName(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
case "code":
feature.setCode(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
case "description":
feature.setDescription(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
case "type":
feature.setType(invokeMethod(featureAnnoMethods[k], featureAnno, STRING));
break;
}
}
//Extracting method with which feature is exposed
if (annotations[i].annotationType().getName().equals(GET.class.getName())) {
feature.setMethod(HttpMethod.GET);
}
if (annotations[i].annotationType().getName().equals(POST.class.getName())) {
feature.setMethod(HttpMethod.POST);
}
if (annotations[i].annotationType().getName().equals(OPTIONS.class.getName())) {
feature.setMethod(HttpMethod.OPTIONS);
}
if (annotations[i].annotationType().getName().equals(DELETE.class.getName())) {
feature.setMethod(HttpMethod.DELETE);
}
if (annotations[i].annotationType().getName().equals(PUT.class.getName())) {
feature.setMethod(HttpMethod.PUT);
}
try {
Class<FormParam> formParamClazz = (Class<FormParam>) classLoader.loadClass(
FormParam.class.getName());
Method[] formMethods = formParamClazz.getMethods();
//Extract method parameter information and store same as feature meta info
List<Feature.MetadataEntry> metaInfoList = new ArrayList<>();
Annotation[][] paramAnnotations = method.getParameterAnnotations();
for (int j = 0; j < paramAnnotations.length; j++) {
for (Annotation anno : paramAnnotations[j]) {
if (anno.annotationType().getName().equals(FormParam.class.getName())) {
Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry();
metadataEntry.setId(j);
metadataEntry.setValue(invokeMethod(formMethods[0], anno, STRING));
metaInfoList.add(metadataEntry);
}
}
}
feature.setMetadataEntries(metaInfoList);
} catch (ClassNotFoundException e) {
log.debug("No Form Param found for class " + featureClazz.getName());
}
featureList.add(feature);
}
}
}
}
return featureList;
}
/**
* When an annotation and method is passed, this method invokes that executes said method against the annotation
*/
private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
switch (returnType) {
case STRING:
return (String) methodHandler.invoke(annotation, method, null);
case STRING_ARR:
return ((String[]) methodHandler.invoke(annotation, method, null))[0];
default:
return null;
}
}
}

@ -40,7 +40,7 @@
</a>
</li>
{{else}}
{{#if permissions.addDevice}}
{{#if permissions.enroll}}
<li>
<a href="{{@app.context}}/device/enroll" class="cu-btn">
<span class="icon fw-stack">

@ -26,10 +26,11 @@ function onRequest(context) {
page.groupName = groupName;
}
page.title =title;
page.permissions = {};
var currentUser = session.get(constants.USER_SESSION_KEY);
if (currentUser) {
if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/add")) {
page.addDevice = true;
page.permissions.enroll = true;
}
}
return page;

@ -1,4 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
@ -22,6 +40,14 @@
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.scannotation</groupId>
<artifactId>scannotation</artifactId>
</dependency>
</dependencies>
<build>
@ -51,6 +77,33 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>ApiApplicationRegistration.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
@ -75,6 +128,15 @@
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.webapp.publisher:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.application.extension:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.apimgt.annotations:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.orbit.org.scannotation:scannotation:${scannotation.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef>

@ -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,
@ -24,6 +35,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,

@ -1,3 +1,3 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.devicemgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.ui_${feature.version}/jaggeryapps/devicemgt-cdmf,target:${installFolder}/../../deployment/server/jaggeryapps/devicemgt-cdmf,overwrite:true);\

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>jwt-client-feature</artifactId>
<version>1.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.identity.jwt.client.extension.feature</artifactId>
<packaging>pom</packaging>
<version>1.1.0-SNAPSHOT</version>
<name>WSO2 Carbon - JWT Client Feature</name>
<url>http://wso2.org</url>
<description>This feature contains jwt client implementation from which we can get a access token using the jwt
grant type handler
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.nimbusds</groupId>
<artifactId>nimbus-jose-jwt</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.identity.jwt.client.extension</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.identity.jwt.client.extension:${carbon.device.mgt.version}
</bundleDef>
<bundleDef>
org.wso2.orbit.com.nimbusds:nimbus-jose-jwt:${nimbus.orbit.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,44 @@
<!--
~ 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.
-->
<IdentityProvider>
<IdentityProviderName>CDMF_DEFAULT_IDP</IdentityProviderName>
<DisplayName>CDMF_DEFAULT_IDP</DisplayName>
<IdentityProviderDescription></IdentityProviderDescription>
<Alias>https://localhost:9443/oauth2/token</Alias>
<IsPrimary>true</IsPrimary>
<IsFederationHub></IsFederationHub>
<HomeRealmId></HomeRealmId>
<ProvisioningRole></ProvisioningRole>
<FederatedAuthenticatorConfigs></FederatedAuthenticatorConfigs>
<DefaultAuthenticatorConfig>
</DefaultAuthenticatorConfig>
<ProvisioningConnectorConfigs>
<!--<ProvisioningConnectorConfig>
<ProvisioningProperties>
</ProvisioningProperties>
</ProvisioningConnectorConfig>-->
</ProvisioningConnectorConfigs>
<!--<DefaultProvisioningConnectorConfig></DefaultProvisioningConnectorConfig>-->
<ClaimConfig></ClaimConfig>
<Certificate>
MIIFkzCCA3sCBAKkVfcwDQYJKoZIhvcNAQEFBQAwgY0xCzAJBgNVBAYTAlNMMRAwDgYDVQQIEwdXZXN0ZXJuMRAwDgYDVQQHEwdDb2xvbWJvMQ0wCwYDVQQKEwRXU08yMRQwEgYDVQQLEwtFbmdpbmVlcmluZzESMBAGA1UEAxMJbG9jYWxob3N0MSEwHwYJKoZIhvcNAQkBFhJpb3RzZXJ2ZXJAd3NvMi5jb20wHhcNMTUxMjE3MTMxMTA0WhcNMTcxMjE2MTMxMTA0WjCBjTELMAkGA1UEBhMCU0wxEDAOBgNVBAgTB1dlc3Rlcm4xEDAOBgNVBAcTB0NvbG9tYm8xDTALBgNVBAoTBFdTTzIxFDASBgNVBAsTC0VuZ2luZWVyaW5nMRIwEAYDVQQDEwlsb2NhbGhvc3QxITAfBgkqhkiG9w0BCQEWEmlvdHNlcnZlckB3c28yLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALkiGVQ9tZOKIi/gD/toV+enq+neqOBGYQ8Fq/ABOWnK2QpGWm81+Rets5GbQ6W//D8C5TOBGqK7z+LAgdmILr1XLkvrXWoan0GPdDJ1wpc2/6XDZvM5f7Y8cmRqVPJv7AF+ImgF9dqv97gYCiujy+nNHd5Nk/60pco2LBV5SyLqqrzKXEnSGrS4zoYWpPeJ9YrXPEkW7A6AxTQK0yU9Ej4TktgafbTueythrLomKiZJj4wPxm2lA2lAZscDdws9NWrI5z/LUVLbUMxrY10Nig1liX5b1mrUk5bb1d2tqwkPrpRILKoOBJtI674SQS3GziiUiCJGIO/EGGRn1AJsC/SvnnEez3WKY/DgJ6102MWK/yWtY8NYHUX2anwMBS7UpT5A4BXdsfBz3R+iPF99FxdAGGsS4GQuuPocZaycLqoPCxpTSSxBsKMUcKpn3yaiQRd6uDuiTNt7odDOQj0Tno7uokh/HILgbzvj9EExDOsdwLVvqYmUHBPeLmiICWXfi4kyH/twPOZtV9eVnfWYx5Kwg+2Y4fIb3q4ABr0hzxaMYHQo6NOukSH1BcdAWiQIXbSFFaTZD8p6OfiZpHcQ59HT/Z8GBlCFL2xkYJFmOhXI/Cu+xrcwqEIInv7d8w3eiNQ7MneomEptLbBk9+kMsP0ubo34oOGHR9qk3Lj580c/AgMBAAEwDQYJKoZIhvcNAQEFBQADggIBADw70g2/wrgzrAM8OXBlthGbCEaXZpKwq9IJN0qu+/l+PNwF7csQhj+qW+zMrWaH1DGWJroaei1+NFFrj/pvp61rF/ZeTPGVJd7puCq++SevqIrzKyAEBtwtpXmcFhBpV/FrQAv3ODOJ3bN2wSRPZHUvARTBB3RaUI06g1jCaBzjDEGoMfSxdr5/Ty2WxTI9u9RlIs3Q52AiOmROtLPiEQZQIqfNO3cxCEWojHxPqVEZA/kQYy+rryj4H0zzSrj7QFlQhsMDw5j8bv9AcvTEGmwp29avsgnceDWinI6lwtd8zqh0ZW9QJdH0BRNCM/EkTlTUHeEg04/sOgOrlWcvEfVxDqNEtbUzU9UFxl0lkQkuRn1UdxZlvhWaFnel5iRC9b7OZvi2mkVujLyxEWlJB1tuyMLQxu6PfabBVODP5V8/+uyiiK/gwrB5rYl8RHxGoznJnI1Y3HVzKlA849CrMBaY5vnhE03cNja7QroPzLmmuXBLk2LbI1lu5nJAqKpBUPMI/IU3pF4Q7VTD2ZANI+ktGgGlM8AK4OJHWOhj8W289pWTHVjG8syPLTsaYkhgLjzZl/g9cUwn/96NJNvzd3dkT+7VgE+BJOLofq25CjZcN1M7MhWdl3vbWNj9vzL0+FCnwca8UecfvFS39PIekIvqbtP+Gw8NiYOUGIllZ0JH
</Certificate>
<PermissionAndRoleConfig></PermissionAndRoleConfig>
<JustInTimeProvisioningConfig></JustInTimeProvisioningConfig>
</IdentityProvider>

@ -0,0 +1,19 @@
#
# 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.
#
custom = true

@ -0,0 +1,54 @@
#
# 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.
#
#issuer of the JWT
iss=CDMF_DEFAULT_IDP
TokenEndpoint=https://localhost:9443/oauth2/token
#audience of JWT claim
#comma seperated values
aud=https://localhost:9443/oauth2/token
#expiration time of JWT (number of minutes from the current time)
exp=1000
#issued at time of JWT (number of minutes from the current time)
iat=0
#nbf time of JWT (number of minutes from current time)
nbf=0
#skew between IDP and issuer(seconds)
skew=0
# JWT Id
#jti=token123
#KeyStore to cryptographic credentials
#KeyStore=src/main/resources/wso2carbon.jks
#Password of the KeyStore
#KeyStorePassword=wso2carbon
#Alias of the SP's private key
#PrivateKeyAlias=wso2carbon
#Private key password to retrieve the private key used to sign
#AuthnRequest and LogoutRequest messages
#PrivateKeyPassword=wso2carbon

@ -0,0 +1,3 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/jwt.properties,target:${installFolder}/../../conf/etc/jwt.properties,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.identity.jwt.client.extension_${feature.version}/CDMF_DEFAULT_IDP.xml,target:${installFolder}/../../conf/identity/identity-providers/CDMF_DEFAULT_IDP.xml,overwrite:true);\

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId>
<version>1.1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jwt-client-feature</artifactId>
<version>1.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - Dynamic Client Registration Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.identity.jwt.client.extension.feature</module>
</modules>
</project>

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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
@ -50,6 +50,7 @@
<module>features/dynamic-client-registration</module>
<module>features/oauth-extensions</module>
<module>features/email-sender</module>
<module>features/jwt-client</module>
</modules>
<dependencyManagement>
@ -200,6 +201,11 @@
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.dynamic.client.registration</artifactId>
@ -275,6 +281,21 @@
<type>zip</type>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<!-- Device Management dependencies -->
<!-- Governance dependencies -->
@ -1209,6 +1230,11 @@
<artifactId>jackson-jaxrs</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.commons</groupId>
@ -1306,6 +1332,12 @@
<artifactId>commons-collections</artifactId>
<version>${commons-collections.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<!--Tomcat-->
<dependency>
@ -1682,7 +1714,8 @@
<version.commons.lang>2.6.0.wso2v1</version.commons.lang>
<!-- Carbon API Management -->
<carbon.api.mgt.version>4.3.0</carbon.api.mgt.version>
<carbon.api.mgt.version>5.0.3</carbon.api.mgt.version>
<carbon.api.mgt.version.range>(5.0.0,6.0.0]</carbon.api.mgt.version.range>
<!-- Carbon Analytics Commons -->
<carbon.analytics.common.version>5.0.11-SNAPSHOT</carbon.analytics.common.version>

Loading…
Cancel
Save