diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java similarity index 80% rename from components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java rename to components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java index 65ade5cc3a..9e0068635b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java @@ -28,18 +28,24 @@ import java.lang.annotation.Target; */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) -public @interface Permission { +public @interface Scope { + + /** + * Represents the scope key which should be unique. + * @return Returns scope key. + */ + String key(); /** * Represents the scope name. * @return Returns scope name. */ - String scope(); + String name(); /** - * Represents the associated permissions. - * @return Returns list of permissions. + * Represents the scope description. + * @return Returns scope description. */ - String[] permissions(); + String description(); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index 5e7794b952..8d3f9af30b 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -161,6 +161,10 @@ org.wso2.carbon.user.api provided + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java index 8a81a8a5ec..8e2843cdc3 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java @@ -18,20 +18,19 @@ package org.wso2.carbon.apimgt.application.extension.api; +import org.wso2.carbon.apimgt.annotations.api.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.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * This is the application registration service that exposed for apimApplicationRegistration */ +@API(name = "API Registration Service", version = "1.0.0", + context = "api-application-registration", + tags = {"devicemgt_admin"}) public interface ApiApplicationRegistrationService { /** @@ -40,6 +39,7 @@ public interface ApiApplicationRegistrationService { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) + @Path("register/tenants") Response register(@PathParam("tenantDomain") String tenantDomain, @QueryParam("applicationName") String applicationName); @@ -51,6 +51,7 @@ public interface ApiApplicationRegistrationService { @POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) + @Path("register") Response register(RegistrationProfile registrationProfile); /** @@ -59,5 +60,6 @@ public interface ApiApplicationRegistrationService { * @return the response status of request. */ @DELETE + @Path("unregister") Response unregister(@QueryParam("applicationName") String applicationName); } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index d01a2fb7ec..e88d80e67c 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -22,13 +22,13 @@ 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.APIUtil; 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.base.MultitenantConstants; 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; @@ -46,7 +46,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi public Response register(@QueryParam("tenantDomain") String tenantDomain, @QueryParam("applicationName") String applicationName) { String authenticatedTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (!authenticatedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(authenticatedTenantDomain)) { return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } try { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml index 549bf4c1bd..e771ee6c09 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml @@ -47,7 +47,11 @@ managed-api-enabled - false + true + + + managed-api-owner + admin diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java index bc02828ee3..304cab7df0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -23,12 +23,7 @@ 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.api.model.*; 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; @@ -415,7 +410,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId); String tenantDomain = MultitenantUtils.getTenantDomain(username); Set userVisibleAPIs = apiConsumer.getAllPublishedAPIs(tenantDomain); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { userVisibleAPIs.addAll(apiConsumer.getAllPublishedAPIs(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); } Subscriber subscriber = apiConsumer.getSubscriber(username); @@ -443,7 +438,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe try { APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); loginInfoJsonObj.put("user", username); - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { loginInfoJsonObj.put("isSuperTenant", true); } else { loginInfoJsonObj.put("isSuperTenant", false); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java index 530dfa662f..8c204c422e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java @@ -37,7 +37,7 @@ public final class APIManagerUtil { */ public static int getTenantId(String tenantDomain) throws APIManagerException { try { - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { return MultitenantConstants.SUPER_TENANT_ID; } TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager(); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml index 21338e0129..3a565f1762 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml @@ -107,6 +107,10 @@ javax.ws.rs javax.ws.rs-api + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java index 27e2af8fb6..289037e58e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java @@ -18,7 +18,6 @@ package org.wso2.carbon.apimgt.webapp.publisher; -import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; @@ -30,16 +29,20 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.core.util.Utils; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; import javax.servlet.ServletContext; import java.util.*; public class APIPublisherUtil { - private static final Log log = LogFactory.getLog(APIPublisherUtil.class); - private static final String DEFAULT_API_VERSION = "1.0.0"; public static final String API_VERSION_PARAM = "{version}"; public static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox"; + private static final Log log = LogFactory.getLog(APIPublisherUtil.class); + private static final String DEFAULT_API_VERSION = "1.0.0"; private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; @@ -121,16 +124,18 @@ public class APIPublisherUtil { if (scope != null) { if (apiScopes.get(scope.getKey()) == null) { apiScopes.put(scope.getKey(), scope); - } else { - existingScope = apiScopes.get(scope.getKey()); - existingPermissions = existingScope.getRoles(); - existingPermissions = getDistinctPermissions(existingPermissions + "," + scope.getRoles()); - existingScope.setRoles(existingPermissions); - apiScopes.put(scope.getKey(), existingScope); } } } Set scopes = new HashSet<>(apiScopes.values()); + // adding existing persisted roles to the scopes + try { + setExistingRoles(scopes); + } catch (ScopeManagementException | UserStoreException e) { + throw new APIManagementException("Error occurred while retrieving roles for the existing scopes"); + } + + // set current scopes to API api.setScopes(scopes); // this has to be done because of the use of pass by reference @@ -242,7 +247,7 @@ public class APIPublisherUtil { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; apiConfig.setTenantDomain(tenantDomain); String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER; - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER; } apiConfig.setContextTemplate(contextTemplate); @@ -307,9 +312,34 @@ public class APIPublisherUtil { return apiConfig; } - private static String getDistinctPermissions(String permissions) { - String[] unique = new HashSet(Arrays.asList(permissions.split(","))).toArray(new String[0]); - return StringUtils.join(unique, ","); + /** + * This method is used to set the existing roles of the given scope. + * + * @param scopes List of scopes. + * @throws ScopeManagementException + */ + private static void setExistingRoles(Set scopes) throws ScopeManagementException, UserStoreException { + String scopeKey; + String roles; + ScopeManagementService scopeManagementService = WebappPublisherUtil.getScopeManagementService(); + UserRealm userRealm = WebappPublisherUtil.getUserRealm(); + + if (scopeManagementService == null) { + throw new ScopeManagementException("Error occurred while initializing scope management service"); + } else if (userRealm == null) { + throw new UserStoreException("Error occurred while initializing realm service"); + } else { + String adminRole = userRealm.getRealmConfiguration().getAdminRoleName(); + for (Scope scope : scopes) { + scopeKey = scope.getKey(); + roles = scopeManagementService.getRolesOfScope(scopeKey); + if (roles == null) { + roles = adminRole; + } + scope.setRoles(roles); + + } + } } } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java index 17e2edb9a8..ca2f0cba13 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java @@ -18,7 +18,16 @@ package org.wso2.carbon.apimgt.webapp.publisher; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.service.RealmService; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; @@ -31,6 +40,10 @@ import java.io.File; */ public class WebappPublisherUtil { + private static Log log = LogFactory.getLog(WebappPublisherUtil.class); + private static final int CARBON_SUPER = -1234; + + public static Document convertToDocument(File file) throws WebappPublisherConfigurationFailedException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); @@ -44,4 +57,32 @@ public class WebappPublisherUtil { } } + public static ScopeManagementService getScopeManagementService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ScopeManagementService scopeManagementService = + (ScopeManagementService) ctx.getOSGiService(ScopeManagementService.class, null); + if (scopeManagementService == null) { + String msg = "Scope Management Service has not been initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + return scopeManagementService; + } + + /** + * Getting the current tenant's user realm + */ + public static UserRealm getUserRealm() throws UserStoreException { + RealmService realmService; + UserRealm realm; + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + + if (realmService == null) { + throw new IllegalStateException("Realm service not initialized"); + } + realm = realmService.getTenantUserRealm(CARBON_SUPER); + return realm; + } + } diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java deleted file mode 100644 index 651c285723..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.apimgt.webapp.publisher.config; - -/** - * Custom exception class of Permission related operations. - */ -public class PermissionManagementException extends Exception { - - private static final long serialVersionUID = -3151279311929070298L; - - private String errorMessage; - - public String getErrorMessage() { - return errorMessage; - } - - public void setErrorMessage(String errorMessage) { - this.errorMessage = errorMessage; - } - - public PermissionManagementException(String msg, Exception nestedEx) { - super(msg, nestedEx); - setErrorMessage(msg); - } - - public PermissionManagementException(String message, Throwable cause) { - super(message, cause); - setErrorMessage(message); - } - - public PermissionManagementException(String msg) { - super(msg); - setErrorMessage(msg); - } - - public PermissionManagementException() { - super(); - } - - public PermissionManagementException(Throwable cause) { - super(cause); - } - -} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java index 3db6a31551..bc4bf85724 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java @@ -19,20 +19,13 @@ package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; import org.apache.catalina.core.StandardContext; -import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.scannotation.AnnotationDB; -import org.scannotation.WarUrlFinder; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration; -import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionConfiguration; -import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException; import javax.servlet.ServletContext; import javax.ws.rs.*; @@ -61,22 +54,18 @@ public class AnnotationProcessor { private static final String WILD_CARD = "/*"; private static final String AUTH_TYPE = "Any"; - private static final String PROTOCOL_HTTP = "http"; - private static final String SERVER_HOST = "carbon.local.ip"; - private static final String HTTP_PORT = "httpPort"; private static final String STRING_ARR = "string_arr"; private static final String STRING = "string"; + Class apiClazz; private StandardContext context; private Method[] pathClazzMethods; private Class pathClazz; - Class apiClazz; private ClassLoader classLoader; private ServletContext servletContext; public AnnotationProcessor(final StandardContext context) { - this.context = context; servletContext = context.getServletContext(); classLoader = servletContext.getClassLoader(); } @@ -142,7 +131,7 @@ public class AnnotationProcessor { pathClazzMethods = pathClazz.getMethods(); Annotation rootContectAnno = clazz.getAnnotation(pathClazz); - String subContext = ""; + String subContext; if (rootContectAnno != null) { subContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING); if (subContext != null && !subContext.isEmpty()) { @@ -151,8 +140,6 @@ public class AnnotationProcessor { } else { rootContext = rootContext + "/" + subContext; } - } else { - subContext = ""; } if (log.isDebugEnabled()) { log.debug("API Root Context = " + rootContext); @@ -167,7 +154,7 @@ public class AnnotationProcessor { } } } catch (ClassNotFoundException e) { - log.error("Error when passing the api annotation for device type apis."); + log.error("Error when passing the api annotation for device type apis.", e); } return apiResourceConfig; } @@ -252,15 +239,9 @@ public class AnnotationProcessor { Annotation producesAnno = method.getAnnotation(producesClass); resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR)); } - if (annotations[i].annotationType().getName().equals(Permission.class.getName())) { - PermissionConfiguration permissionConf = this.getPermission(method); - if (permissionConf != null) { - Scope scope = new Scope(); - scope.setKey(permissionConf.getScopeName()); - scope.setDescription(permissionConf.getScopeName()); - scope.setName(permissionConf.getScopeName()); - String roles = StringUtils.join(permissionConf.getPermissions(), ","); - scope.setRoles(roles); + if (annotations[i].annotationType().getName().equals(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName())) { + org.wso2.carbon.apimgt.api.model.Scope scope = this.getScope(method); + if (scope != null) { resource.setScope(scope); } } @@ -319,7 +300,7 @@ public class AnnotationProcessor { * @return */ private String makeContextURLReady(String context) { - if (context != null && !context.equalsIgnoreCase("")) { + if (context != null && context.length() > 0) { if (context.startsWith("/")) { return context; } else { @@ -358,35 +339,32 @@ public class AnnotationProcessor { return ((String[]) methodHandler.invoke(annotation, method, null)); } - private PermissionConfiguration getPermission(Method currentMethod) throws Throwable { - Class permissionClass = (Class) classLoader.loadClass(Permission.class.getName()); - Annotation permissionAnnotation = currentMethod.getAnnotation(permissionClass); - if (permissionClass != null) { - Method[] permissionClassMethods = permissionClass.getMethods(); - PermissionConfiguration permissionConf = new PermissionConfiguration(); + private org.wso2.carbon.apimgt.api.model.Scope getScope(Method currentMethod) throws Throwable { + Class scopeClass = + (Class) classLoader. + loadClass(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName()); + Annotation permissionAnnotation = currentMethod.getAnnotation(scopeClass); + if (scopeClass != null) { + Method[] permissionClassMethods = scopeClass.getMethods(); + org.wso2.carbon.apimgt.api.model.Scope scope = new org.wso2.carbon.apimgt.api.model.Scope(); for (Method method : permissionClassMethods) { switch (method.getName()) { - case "scope": - permissionConf.setScopeName(invokeMethod(method, permissionAnnotation, STRING)); + case "key": + scope.setKey(invokeMethod(method, permissionAnnotation, STRING)); break; - case "permissions": - String permissions[] = invokeMethod(method, permissionAnnotation); - this.addPermission(permissions); - permissionConf.setPermissions(permissions); + case "name": + scope.setName(invokeMethod(method, permissionAnnotation, STRING)); + break; + case "description": + scope.setDescription(invokeMethod(method, permissionAnnotation, STRING)); break; } } - return permissionConf; + return scope; } return null; } - private void addPermission(String[] permissions) throws PermissionManagementException { - for (String permission : permissions) { - PermissionUtils.addPermission(permission); - } - } - /** * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java index a62a58f733..e20b4ba467 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java @@ -15,6 +15,7 @@ */ package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; + import org.scannotation.archiveiterator.DirectoryIteratorFactory; import org.scannotation.archiveiterator.Filter; import org.scannotation.archiveiterator.JarIterator; diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java deleted file mode 100644 index 32c5bad855..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * you may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util; - -import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException; -import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.registry.api.RegistryException; -import org.wso2.carbon.registry.api.Resource; -import org.wso2.carbon.registry.core.Registry; - -import java.util.StringTokenizer; - -/** - * Utility class which holds necessary utility methods required for persisting permissions in - * registry. - */ -public class PermissionUtils { - - public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; - public static final String PERMISSION_PROPERTY_NAME = "name"; - - public static Registry getGovernanceRegistry() throws PermissionManagementException { - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return APIPublisherDataHolder.getInstance().getRegistryService() - .getGovernanceSystemRegistry( - tenantId); - } catch (RegistryException e) { - throw new PermissionManagementException( - "Error in retrieving governance registry instance: " + - e.getMessage(), e); - } - } - - public static void addPermission(String permission) throws PermissionManagementException { - String resourcePermission = getAbsolutePermissionPath(permission); - try { - StringTokenizer tokenizer = new StringTokenizer(resourcePermission, "/"); - String lastToken = "", currentToken, tempPath; - while (tokenizer.hasMoreTokens()) { - currentToken = tokenizer.nextToken(); - tempPath = lastToken + "/" + currentToken; - if (!checkResourceExists(tempPath)) { - createRegistryCollection(tempPath, currentToken); - } - lastToken = tempPath; - } - } catch (RegistryException e) { - throw new PermissionManagementException("Error occurred while persisting permission : " + - resourcePermission, e); - } - } - - public static void createRegistryCollection(String path, String resourceName) - throws PermissionManagementException, - RegistryException { - Resource resource = PermissionUtils.getGovernanceRegistry().newCollection(); - resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName); - PermissionUtils.getGovernanceRegistry().beginTransaction(); - PermissionUtils.getGovernanceRegistry().put(path, resource); - PermissionUtils.getGovernanceRegistry().commitTransaction(); - } - - public static boolean checkResourceExists(String path) - throws PermissionManagementException, - org.wso2.carbon.registry.core.exceptions.RegistryException { - return PermissionUtils.getGovernanceRegistry().resourceExists(path); - } - - private static String getAbsolutePermissionPath(String permissionPath) { - return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath; - } - -} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml index 714b002d9b..b1b0b768d7 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml @@ -76,7 +76,7 @@ - + @@ -148,26 +148,6 @@ org.wso2.carbon.logging provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - provided - - - org.apache.axis2.wso2 - axis2-client - - - org.apache.neethi.wso2 - neethi - - - org.wso2.carbon.devicemgt org.wso2.carbon.certificate.mgt.core diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java index 96351caedd..fbb9458962 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java @@ -4,7 +4,7 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse; import javax.ws.rs.*; @@ -46,7 +46,7 @@ public interface CertificateMgtService { message = "Internal Server Error. \n Error occurred while retrieving signed certificate.", response = ErrorResponse.class) }) - @Permission(scope = "sign-csr", permissions = {"/permission/admin/device-mgt/scep/sign-csr"}) + @Scope(key = "certificate:sign-csr", name = "Sign CSR", description = "") Response getSignedCertFromCSR( @ApiParam( name = "If-Modified-Since", diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml index f0c8147017..e0bbaee6bc 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml @@ -72,7 +72,7 @@ - + @@ -144,26 +144,6 @@ org.wso2.carbon.logging provided - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.common - provided - - - org.wso2.carbon.devicemgt - org.wso2.carbon.device.mgt.core - provided - - - org.apache.axis2.wso2 - axis2-client - - - org.apache.neethi.wso2 - neethi - - - org.wso2.carbon.devicemgt org.wso2.carbon.certificate.mgt.core diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java index 6988f31712..da1d54bc4f 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java @@ -1,7 +1,8 @@ package org.wso2.carbon.certificate.mgt.cert.jaxrs.api; import io.swagger.annotations.*; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; @@ -11,6 +12,10 @@ import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@API(name = "Certificate Management", version = "1.0.0", + context = "api/certificate-mgt/v1.0/admin/certificates", + tags = {"devicemgt_admin"}) + @Api(value = "Certificate Management", description = "This API carries all certificate management related operations " + "such as get all the available devices, etc.") @Path("/admin/certificates") @@ -72,7 +77,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n Server error occurred while adding certificates.", response = ErrorResponse.class) }) - @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"}) + @Scope(key = "certificate:manage", name = "Add certificates", description = "") Response addCertificate( @ApiParam( name = "enrollmentCertificates", @@ -130,7 +135,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving information requested certificate.", response = ErrorResponse.class) }) - @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + @Scope(key = "certificate:view", name = "View certificates", description = "") Response getCertificate( @ApiParam(name = "serialNumber", value = "Provide the serial number of the certificate that you wish to get the details of", @@ -202,7 +207,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving all certificates enrolled in the system.", response = ErrorResponse.class) }) - @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"}) + @Scope(key = "certificate:view", name = "View certificates", description = "") Response getAllCertificates( @ApiParam( name = "offset", @@ -245,7 +250,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n " + "Server error occurred while removing the certificate.", response = ErrorResponse.class)}) - @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"}) + @Scope(key = "certificate:manage", name = "Add certificates", description = "") Response removeCertificate( @ApiParam( name = "serialNumber", diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java index d9d074c70b..f3c454bda5 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java @@ -6,15 +6,14 @@ import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.CertificateManagementAdmin import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse; -import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.DeviceMgtAPIUtils; +import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.CertificateMgtAPIUtils; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.util.RequestValidationUtil; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import javax.ws.rs.*; import javax.ws.rs.core.Response; @@ -38,7 +37,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem CertificateManagementService certificateService; List certificates = new ArrayList<>(); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate; - certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) { certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); @@ -70,7 +69,7 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem @HeaderParam("If-Modified-Since") String ifModifiedSince) { RequestValidationUtil.validateSerialNumber(serialNumber); - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); List certificateResponse; try { certificateResponse = certificateService.searchCertificates(serialNumber); @@ -96,11 +95,9 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem @QueryParam("limit") int limit, @HeaderParam("If-Modified-Since") String ifModifiedSince) { RequestValidationUtil.validatePaginationInfo(offset, limit); - - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); - PaginationRequest paginationRequest = new PaginationRequest(offset, limit); + CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { - PaginationResult result = certificateService.getAllCertificates(paginationRequest); + PaginationResult result = certificateService.getAllCertificates(offset, limit); CertificateList certificates = new CertificateList(); certificates.setCount(result.getRecordsTotal()); certificates.setList((List) result.getData()); @@ -118,15 +115,18 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem public Response removeCertificate(@PathParam("serialNumber") String serialNumber) { RequestValidationUtil.validateSerialNumber(serialNumber); - CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService(); + CertificateManagementService certificateService = CertificateMgtAPIUtils.getCertificateManagementService(); try { boolean status = certificateService.removeCertificate(serialNumber); if (!status) { - Response.status(Response.Status.NOT_FOUND).entity("No certificate is found with the given " + - "serial number '" + serialNumber + "'"); + return Response.status(Response.Status.NOT_FOUND).entity( + "No certificate is found with the given " + + "serial number '" + serialNumber + "'").build(); + } else { + return Response.status(Response.Status.OK).entity( + "Certificate that carries the serial number '" + + serialNumber + "' has been removed").build(); } - return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" + - serialNumber + "' has been removed").build(); } catch (CertificateManagementException e) { String msg = "Error occurred while converting PEM file to X509Certificate"; log.error(msg, e); @@ -135,4 +135,4 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem } } -} +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/CertificateMgtAPIUtils.java similarity index 92% rename from components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java rename to components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/CertificateMgtAPIUtils.java index 4419bcf79a..a96b013b7b 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/DeviceMgtAPIUtils.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/util/CertificateMgtAPIUtils.java @@ -27,12 +27,12 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; import javax.ws.rs.core.MediaType; /** - * DMAPIUtils class provides utility function used by CDM REST-API classes. + * CertificateMgtAPIUtils class provides utility functions used by Certificate Mgt REST-API classes. */ -public class DeviceMgtAPIUtils { +public class CertificateMgtAPIUtils { public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE; - private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class); + private static Log log = LogFactory.getLog(CertificateMgtAPIUtils.class); public static CertificateManagementService getCertificateManagementService() { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml index a22b8681cd..68a07fcb86 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -44,7 +44,7 @@ - + diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java index 4329a1523f..f7ce3b3aae 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateConfigurationManager.java @@ -34,11 +34,11 @@ import java.io.File; */ public class CertificateConfigurationManager { - private CertificateManagementConfig currentPolicyConfig; + private CertificateManagementConfig certificateManagementConfig; private static CertificateConfigurationManager certificateConfigurationManager; - private final String deviceMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + - CertificateManagementConstants.DEVICE_CONFIG_XML_NAME; + private final String certMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + File.separator + + CertificateManagementConstants.CERTIFICATE_CONFIG_XML_FILE; public static CertificateConfigurationManager getInstance() { if (certificateConfigurationManager == null) { @@ -53,24 +53,36 @@ public class CertificateConfigurationManager { public synchronized void initConfig() throws CertificateManagementException { try { - File deviceMgtConfig = new File(deviceMgtConfigXMLPath); - Document doc = CertificateManagerUtil.convertToDocument(deviceMgtConfig); + File certMgtConfig = new File(certMgtConfigXMLPath); + Document doc = CertificateManagerUtil.convertToDocument(certMgtConfig); - /* Un-marshaling Device Management configuration */ + /* Un-marshaling Certificate Management configuration */ JAXBContext rssContext = JAXBContext.newInstance(CertificateManagementConfig.class); Unmarshaller unmarshaller = rssContext.createUnmarshaller(); - this.currentPolicyConfig = (CertificateManagementConfig) unmarshaller.unmarshal(doc); + this.certificateManagementConfig = (CertificateManagementConfig) unmarshaller.unmarshal(doc); } catch (Exception e) { - throw new CertificateManagementException("Error occurred while initializing device config", e); + throw new CertificateManagementException("Error occurred while initializing certificate config", e); } } - public CertificateManagementConfig getPolicyManagementConfig() { - return currentPolicyConfig; + public CertificateManagementConfig getCertificateManagementConfig() throws CertificateManagementException { + if (certificateManagementConfig == null) { + initConfig(); + } + return certificateManagementConfig; } - public DataSourceConfig getDataSourceConfig() { - return currentPolicyConfig.getCertificateManagementRepository().getDataSourceConfig(); + public DataSourceConfig getDataSourceConfig() throws CertificateManagementException { + if (certificateManagementConfig == null) { + initConfig(); + } + return certificateManagementConfig.getCertificateManagementRepository().getDataSourceConfig(); } -} + public CertificateKeystoreConfig getCertificateKeyStoreConfig() throws CertificateManagementException { + if (certificateManagementConfig == null) { + initConfig(); + } + return certificateManagementConfig.getCertificateKeystoreConfig(); + } +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateKeystoreConfig.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateKeystoreConfig.java new file mode 100644 index 0000000000..249b0ce478 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateKeystoreConfig.java @@ -0,0 +1,107 @@ +/* + * 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.certificate.mgt.core.config; + +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Class for holding CertificateKeystore data. + */ +@XmlRootElement(name = "CertificateKeystore") +public class CertificateKeystoreConfig { + + private String certificateKeystoreLocation; + private String certificateKeystoreType; + private String certificateKeystorePassword; + private String caCertAlias; + private String caPrivateKeyPassword; + private String raCertAlias; + private String raPrivateKeyPassword; + + @XmlElement(name = "CertificateKeystoreLocation", required = true) + public String getCertificateKeystoreLocation() { + return certificateKeystoreLocation; + } + + public void setCertificateKeystoreLocation(String certificateKeystoreLocation) { + if (certificateKeystoreLocation != null && certificateKeystoreLocation.toLowerCase(). + contains(CertificateManagementConstants.CARBON_HOME_ENTRY)) { + certificateKeystoreLocation = certificateKeystoreLocation.replace(CertificateManagementConstants.CARBON_HOME_ENTRY, + System.getProperty(CertificateManagementConstants.CARBON_HOME)); + } + this.certificateKeystoreLocation = certificateKeystoreLocation; + } + + @XmlElement(name = "CertificateKeystoreType", required = true) + public String getCertificateKeystoreType() { + return certificateKeystoreType; + } + + public void setCertificateKeystoreType(String certificateKeystoreType) { + this.certificateKeystoreType = certificateKeystoreType; + } + + @XmlElement(name = "CertificateKeystorePassword", required = true) + public String getCertificateKeystorePassword() { + return certificateKeystorePassword; + } + + public void setCertificateKeystorePassword(String certificateKeystorePassword) { + this.certificateKeystorePassword = certificateKeystorePassword; + } + + @XmlElement(name = "CACertAlias", required = true) + public String getCACertAlias() { + return caCertAlias; + } + + public void setCACertAlias(String caCertAlias) { + this.caCertAlias = caCertAlias; + } + + @XmlElement(name = "CAPrivateKeyPassword", required = true) + public String getCAPrivateKeyPassword() { + return caPrivateKeyPassword; + } + + public void setCAPrivateKeyPassword(String caPrivateKeyPassword) { + this.caPrivateKeyPassword = caPrivateKeyPassword; + } + + @XmlElement(name = "RACertAlias", required = true) + public String getRACertAlias() { + return raCertAlias; + } + + public void setRACertAlias(String raCertAlias) { + this.raCertAlias = raCertAlias; + } + + @XmlElement(name = "RAPrivateKeyPassword", required = true) + public String getRAPrivateKeyPassword() { + return raPrivateKeyPassword; + } + + public void setRAPrivateKeyPassword(String raPrivateKeyPassword) { + this.raPrivateKeyPassword = raPrivateKeyPassword; + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementConfig.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementConfig.java index e778b1757c..cc85c2bbf6 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementConfig.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementConfig.java @@ -22,20 +22,39 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Represents Device Mgt configuration. + * Represents Certificate Mgt configuration. */ -@XmlRootElement(name = "DeviceMgtConfiguration") +@XmlRootElement(name = "CertificateConfigurations") public final class CertificateManagementConfig { + private CertificateManagementRepository certificateManagementRepository; + private CertificateKeystoreConfig certificateKeystoreConfig; + private int defaultPageSize; + public void setCertificateManagementRepository(CertificateManagementRepository certificateManagementRepository) { this.certificateManagementRepository = certificateManagementRepository; } - private CertificateManagementRepository certificateManagementRepository; - - @XmlElement(name = "ManagementRepository", nillable = false) + @XmlElement(name = "ManagementRepository", required = true) public CertificateManagementRepository getCertificateManagementRepository() { return certificateManagementRepository; } + @XmlElement(name = "CertificateKeystore", required = true) + public CertificateKeystoreConfig getCertificateKeystoreConfig() { + return certificateKeystoreConfig; + } + + public void setCertificateKeystoreConfig(CertificateKeystoreConfig certificateKeystoreConfig) { + this.certificateKeystoreConfig = certificateKeystoreConfig; + } + + @XmlElement(name = "DefaultPageSize", required = true) + public int getDefaultPageSize() { + return defaultPageSize; + } + + public void setDefaultPageSize(int defaultPageSize) { + this.defaultPageSize = defaultPageSize; + } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementRepository.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementRepository.java index 86cb11e29e..b8a07779e0 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementRepository.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/config/CertificateManagementRepository.java @@ -24,14 +24,14 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** - * Class for holding management repository data + * Class for holding management repository data. */ @XmlRootElement(name = "ManagementRepository") public class CertificateManagementRepository { private DataSourceConfig dataSourceConfig; - @XmlElement(name = "DataSourceConfiguration", nillable = false) + @XmlElement(name = "DataSourceConfiguration", required = true) public DataSourceConfig getDataSourceConfig() { return dataSourceConfig; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java index 1895c14491..cb97cf8892 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java @@ -20,8 +20,7 @@ package org.wso2.carbon.certificate.mgt.core.dao; import org.wso2.carbon.certificate.mgt.core.bean.Certificate; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; import java.util.List; @@ -55,12 +54,13 @@ public interface CertificateDAO { /** * Get all the certificates in a paginated manner. * - * @param request Request mentioning pagination details such as length and stating index. + * @param rowNum Stating index of the paginated result. + * @param limit Number of records to return. * @return Pagination result with data and the count of results. * @throws CertificateManagementDAOException * */ - PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementDAOException; + PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException; /** * Get all the certificates. @@ -69,7 +69,7 @@ public interface CertificateDAO { * @throws CertificateManagementDAOException * */ - public List getAllCertificates() throws CertificateManagementDAOException; + List getAllCertificates() throws CertificateManagementDAOException; /** * Delete a certificate identified by a serial number() @@ -79,6 +79,6 @@ public interface CertificateDAO { */ boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException; - public List searchCertificate(String serialNumber) throws CertificateManagementDAOException; + List searchCertificate(String serialNumber) throws CertificateManagementDAOException; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java index b87a4af218..5c82ea83a3 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateManagementDAOFactory.java @@ -23,9 +23,13 @@ import org.apache.commons.logging.LogFactory; import org.wso2.carbon.certificate.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.certificate.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.certificate.mgt.core.dao.impl.GenericCertificateDAOImpl; -import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; -import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; -import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.certificate.mgt.core.dao.impl.OracleCertificateDAOImpl; +import org.wso2.carbon.certificate.mgt.core.dao.impl.PostgreSQLCertificateDAOImpl; +import org.wso2.carbon.certificate.mgt.core.dao.impl.SQLServerCertificateDAOImpl; +import org.wso2.carbon.certificate.mgt.core.exception.IllegalTransactionStateException; +import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException; +import org.wso2.carbon.certificate.mgt.core.exception.UnsupportedDatabaseEngineException; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; import javax.sql.DataSource; import java.sql.Connection; @@ -45,9 +49,23 @@ public class CertificateManagementDAOFactory { CONNECTION_NOT_BORROWED, CONNECTION_BORROWED, CONNECTION_CLOSED } - public static CertificateDAO getCertificateDAO() { - return new GenericCertificateDAOImpl(); + if (databaseEngine != null) { + switch (databaseEngine) { + case CertificateManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleCertificateDAOImpl(); + case CertificateManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerCertificateDAOImpl(); + case CertificateManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLCertificateDAOImpl(); + case CertificateManagementConstants.DataBaseTypes.DB_TYPE_H2: + case CertificateManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericCertificateDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); } public static void init(DataSourceConfig config) { @@ -72,8 +90,8 @@ public class CertificateManagementDAOFactory { Connection conn = currentConnection.get(); if (conn != null) { throw new IllegalTransactionStateException("A transaction is already active within the context of " + - "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + - "transaction is already active is a sign of improper transaction handling"); + "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " + + "transaction is already active is a sign of improper transaction handling"); } try { conn = dataSource.getConnection(); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java new file mode 100644 index 0000000000..4af136c987 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -0,0 +1,223 @@ +/* + * 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.certificate.mgt.core.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.bean.Certificate; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.util.Serializer; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the generic implementation of CertificateDAO which can be used to support ANSI db syntax. + */ +public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ + + private static final Log log = LogFactory.getLog(GenericCertificateDAOImpl.class); + + @Override + public void addCertificate(List certificates) + throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement( + "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)" + + " VALUES (?,?,?,?)"); + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext. + getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + for (Certificate certificate : certificates) { + // the serial number of the certificate used for its creation is set as its alias. + String serialNumber = certificate.getSerial(); + if (serialNumber == null || serialNumber.isEmpty()) { + serialNumber = String.valueOf(certificate.getCertificate().getSerialNumber()); + } + byte[] bytes = Serializer.serialize(certificate.getCertificate()); + + stmt.setString(1, serialNumber); + stmt.setBytes(2, bytes); + stmt.setInt(3, certificate.getTenantId()); + stmt.setString(4, username); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException | IOException e) { + throw new CertificateManagementDAOException("Error occurred while saving certificates. " + , e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, null); + } + } + + @Override + public CertificateResponse retrieveCertificate(String serialNumber) + throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = + "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM" + + " DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ? AND TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setString(1, serialNumber); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setCertificate(certificateBytes); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + } + } catch (SQLException e) { + String errorMsg = + "Unable to get the read the certificate with serial" + serialNumber; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return certificateResponse; + } + + @Override + public List searchCertificate(String serialNumber) + throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse = null; + List certificates = new ArrayList<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = + "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM DM_DEVICE_CERTIFICATE " + + "WHERE SERIAL_NUMBER LIKE ? AND TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setString(1, "%" + serialNumber + "%"); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + } catch (SQLException e) { + String errorMsg = + "Unable to get the read the certificate with serial" + serialNumber; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return certificates; + } + + @Override + public List getAllCertificates() throws CertificateManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse; + List certificates = new ArrayList<>(); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + Connection conn = this.getConnection(); + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME" + + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + resultSet = stmt.executeQuery(); + + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + } + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return certificates; + } + + @Override + public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + conn = this.getConnection(); + String query = + "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + + " AND TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setString(1, serialNumber); + stmt.setInt(2, tenantId); + + return stmt.executeUpdate() > 0; + } catch (SQLException e) { + String msg = "Unable to get the read the certificate with serial" + serialNumber; + log.error(msg, e); + throw new CertificateManagementDAOException(msg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + } + + private Connection getConnection() throws SQLException { + return CertificateManagementDAOFactory.getConnection(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java index 13543d66b6..0ec076da44 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/GenericCertificateDAOImpl.java @@ -20,149 +20,36 @@ package org.wso2.carbon.certificate.mgt.core.dao.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.bean.Certificate; -import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; -import org.wso2.carbon.certificate.mgt.core.util.CertificateManagerUtil; -import org.wso2.carbon.certificate.mgt.core.util.Serializer; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -public class GenericCertificateDAOImpl implements CertificateDAO { +/** + * This class holds the generic implementation of CertificateDAO which can be used to support ANSI db syntax for pagination + * queries. + */ +public class GenericCertificateDAOImpl extends AbstractCertificateDAOImpl { private static final Log log = LogFactory.getLog(GenericCertificateDAOImpl.class); - @Override - public void addCertificate(List certificates) - throws CertificateManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - try { - conn = this.getConnection(); - stmt = conn.prepareStatement( - "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID, USERNAME)" - + " VALUES (?,?,?,?)"); - PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext. - getThreadLocalCarbonContext(); - String username = threadLocalCarbonContext.getUsername(); - for (Certificate certificate : certificates) { - // the serial number of the certificate used for its creation is set as its alias. - String serialNumber = certificate.getSerial(); - if (serialNumber == null || serialNumber.isEmpty()) { - serialNumber = String.valueOf(certificate.getCertificate().getSerialNumber()); - } - byte[] bytes = Serializer.serialize(certificate.getCertificate()); - stmt.setString(1, serialNumber); - stmt.setBytes(2, bytes); - stmt.setInt(3, certificate.getTenantId()); - stmt.setString(4, username); - stmt.addBatch(); - } - stmt.executeBatch(); - } catch (SQLException | IOException e) { - throw new CertificateManagementDAOException("Error occurred while saving certificates. " - , e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, null); - } + private Connection getConnection() throws SQLException { + return CertificateManagementDAOFactory.getConnection(); } @Override - public CertificateResponse retrieveCertificate(String serialNumber) - throws CertificateManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet resultSet = null; - CertificateResponse certificateResponse = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - conn = this.getConnection(); - String query = - "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM" - + " DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ? AND TENANT_ID = ? "; - stmt = conn.prepareStatement(query); - stmt.setString(1, serialNumber); - stmt.setInt(2, tenantId); - resultSet = stmt.executeQuery(); - - if (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setCertificate(certificateBytes); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - } - } catch (SQLException e) { - String errorMsg = - "Unable to get the read the certificate with serial" + serialNumber; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); - } - return certificateResponse; - } - - @Override - public List searchCertificate(String serialNumber) - throws CertificateManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet resultSet = null; - CertificateResponse certificateResponse = null; - List certificates = new ArrayList<>(); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - conn = this.getConnection(); - String query = - "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM DM_DEVICE_CERTIFICATE " - + "WHERE SERIAL_NUMBER LIKE ? AND TENANT_ID = ? "; - stmt = conn.prepareStatement(query); - stmt.setString(1, "%" + serialNumber + "%"); - stmt.setInt(2, tenantId); - resultSet = stmt.executeQuery(); - - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - } catch (SQLException e) { - String errorMsg = - "Unable to get the read the certificate with serial" + serialNumber; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); - } - return certificates; - } - - @Override - public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementDAOException { + public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { PreparedStatement stmt = null; ResultSet resultSet = null; CertificateResponse certificateResponse; @@ -172,11 +59,11 @@ public class GenericCertificateDAOImpl implements CertificateDAO { try { Connection conn = this.getConnection(); String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " - + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; + + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ?,?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); - stmt.setInt(2, request.getStartIndex()); - stmt.setInt(3, request.getRowCount()); + stmt.setInt(2, rowNum); + stmt.setInt(3, limit); resultSet = stmt.executeQuery(); int resultCount = 0; @@ -202,67 +89,4 @@ public class GenericCertificateDAOImpl implements CertificateDAO { } return paginationResult; } - - @Override - public List getAllCertificates() throws CertificateManagementDAOException { - PreparedStatement stmt = null; - ResultSet resultSet = null; - CertificateResponse certificateResponse; - List certificates = new ArrayList<>(); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - Connection conn = this.getConnection(); - String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME" - + " FROM DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC"; - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - resultSet = stmt.executeQuery(); - - while (resultSet.next()) { - certificateResponse = new CertificateResponse(); - byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); - certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); - certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); - certificateResponse.setUsername(resultSet.getString("USERNAME")); - CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); - certificates.add(certificateResponse); - } - } catch (SQLException e) { - String errorMsg = "SQL error occurred while retrieving the certificates."; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); - } - return certificates; - } - - @Override - public boolean removeCertificate(String serialNumber) throws CertificateManagementDAOException { - Connection conn; - PreparedStatement stmt = null; - ResultSet resultSet = null; - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - try { - conn = this.getConnection(); - String query = - "DELETE FROM DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ?" + - " AND TENANT_ID = ? "; - stmt = conn.prepareStatement(query); - stmt.setString(1, serialNumber); - stmt.setInt(2, tenantId); - - return stmt.executeUpdate() > 0; - } catch (SQLException e) { - String msg = "Unable to get the read the certificate with serial" + serialNumber; - log.error(msg, e); - throw new CertificateManagementDAOException(msg, e); - } finally { - CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); - } - } - - private Connection getConnection() throws SQLException { - return CertificateManagementDAOFactory.getConnection(); - } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java new file mode 100644 index 0000000000..69e61138bb --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/OracleCertificateDAOImpl.java @@ -0,0 +1,91 @@ +/* + * 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.certificate.mgt.core.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the oracle sql implementation of CertificateDAO which can be used to support Oracle specific + * db syntax. + */ +public class OracleCertificateDAOImpl extends AbstractCertificateDAOImpl { + + private static final Log log = LogFactory.getLog(OracleCertificateDAOImpl.class); + + @Override + public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse; + List certificates = new ArrayList<>(); + PaginationResult paginationResult; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + Connection conn = this.getConnection(); + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC WHERE OFFSET >= ? AND ROWNUM <= ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, rowNum); + stmt.setInt(3, limit); + resultSet = stmt.executeQuery(); + + int resultCount = 0; + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + resultCount++; + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(resultCount); + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return paginationResult; + } + + private Connection getConnection() throws SQLException { + return CertificateManagementDAOFactory.getConnection(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java new file mode 100644 index 0000000000..bc894b7462 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/PostgreSQLCertificateDAOImpl.java @@ -0,0 +1,91 @@ +/* + * 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.certificate.mgt.core.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the PostgreSQL implementation of CertificateDAO which can be used to support PostgreSQL specific + * db syntax. + */ +public class PostgreSQLCertificateDAOImpl extends AbstractCertificateDAOImpl { + + private static final Log log = LogFactory.getLog(PostgreSQLCertificateDAOImpl.class); + + @Override + public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse; + List certificates = new ArrayList<>(); + PaginationResult paginationResult; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + Connection conn = this.getConnection(); + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC LIMIT ? OFFSET ?"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, limit); + stmt.setInt(3, rowNum); + resultSet = stmt.executeQuery(); + + int resultCount = 0; + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + resultCount++; + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(resultCount); + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return paginationResult; + } + + private Connection getConnection() throws SQLException { + return CertificateManagementDAOFactory.getConnection(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java new file mode 100644 index 0000000000..3504fd4a9a --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/SQLServerCertificateDAOImpl.java @@ -0,0 +1,91 @@ +/* + * 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.certificate.mgt.core.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; +import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; +import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; +import org.wso2.carbon.certificate.mgt.core.service.PaginationResult; +import org.wso2.carbon.context.PrivilegedCarbonContext; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the SQLServer implementation of CertificateDAO which can be used to support SQLServer specific + * db syntax. + */ +public class SQLServerCertificateDAOImpl extends AbstractCertificateDAOImpl { + + private static final Log log = LogFactory.getLog(SQLServerCertificateDAOImpl.class); + + @Override + public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementDAOException { + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse; + List certificates = new ArrayList<>(); + PaginationResult paginationResult; + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + try { + Connection conn = this.getConnection(); + String sql = "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM " + + "DM_DEVICE_CERTIFICATE WHERE TENANT_ID = ? ORDER BY ID DESC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, rowNum); + stmt.setInt(3, limit); + resultSet = stmt.executeQuery(); + + int resultCount = 0; + while (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + certificates.add(certificateResponse); + resultCount++; + } + paginationResult = new PaginationResult(); + paginationResult.setData(certificates); + paginationResult.setRecordsTotal(resultCount); + } catch (SQLException e) { + String errorMsg = "SQL error occurred while retrieving the certificates."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return paginationResult; + } + + private Connection getConnection() throws SQLException { + return CertificateManagementDAOFactory.getConnection(); + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/IllegalTransactionStateException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/IllegalTransactionStateException.java new file mode 100644 index 0000000000..b175c8ce11 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/IllegalTransactionStateException.java @@ -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. + */ +package org.wso2.carbon.certificate.mgt.core.exception; + +public class IllegalTransactionStateException extends RuntimeException { + + private static final long serialVersionUID = -3151279331929070297L; + + public IllegalTransactionStateException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public IllegalTransactionStateException(String message, Throwable cause) { + super(message, cause); + } + + public IllegalTransactionStateException(String msg) { + super(msg); + } + + public IllegalTransactionStateException() { + super(); + } + + public IllegalTransactionStateException(Throwable cause) { + super(cause); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/TransactionManagementException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/TransactionManagementException.java new file mode 100644 index 0000000000..eb131b98c6 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/TransactionManagementException.java @@ -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. + */ +package org.wso2.carbon.certificate.mgt.core.exception; + +public class TransactionManagementException extends Exception { + + private static final long serialVersionUID = -3151279321929070297L; + + public TransactionManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public TransactionManagementException(String message, Throwable cause) { + super(message, cause); + } + + public TransactionManagementException(String msg) { + super(msg); + } + + public TransactionManagementException() { + super(); + } + + public TransactionManagementException(Throwable cause) { + super(cause); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/UnsupportedDatabaseEngineException.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/UnsupportedDatabaseEngineException.java new file mode 100644 index 0000000000..12bba7afc9 --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/exception/UnsupportedDatabaseEngineException.java @@ -0,0 +1,48 @@ +/* + * 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.certificate.mgt.core.exception; + +/** + * This runtime exception will be thrown if the server has configured with unsupported DB engine. + */ +public class UnsupportedDatabaseEngineException extends RuntimeException { + + private static final long serialVersionUID = -3151279311929070297L; + + public UnsupportedDatabaseEngineException(String msg, Exception nestedEx) { + super(msg, nestedEx); + } + + public UnsupportedDatabaseEngineException(String message, Throwable cause) { + super(message, cause); + } + + public UnsupportedDatabaseEngineException(String msg) { + super(msg); + } + + public UnsupportedDatabaseEngineException() { + super(); + } + + public UnsupportedDatabaseEngineException(Throwable cause) { + super(cause); + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 92bf568dba..854d88794a 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -46,14 +46,7 @@ import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.Store; -import org.jscep.message.CertRep; -import org.jscep.message.MessageDecodingException; -import org.jscep.message.MessageEncodingException; -import org.jscep.message.PkcsPkiEnvelopeDecoder; -import org.jscep.message.PkcsPkiEnvelopeEncoder; -import org.jscep.message.PkiMessage; -import org.jscep.message.PkiMessageDecoder; -import org.jscep.message.PkiMessageEncoder; +import org.jscep.message.*; import org.jscep.transaction.FailInfo; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; @@ -64,39 +57,19 @@ import org.wso2.carbon.certificate.mgt.core.dto.CAStatus; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; import org.wso2.carbon.certificate.mgt.core.util.CommonUtil; -import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil; import org.wso2.carbon.certificate.mgt.core.util.Serializer; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.TransactionManagementException; import javax.security.auth.x500.X500Principal; import javax.xml.bind.DatatypeConverter; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.SignatureException; +import java.security.*; import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; +import java.security.cert.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; @@ -108,6 +81,45 @@ public class CertificateGenerator { private static final Log log = LogFactory.getLog(CertificateGenerator.class); + public static String getCommonName(X509Certificate requestCertificate) { + String distinguishedName = requestCertificate.getSubjectDN().getName(); + if (distinguishedName != null && !distinguishedName.isEmpty()) { + String[] dnSplits = distinguishedName.split(","); + for (String dnSplit : dnSplits) { + if (dnSplit.contains("CN=")) { + String[] cnSplits = dnSplit.split("="); + if (cnSplits[1] != null) { + return cnSplits[1]; + } + } + } + } + return null; + } + + public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) + throws CertificateManagementDAOException { + try { + if (certificateBytes != null) { + java.security.cert.Certificate x509Certificate = + (java.security.cert.Certificate) Serializer.deserialize(certificateBytes); + if (x509Certificate instanceof X509Certificate) { + X509Certificate certificate = (X509Certificate) x509Certificate; + certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); + certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); + certificateResponse.setCertificateserial(certificate.getSerialNumber()); + certificateResponse.setIssuer(certificate.getIssuerDN().getName()); + certificateResponse.setSubject(certificate.getSubjectDN().getName()); + certificateResponse.setCertificateVersion(certificate.getVersion()); + } + } + } catch (ClassNotFoundException | IOException e) { + String errorMsg = "Error while deserializing the certificate."; + throw new CertificateManagementDAOException(errorMsg, e); + } + + } + public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException { if (ca == null) { @@ -123,7 +135,7 @@ public class CertificateGenerator { InputStream raInputStream = null; try { - CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509); + CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509); caInputStream = new ByteArrayInputStream(ca); raInputStream = new ByteArrayInputStream(ra); @@ -134,7 +146,6 @@ public class CertificateGenerator { certificateList.add(raCert); } catch (CertificateException e) { String errorMsg = "Error occurred while fetching root certificates"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { if (caInputStream != null) { @@ -167,19 +178,19 @@ public class CertificateGenerator { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance( - ConfigurationUtil.RSA, ConfigurationUtil.PROVIDER); - keyPairGenerator.initialize(ConfigurationUtil.RSA_KEY_LENGTH, new SecureRandom()); + CertificateManagementConstants.RSA, CertificateManagementConstants.PROVIDER); + keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom()); KeyPair pair = keyPairGenerator.generateKeyPair(); - X500Principal principal = new X500Principal(ConfigurationUtil.DEFAULT_PRINCIPAL); + X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( principal, CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal, pair.getPublic()); - ContentSigner contentSigner = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA) - .setProvider(ConfigurationUtil.PROVIDER).build( + ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) + .setProvider(CertificateManagementConstants.PROVIDER).build( pair.getPrivate()); X509Certificate certificate = new JcaX509CertificateConverter() - .setProvider(ConfigurationUtil.PROVIDER).getCertificate( + .setProvider(CertificateManagementConstants.PROVIDER).getCertificate( certificateBuilder.build(contentSigner)); // cert.checkValidity(); @@ -197,35 +208,27 @@ public class CertificateGenerator { return certificate; } catch (NoSuchAlgorithmException e) { String errorMsg = "No such algorithm found when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchProviderException e) { String errorMsg = "No such provider found when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (OperatorCreationException e) { String errorMsg = "Issue in operator creation when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateExpiredException e) { String errorMsg = "Certificate expired after generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateNotYetValidException e) { String errorMsg = "Certificate not yet valid when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (InvalidKeyException e) { String errorMsg = "Invalid key used when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (SignatureException e) { String errorMsg = "Signature related issue occurred when generating certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -244,7 +247,7 @@ public class CertificateGenerator { X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate(); X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); - CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509); + CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream); @@ -273,7 +276,7 @@ public class CertificateGenerator { certRep = new CertRep(transId, senderNonce, recipientNonce, messageData); } - PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, ConfigurationUtil.DES_EDE); + PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, CertificateManagementConstants.DES_EDE); PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder); CMSSignedData cmsSignedData = encoder.encode(certRep); @@ -281,23 +284,18 @@ public class CertificateGenerator { } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating getPKIMessage"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (MessageEncodingException e) { String errorMsg = "Message encoding issue occurred when generating getPKIMessage"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred when generating getPKIMessage"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (MessageDecodingException e) { String errorMsg = "Message decoding issue occurred when generating getPKIMessage"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "CMS issue occurred when generating getPKIMessage"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -333,22 +331,6 @@ public class CertificateGenerator { return lookUpCertificate; } - public static String getCommonName(X509Certificate requestCertificate) { - String distinguishedName = requestCertificate.getSubjectDN().getName(); - if (distinguishedName != null && !distinguishedName.isEmpty()) { - String[] dnSplits = distinguishedName.split(","); - for (String dnSplit : dnSplits) { - if (dnSplit.contains("CN=")) { - String[] cnSplits = dnSplit.split("="); - if (cnSplits[1] != null) { - return cnSplits[1]; - } - } - } - } - return null; - } - public X509Certificate pemToX509Certificate(String pem) throws KeystoreException { InputStream inputStream = null; @@ -389,7 +371,7 @@ public class CertificateGenerator { Collection reqCerts = reqStore.getMatches(null); if (reqCerts != null && reqCerts.size() > 0) { - CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509); + CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) certificateFactory. @@ -399,7 +381,7 @@ public class CertificateGenerator { Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias( reqCert.getSerialNumber().toString()); - if (lookUpCertificate != null && (lookUpCertificate instanceof X509Certificate)) { + if (lookUpCertificate instanceof X509Certificate) { return (X509Certificate) lookUpCertificate; } } @@ -407,15 +389,12 @@ public class CertificateGenerator { } } catch (CMSException e) { String errorMsg = "CMSException when decoding certificate signature"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "IOException when decoding certificate signature"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "CertificateException when decoding certificate signature"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } @@ -431,7 +410,7 @@ public class CertificateGenerator { Date validityBeginDate = commonUtil.getValidityStartDate(); Date validityEndDate = commonUtil.getValidityEndDate(); - X500Name certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL); + X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL); //X500Name certSubject = request.getSubject(); Attribute attributes[] = request.getAttributes(); @@ -490,10 +469,10 @@ public class CertificateGenerator { } } - sigGen = new JcaContentSignerBuilder(ConfigurationUtil.SHA256_RSA) - .setProvider(ConfigurationUtil.PROVIDER).build(privateKey); + sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA) + .setProvider(CertificateManagementConstants.PROVIDER).build(privateKey); issuedCert = new JcaX509CertificateConverter().setProvider( - ConfigurationUtil.PROVIDER).getCertificate( + CertificateManagementConstants.PROVIDER).getCertificate( certificateBuilder.build(sigGen)); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); @@ -504,15 +483,12 @@ public class CertificateGenerator { saveCertInKeyStore(certificates); } catch (CertIOException e) { String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (OperatorCreationException e) { String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } @@ -543,11 +519,9 @@ public class CertificateGenerator { return generator.generate(new CMSAbsentContent()); } catch (CertificateEncodingException e) { String errorMsg = "Certificate encoding issue occurred when generating getMessageData"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "Message decoding issue occurred when generating getMessageData"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -566,30 +540,26 @@ public class CertificateGenerator { String temp = new String(keyBytes); String privateKeyPEM = temp.replace( - ConfigurationUtil.RSA_PRIVATE_KEY_BEGIN_TEXT, ConfigurationUtil.EMPTY_TEXT); + CertificateManagementConstants.RSA_PRIVATE_KEY_BEGIN_TEXT, CertificateManagementConstants.EMPTY_TEXT); privateKeyPEM = privateKeyPEM - .replace(ConfigurationUtil.RSA_PRIVATE_KEY_END_TEXT, ConfigurationUtil.EMPTY_TEXT); + .replace(CertificateManagementConstants.RSA_PRIVATE_KEY_END_TEXT, CertificateManagementConstants.EMPTY_TEXT); byte[] decoded = Base64.decodeBase64(privateKeyPEM); PKCS8EncodedKeySpec encodedKeySpec = new PKCS8EncodedKeySpec(decoded); - KeyFactory keyFactory = KeyFactory.getInstance(ConfigurationUtil.RSA); + KeyFactory keyFactory = KeyFactory.getInstance(CertificateManagementConstants.RSA); return keyFactory.generatePrivate(encodedKeySpec); } catch (FileNotFoundException e) { String errorMsg = "Private key file not found in getSignerKey"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue in getSignerKey"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not not found in getSignerKey"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (InvalidKeySpecException e) { String errorMsg = "Invalid key found in getSignerKey"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -598,18 +568,16 @@ public class CertificateGenerator { X509Certificate certificate; try { - CertificateFactory certificateFactory = CertificateFactory.getInstance(ConfigurationUtil.X_509); + CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509); certificate = (X509Certificate) certificateFactory.generateCertificate( new FileInputStream(signerCertificatePath)); return certificate; } catch (CertificateException e) { String errorMsg = "Certificate related issue occurred in getSigner"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (FileNotFoundException e) { String errorMsg = "Signer certificate path not found in getSigner"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -645,15 +613,12 @@ public class CertificateGenerator { return scepResponse; } catch (CertificateEncodingException e) { String errorMsg = "Certificate encoding issue occurred in getCACert"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CMSException e) { String errorMsg = "CMS issue occurred in getCACert"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred in getCACert"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } @@ -672,17 +637,14 @@ public class CertificateGenerator { CertificateManagementDAOFactory.commitTransaction(); } catch (CertificateManagementDAOException e) { String errorMsg = "Error occurred when saving the generated certificate"; - log.error(errorMsg, e); CertificateManagementDAOFactory.rollbackTransaction(); throw new KeystoreException(errorMsg, e); } catch (TransactionManagementException e) { String errorMsg = "Error occurred when saving the generated certificate"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } } - public String extractChallengeToken(X509Certificate certificate) { byte[] challengePassword = certificate.getExtensionValue( @@ -742,28 +704,4 @@ public class CertificateGenerator { return generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); } - - public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) - throws CertificateManagementDAOException { - try { - if (certificateBytes != null) { - java.security.cert.Certificate x509Certificate = - (java.security.cert.Certificate) Serializer.deserialize(certificateBytes); - if (x509Certificate instanceof X509Certificate) { - X509Certificate certificate = (X509Certificate) x509Certificate; - certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); - certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); - certificateResponse.setCertificateserial(certificate.getSerialNumber()); - certificateResponse.setIssuer(certificate.getIssuerDN().getName()); - certificateResponse.setSubject(certificate.getSubjectDN().getName()); - certificateResponse.setCertificateVersion(certificate.getVersion()); - } - } - } catch (ClassNotFoundException | IOException e) { - String errorMsg = "Error while deserializing the certificate."; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } - - } } \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java index 3faf94abb9..594ceeec9b 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java @@ -19,11 +19,13 @@ package org.wso2.carbon.certificate.mgt.core.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.config.CertificateConfigurationManager; +import org.wso2.carbon.certificate.mgt.core.config.CertificateKeystoreConfig; import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; -import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; import org.wso2.carbon.certificate.mgt.core.util.Serializer; @@ -54,28 +56,23 @@ public class KeyStoreReader { InputStream is = null; KeyStore keystore; try { - keystore = KeyStore.getInstance(ConfigurationUtil.getConfigEntry(configEntryKeyStoreType)); - is = new FileInputStream(ConfigurationUtil.getConfigEntry(configEntryKeyStorePath)); - keystore.load(is, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); + keystore = KeyStore.getInstance(configEntryKeyStoreType); + is = new FileInputStream(configEntryKeyStorePath); + keystore.load(is, configEntryKeyStorePassword.toCharArray()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (FileNotFoundException e) { String errorMsg = "KeyStore file not found when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "CertificateException when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { try { @@ -94,28 +91,22 @@ public class KeyStoreReader { String configEntryKeyStorePassword) throws KeystoreException { FileOutputStream os = null; try { - os = new FileOutputStream( - ConfigurationUtil.getConfigEntry(configEntryKeyStorePath)); - keyStore.store(os, ConfigurationUtil.getConfigEntry(configEntryKeyStorePassword).toCharArray()); + os = new FileOutputStream(configEntryKeyStorePath); + keyStore.store(os, configEntryKeyStorePassword.toCharArray()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (FileNotFoundException e) { String errorMsg = "KeyStore file not found when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "CertificateException when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "Input output issue occurred when loading KeyStore"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { try { @@ -130,23 +121,44 @@ public class KeyStoreReader { KeyStore loadCertificateKeyStore() throws KeystoreException { - return loadKeyStore(ConfigurationUtil.CERTIFICATE_KEYSTORE, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE, - ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD); + KeyStore keyStore = null; + try { + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + keyStore = loadKeyStore(certificateKeystoreConfig.getCertificateKeystoreType(), + certificateKeystoreConfig.getCertificateKeystoreLocation(), + certificateKeystoreConfig.getCertificateKeystorePassword()); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; + throw new KeystoreException(errorMsg, e); + } + return keyStore; } void saveCertificateKeyStore(KeyStore keyStore) throws KeystoreException { - saveKeyStore(keyStore, ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE, - ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD); + try { + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + saveKeyStore(keyStore, certificateKeystoreConfig.getCertificateKeystoreLocation(), + certificateKeystoreConfig.getCertificateKeystorePassword()); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; + throw new KeystoreException(errorMsg, e); + } } public Certificate getCACertificate() throws KeystoreException { KeyStore keystore = loadCertificateKeyStore(); Certificate caCertificate; try { - caCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.CA_CERT_ALIAS)); + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + caCertificate = keystore.getCertificate(certificateKeystoreConfig.getCACertAlias()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when loading KeyStore"; - log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } @@ -158,24 +170,25 @@ public class KeyStoreReader { } PrivateKey getCAPrivateKey() throws KeystoreException { - KeyStore keyStore = loadCertificateKeyStore(); PrivateKey caPrivateKey; try { - caPrivateKey = (PrivateKey) (keyStore.getKey( - ConfigurationUtil.getConfigEntry(ConfigurationUtil.CA_CERT_ALIAS), - ConfigurationUtil.getConfigEntry(ConfigurationUtil.KEYSTORE_CA_CERT_PRIV_PASSWORD).toCharArray())); + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + caPrivateKey = (PrivateKey) keyStore.getKey(certificateKeystoreConfig.getCACertAlias(), certificateKeystoreConfig + . + getCAPrivateKeyPassword().toCharArray()); } catch (UnrecoverableKeyException e) { String errorMsg = "Key is unrecoverable when retrieving CA private key"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when retrieving CA private key"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found when retrieving CA private key"; - log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } @@ -190,10 +203,14 @@ public class KeyStoreReader { KeyStore keystore = loadCertificateKeyStore(); Certificate raCertificate; try { - raCertificate = keystore.getCertificate(ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS)); + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + raCertificate = keystore.getCertificate(certificateKeystoreConfig.getRACertAlias()); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when retrieving RA private key"; - log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } @@ -214,15 +231,12 @@ public class KeyStoreReader { } } catch (CertificateManagementDAOException e) { String errorMsg = "Error when retrieving certificate the the database for the alias " + alias; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (ClassNotFoundException | IOException e) { String errorMsg = "Error when de-serializing saved certificate."; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (SQLException e) { String errorMsg = "Error when making a connection to the database."; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { CertificateManagementDAOFactory.closeConnection(); @@ -234,20 +248,21 @@ public class KeyStoreReader { KeyStore keystore = loadCertificateKeyStore(); PrivateKey raPrivateKey; try { - raPrivateKey = (PrivateKey) (keystore.getKey( - ConfigurationUtil.getConfigEntry(ConfigurationUtil.RA_CERT_ALIAS), - ConfigurationUtil.getConfigEntry(ConfigurationUtil.KEYSTORE_RA_CERT_PRIV_PASSWORD).toCharArray())); + CertificateKeystoreConfig certificateKeystoreConfig = CertificateConfigurationManager.getInstance(). + getCertificateKeyStoreConfig(); + raPrivateKey = (PrivateKey) keystore.getKey(certificateKeystoreConfig.getRACertAlias(), + certificateKeystoreConfig.getRAPrivateKeyPassword().toCharArray()); } catch (UnrecoverableKeyException e) { String errorMsg = "Key is unrecoverable when retrieving RA private key"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (KeyStoreException e) { String errorMsg = "KeyStore issue occurred when retrieving RA private key"; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Algorithm not found when retrieving RA private key"; - log.error(errorMsg, e); + throw new KeystoreException(errorMsg, e); + } catch (CertificateManagementException e) { + String errorMsg = "Unable to find KeyStore configuration in certificate-mgt.config file."; throw new KeystoreException(errorMsg, e); } @@ -274,15 +289,12 @@ public class KeyStoreReader { } catch (CertificateManagementDAOException e) { String errorMsg = "Error when retrieving certificate from the the database for the serial number: " + serialNumber; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (SQLException e) { String errorMsg = "Error when making a connection to the database."; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } catch (ClassNotFoundException | IOException e) { String errorMsg = "Error when de-serializing saved certificate."; - log.error(errorMsg, e); throw new KeystoreException(errorMsg, e); } finally { CertificateManagementDAOFactory.closeConnection(); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java index 23190294b2..82582e1b40 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/internal/CertificateManagementServiceComponent.java @@ -26,8 +26,11 @@ import org.wso2.carbon.certificate.mgt.core.config.CertificateConfigurationManag import org.wso2.carbon.certificate.mgt.core.config.CertificateManagementConfig; import org.wso2.carbon.certificate.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; +import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementServiceImpl; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; +import org.wso2.carbon.certificate.mgt.core.util.CertificateMgtSchemaInitializer; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; /** @@ -50,15 +53,25 @@ public class CertificateManagementServiceComponent { log.debug("Initializing certificate management core bundle"); } CertificateConfigurationManager.getInstance().initConfig(); - CertificateManagementConfig config = CertificateConfigurationManager.getInstance().getPolicyManagementConfig(); + CertificateManagementConfig config = CertificateConfigurationManager.getInstance().getCertificateManagementConfig(); DataSourceConfig dsConfig = config.getCertificateManagementRepository().getDataSourceConfig(); CertificateManagementDAOFactory.init(dsConfig); BundleContext bundleContext = componentContext.getBundleContext(); + + /* If -Dsetup option enabled then create Certificate management database schema */ + String setupOption = + System.getProperty(CertificateManagementConstants.SETUP_PROPERTY); + if (setupOption != null) { + if (log.isDebugEnabled()) { + log.debug("-Dsetup is enabled. Certificate management repository schema initialization is about to " + + "begin"); + } + this.setupDeviceManagementSchema(dsConfig); + } bundleContext.registerService(CertificateManagementService.class.getName(), CertificateManagementServiceImpl.getInstance(), null); - if (log.isDebugEnabled()) { log.debug("Certificate management core bundle has been successfully initialized"); } @@ -86,4 +99,19 @@ public class CertificateManagementServiceComponent { CertificateManagementDataHolder.getInstance().setDeviceManagementService(null); } + private void setupDeviceManagementSchema(DataSourceConfig config) throws CertificateManagementException { + CertificateMgtSchemaInitializer initializer = new CertificateMgtSchemaInitializer(config); + log.info("Initializing Certificate management repository database schema"); + try { + initializer.createRegistryDatabase(); + } catch (Exception e) { + throw new CertificateManagementException( + "Error occurred while initializing Certificate Management database schema", e); + } + if (log.isDebugEnabled()) { + log.debug("Certificate management metadata repository schema has been successfully initialized"); + } + } + + } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java index 04d4c8c35f..becd68720b 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java @@ -22,8 +22,6 @@ import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementExcep import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; import java.io.InputStream; import java.security.PrivateKey; @@ -54,31 +52,31 @@ public interface CertificateManagementService { boolean verifySignature(String headerSignature) throws KeystoreException; - public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException; + CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException; - public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException; + CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException; - public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException; + X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException; String extractChallengeToken(X509Certificate certificate); X509Certificate getSignedCertificateFromCSR(String binarySecurityToken) throws KeystoreException; - public CertificateResponse getCertificateBySerial(String serial) throws KeystoreException; + CertificateResponse getCertificateBySerial(String serial) throws KeystoreException; - public void saveCertificate(List certificate) + void saveCertificate(List certificate) throws KeystoreException; - public X509Certificate pemToX509Certificate(String pem) throws KeystoreException; + X509Certificate pemToX509Certificate(String pem) throws KeystoreException; - public CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; + CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementException; - public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementException; + PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException; boolean removeCertificate(String serialNumber) throws CertificateManagementException; - public List getCertificates() throws CertificateManagementException; + List getCertificates() throws CertificateManagementException; - public List searchCertificates(String serialNumber) throws CertificateManagementException; + List searchCertificates(String serialNumber) throws CertificateManagementException; } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index 26902e7248..c47472f35c 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -27,12 +27,11 @@ import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse; import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse; import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; +import org.wso2.carbon.certificate.mgt.core.exception.TransactionManagementException; import org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator; import org.wso2.carbon.certificate.mgt.core.impl.KeyStoreReader; -import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil; -import org.wso2.carbon.device.mgt.common.PaginationRequest; -import org.wso2.carbon.device.mgt.common.PaginationResult; -import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagerUtil; import java.io.InputStream; import java.security.PrivateKey; @@ -81,7 +80,7 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } public byte[] getCACapsSCEP() { - return ConfigurationUtil.POST_BODY_CA_CAPS.getBytes(); + return CertificateManagementConstants.POST_BODY_CA_CAPS.getBytes(); } public byte[] getPKIMessageSCEP(InputStream inputStream) throws KeystoreException { @@ -144,30 +143,29 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe return certificateDAO.retrieveCertificate(serialNumber); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; - log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while looking up for the certificate carrying the serial number '" + serialNumber + "' in the underlying certificate repository"; - log.error(msg, e); throw new CertificateManagementException(msg, e); } finally { CertificateManagementDAOFactory.closeConnection(); } } - public PaginationResult getAllCertificates(PaginationRequest request) throws CertificateManagementException { + @Override + public PaginationResult getAllCertificates(int rowNum, int limit) throws CertificateManagementException { try { CertificateManagementDAOFactory.openConnection(); CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); - return certificateDAO.getAllCertificates(request); + return certificateDAO.getAllCertificates(rowNum, CertificateManagerUtil.validateCertificateListPageSize(limit)); } catch (SQLException e) { String msg = "Error occurred while opening a connection to the underlying data source"; log.error(msg, e); throw new CertificateManagementException(msg, e); } catch (CertificateManagementDAOException e) { String msg = "Error occurred while looking up for the list of certificates managed in the underlying " + - "certificate repository"; + "certificate repository"; log.error(msg, e); throw new CertificateManagementException(msg, e); } finally { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/PaginationResult.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/PaginationResult.java new file mode 100644 index 0000000000..2328d9677f --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/PaginationResult.java @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.certificate.mgt.core.service; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import java.io.Serializable; +import java.util.List; + +/** + * This class holds necessary data to represent a paginated result. + */ +@ApiModel(value = "PaginationResult", description = "This class carries all information related Pagination Result") +public class PaginationResult implements Serializable { + + private static final long serialVersionUID = 1998101711L; + + @ApiModelProperty(name = "recordsTotal", value = "The total number of records that are given before filtering", required = true) + private int recordsTotal; + + @ApiModelProperty(name = "recordsFiltered", value = "The total number of records that are given after filtering", required = true) + private int recordsFiltered; + + @ApiModelProperty(name = "draw", value = "The draw counter that this object is a response to, from the draw parameter sent as part of the data request", required = true) + private int draw; + + @ApiModelProperty(name = "data", value = "This holds the db records that matches given criteria", required = true) + private List data; + + public int getRecordsTotal() { + return recordsTotal; + } + + public int getRecordsFiltered() { + return recordsFiltered; + } + + public void setRecordsFiltered(int recordsFiltered) { + this.recordsFiltered = recordsFiltered; + } + + public void setRecordsTotal(int recordsTotal) { + this.recordsTotal = recordsTotal; + + } + + public List getData() { + return data; + } + + public void setData(List data) { + this.data = data; + } + + public int getDraw() { + return draw; + } + + public void setDraw(int draw) { + this.draw = draw; + } +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java index dabeda872a..1af981f3cc 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java @@ -21,6 +21,34 @@ package org.wso2.carbon.certificate.mgt.core.util; public final class CertificateManagementConstants { - public static final String DEVICE_CONFIG_XML_NAME = "cdm-config.xml"; + public static final String CERTIFICATE_CONFIG_XML_FILE = "certificate-config.xml"; + public static final String SETUP_PROPERTY = "setup"; + public static final String CARBON_HOME = "carbon.home"; + public static final String CARBON_HOME_ENTRY = "${carbon.home}"; + public static final String PROVIDER = "BC"; + public static final String CERTIFICATE_KEYSTORE = "CertificateKeystoreType"; + public static final String RSA = "RSA"; + public static final String SHA256_RSA = "SHA256WithRSAEncryption"; + public static final String X_509 = "X.509"; + public static final String POST_BODY_CA_CAPS = "POSTPKIOperation\nSHA-1\nDES3\n"; + public static final String DES_EDE = "DESede"; + public static final String CONF_LOCATION = "conf.location"; + public static final String DEFAULT_PRINCIPAL = "O=WSO2, OU=Mobile, C=LK"; + public static final String RSA_PRIVATE_KEY_BEGIN_TEXT = "-----BEGIN RSA PRIVATE KEY-----\n"; + public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----"; + public static final String EMPTY_TEXT = ""; + public static final int RSA_KEY_LENGTH = 1024; + + public static final class DataBaseTypes { + private DataBaseTypes() { + throw new AssertionError(); + } + public static final String DB_TYPE_MYSQL = "MySQL"; + public static final String DB_TYPE_ORACLE = "Oracle"; + public static final String DB_TYPE_MSSQL = "Microsoft SQL Server"; + public static final String DB_TYPE_DB2 = "DB2"; + public static final String DB_TYPE_H2 = "H2"; + public static final String DB_TYPE_POSTGRESQL = "PostgreSQL"; + } } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java index 9f75079cfb..b24bf12f84 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagerUtil.java @@ -22,6 +22,8 @@ package org.wso2.carbon.certificate.mgt.core.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; +import org.wso2.carbon.certificate.mgt.core.config.CertificateConfigurationManager; +import org.wso2.carbon.certificate.mgt.core.config.CertificateManagementConfig; import org.wso2.carbon.certificate.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.certificate.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOUtil; @@ -88,4 +90,18 @@ public class CertificateManagerUtil { return dataSource; } -} + public static int validateCertificateListPageSize(int limit) throws CertificateManagementException { + if (limit == 0) { + CertificateManagementConfig certificateManagementConfig = CertificateConfigurationManager.getInstance(). + getCertificateManagementConfig(); + if (certificateManagementConfig != null) { + return certificateManagementConfig.getDefaultPageSize(); + } else { + throw new CertificateManagementException("Certificate-Mgt configuration has not initialized. Please check the " + + "certificate-config.xml file."); + } + } + return limit; + } + +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java new file mode 100644 index 0000000000..9386564cfe --- /dev/null +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateMgtSchemaInitializer.java @@ -0,0 +1,47 @@ +/* + * 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.certificate.mgt.core.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.certificate.mgt.core.config.datasource.DataSourceConfig; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.dbcreator.DatabaseCreator; + +import java.io.File; + +public final class CertificateMgtSchemaInitializer extends DatabaseCreator { + + private static final Log log = LogFactory.getLog(CertificateMgtSchemaInitializer.class); + private static final String setupSQLScriptBaseLocation = + CarbonUtils.getCarbonHome() + File.separator + "dbscripts" + File.separator + "certMgt" + File.separator; + + public CertificateMgtSchemaInitializer(DataSourceConfig config) { + super(CertificateManagerUtil.resolveDataSource(config)); + } + + protected String getDbScriptLocation(String databaseType) { + String scriptName = databaseType + ".sql"; + if (log.isDebugEnabled()) { + log.debug("Loading database script from :" + scriptName); + } + return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName; + } + +} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java index 6b9bc5897e..e9e59a8450 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CommonUtil.java @@ -28,7 +28,6 @@ public class CommonUtil { Calendar calendar = Calendar.getInstance(); calendar.setTime(targetDate); calendar.add(Calendar.DATE, -2); - return calendar.getTime(); } @@ -37,7 +36,6 @@ public class CommonUtil { Calendar calendar = Calendar.getInstance(); calendar.setTime(targetDate); calendar.add(Calendar.YEAR, 100); - return calendar.getTime(); } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java deleted file mode 100644 index fa5b49e56c..0000000000 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/ConfigurationUtil.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.wso2.carbon.certificate.mgt.core.util; - -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.xml.sax.SAXException; - -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -public class ConfigurationUtil { - - public static final String PATH_CERTIFICATE_KEYSTORE = "CertificateKeystoreLocation"; - public static final String CERTIFICATE_KEYSTORE_PASSWORD = "CertificateKeystorePassword"; - public static final String KEYSTORE_CA_CERT_PRIV_PASSWORD = "CAPrivateKeyPassword"; - public static final String KEYSTORE_RA_CERT_PRIV_PASSWORD = "RAPrivateKeyPassword"; - public static final String CA_CERT_ALIAS = "CACertAlias"; - public static final String RA_CERT_ALIAS = "RACertAlias"; - public static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; - public static final String PROVIDER = "BC"; - public static final String KEYSTORE = "Type"; - public static final String CERTIFICATE_KEYSTORE = "CertificateKeystoreType"; - public static final String RSA = "RSA"; - public static final String UTF_8 = "UTF-8"; - public static final String SHA256_RSA = "SHA256WithRSAEncryption"; - public static final String X_509 = "X.509"; - public static final String POST_BODY_CA_CAPS = "POSTPKIOperation\nSHA-1\nDES3\n"; - public static final String DES_EDE = "DESede"; - public static final String CONF_LOCATION = "conf.location"; - public static final String DEFAULT_PRINCIPAL = "O=WSO2, OU=Mobile, C=LK"; - public static final String RSA_PRIVATE_KEY_BEGIN_TEXT = "-----BEGIN RSA PRIVATE KEY-----\n"; - public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----"; - public static final String EMPTY_TEXT = ""; - public static final int RSA_KEY_LENGTH = 1024; - public static final long MILLI_SECONDS = 1000L * 60 * 60 * 24; - private static final String CARBON_HOME = "carbon.home"; - private static final String CERTIFICATE_CONFIG_XML = "certificate-config.xml"; - private static final String CARBON_HOME_ENTRY = "${carbon.home}"; - private static final String[] certificateConfigEntryNames = { CA_CERT_ALIAS, RA_CERT_ALIAS, - CERTIFICATE_KEYSTORE, PATH_CERTIFICATE_KEYSTORE, CERTIFICATE_KEYSTORE_PASSWORD, - KEYSTORE_CA_CERT_PRIV_PASSWORD, KEYSTORE_RA_CERT_PRIV_PASSWORD }; - private static ConfigurationUtil configurationUtil; - private static Map configMap; - - private static Map readCertificateConfigurations() throws KeystoreException { - - String certConfLocation = System.getProperty(CONF_LOCATION) + File.separator + CERTIFICATE_CONFIG_XML; - - if (configurationUtil == null || configMap == null) { - - configurationUtil = new ConfigurationUtil(); - configMap = new HashMap(); - - Document document; - try { - File fXmlFile = new File(certConfLocation); - DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); - documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); - document = documentBuilder.parse(fXmlFile); - } catch (ParserConfigurationException e) { - throw new KeystoreException("Error parsing configuration in certificate-config.xml file"); - } catch (SAXException e) { - throw new KeystoreException("SAX exception in certificate-config.xml file"); - } catch (IOException e) { - throw new KeystoreException("Error reading certificate-config.xml file"); - } - - for (String configEntry : certificateConfigEntryNames) { - NodeList elements = document.getElementsByTagName(configEntry); - if (elements != null && elements.getLength() > 0) { - configMap.put(configEntry, elements.item(0).getTextContent()); - } - } - - String certKeyStoreLocation = replaceCarbonHomeEnvEntry(configMap.get(PATH_CERTIFICATE_KEYSTORE)); - if (certKeyStoreLocation != null) { - configMap.put(PATH_CERTIFICATE_KEYSTORE, certKeyStoreLocation); - } - } - - return configMap; - } - - public static String getConfigEntry(final String entry) throws KeystoreException { - - Map configurationMap = readCertificateConfigurations(); - String configValue = configurationMap.get(entry); - - if (configValue == null) { - throw new KeystoreException(String.format("Configuration entry %s not available", entry)); - } - - return configValue.trim(); - } - - private static String replaceCarbonHomeEnvEntry(String entry) { - if (entry != null && entry.toLowerCase().contains(CARBON_HOME_ENTRY)) { - return entry.replace(CARBON_HOME_ENTRY, System.getProperty(CARBON_HOME)); - } - - return null; - } - - public static ConfigurationUtil getInstance() { - if (configurationUtil == null) { - synchronized (ConfigurationUtil.class) { - if (configurationUtil == null) { - configurationUtil = new ConfigurationUtil(); - } - } - } - return configurationUtil; - } -} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/TenantUtil.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/TenantUtil.java deleted file mode 100644 index f452360bd8..0000000000 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/TenantUtil.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.wso2.carbon.certificate.mgt.core.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.certificate.mgt.core.exception.CertificateManagementException; -import org.wso2.carbon.context.PrivilegedCarbonContext; - -public class TenantUtil { - - private static final Log log = LogFactory.getLog(TenantUtil.class); - - public static int getTenanntId(String tenantDomain) throws CertificateManagementException { - return PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - } -} diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java index 38ea1fda12..a252754f45 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/test/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGeneratorTestSuite.java @@ -6,7 +6,7 @@ import org.apache.commons.logging.LogFactory; import org.testng.Assert; import org.testng.annotations.Test; import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException; -import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil; +import org.wso2.carbon.certificate.mgt.core.util.CertificateManagementConstants; import java.io.File; import java.io.IOException; @@ -34,8 +34,8 @@ public class CertificateGeneratorTestSuite { List rootCertificates = certificateGenerator.getRootCertificates(ca, ra); Assert.assertNotNull(rootCertificates, "Root certificates retrieved"); - Assert.assertEquals(rootCertificates.get(0).getType(), ConfigurationUtil.X_509); - Assert.assertEquals(rootCertificates.get(1).getType(), ConfigurationUtil.X_509); + Assert.assertEquals(rootCertificates.get(0).getType(), CertificateManagementConstants.X_509); + Assert.assertEquals(rootCertificates.get(1).getType(), CertificateManagementConstants.X_509); } catch (IOException e) { Assert.fail("Error reading byte streams for CA and RA ", e); } catch (KeystoreException e) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java index 04f9030760..537e5b01b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java @@ -60,6 +60,10 @@ public class DeviceDataPublisher { private static Map dataPublisherMap; private static DeviceDataPublisher deviceDataPublisher; + public DeviceDataPublisher() { + dataPublisherMap = new ConcurrentHashMap<>(); + } + public static DeviceDataPublisher getInstance() { if (deviceDataPublisher == null) { synchronized (DeviceDataPublisher.class) { @@ -71,10 +75,6 @@ public class DeviceDataPublisher { return deviceDataPublisher; } - public DeviceDataPublisher() { - dataPublisherMap = new ConcurrentHashMap<>(); - } - /** * this return the data publisher for the tenant. * @@ -95,7 +95,7 @@ public class DeviceDataPublisher { String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl(); String analyticsServerUsername = analyticsConfig.getAdminUsername(); String analyticsServerPassword = analyticsConfig.getAdminPassword(); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String userInfo[] = getAnalyticsServerUserInfo(tenantId); if (userInfo != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml index 0876d99c1f..98bdddfd20 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml @@ -110,14 +110,17 @@ org.apache.cxf cxf-rt-frontend-jaxws + provided org.apache.cxf cxf-rt-frontend-jaxrs + provided org.apache.cxf cxf-rt-transports-http + provided junit @@ -237,6 +240,7 @@ org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations + provided org.wso2.carbon.devicemgt @@ -248,6 +252,14 @@ jackson-annotations provided + + org.hibernate + hibernate-validator + + + javax.ws.rs + javax.ws.rs-api + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java index 8804fa3add..c695932eae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java @@ -34,7 +34,7 @@ public class ErrorResponse { private String moreInfo = null; private List errorItems = new ArrayList<>(); - private ErrorResponse() { + public ErrorResponse() { } @JsonProperty(value = "code") diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java index 1795e29982..c0c768eeb2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import javax.validation.constraints.Size; import java.util.List; @ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy " @@ -29,9 +30,11 @@ import java.util.List; public class PolicyWrapper { @ApiModelProperty(name = "policyName", value = "The name of the policy", required = true) + @Size(max = 45) private String policyName; @ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true) + @Size(max = 1000) private String description; @ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the" @@ -41,6 +44,7 @@ public class PolicyWrapper { + "Monitor - If the device does not adhere to the given policies the server is notified of the " + "violation unknown to the user and the administrator can take the necessary actions with regard" + " to the reported", required = true) + @Size(max = 100) private String compliance; @ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the " @@ -49,6 +53,7 @@ public class PolicyWrapper { + "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n" + "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE " + "device type", required = true) + @Size(max = 45) private String ownershipType; @ApiModelProperty(name = "active", value = "If the value is true it indicates that the policy is active. " diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java index 27aebb2abf..77bd4f9b63 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java @@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.core.dto.DeviceType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java index e62b5a4a3c..701d341133 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java @@ -20,7 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.user.mgt.common.UIPermissionNode; + +import java.util.List; @ApiModel(value = "RoleInfo", description = "Role details including permission and the users in the roles are " + "wrapped here.") @@ -28,19 +29,12 @@ public class RoleInfo { @ApiModelProperty(name = "roleName", value = "The name of the role.", required = true) private String roleName; - @ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.", - required = true, dataType = "List[java.lang.String]") - private String[] permissions; + @ApiModelProperty(name = "scopes", value = "Lists out all the scopes associated with roles.", + required = true, dataType = "List[org.wso2.carbon.device.mgt.jaxrs.beans.Scope]") + private List scopes; @ApiModelProperty(name = "users", value = "The list of users assigned to the selected role.", required = true, dataType = "List[java.lang.String]") private String[] users; - @ApiModelProperty(name = "permissionList", value = "This contain the following, " + - "\n resourcePath\tThe path related to the API.\n " + - "displayName\tThe name of the permission that is shown " + - "in the UI.\n" + - "nodeList\tLists out the nested permissions.", - required = true) - private UIPermissionNode permissionList; public String getRoleName() { return roleName; @@ -50,12 +44,12 @@ public class RoleInfo { this.roleName = roleName; } - public String[] getPermissions() { - return permissions; + public List getScopes() { + return scopes; } - public void setPermissions(String[] permissions) { - this.permissions = permissions; + public void setScopes(List scopes) { + this.scopes = scopes; } public String[] getUsers() { @@ -66,11 +60,4 @@ public class RoleInfo { this.users = users; } - public UIPermissionNode getPermissionList() { - return permissionList; - } - - public void setPermissionList(UIPermissionNode permissionList) { - this.permissionList = permissionList; - } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java new file mode 100644 index 0000000000..0badaa417c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java @@ -0,0 +1,71 @@ +/* +* Copyright (c) 2014, 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. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.jaxrs.beans; + +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +@ApiModel(value = "Scope", description = "Template of the authorization scope") +public class Scope { + + @ApiModelProperty(name = "scope key", value = "An unique string as a key.", required = true) + private String key; + + @ApiModelProperty(name = "scope name", value = "Scope name.", required = true) + private String name; + + @ApiModelProperty(name = "roles", value = "List of roles to be associated with the scope", required = true) + private String roles; + + @ApiModelProperty(name = "scope description", value = "A description of the scope", required = true) + private String description; + + public Scope() { + } + + public String getKey() { + return this.key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getRoles() { + return this.roles; + } + + public void setRoles(String roles) { + this.roles = roles; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java similarity index 55% rename from components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java index 7d16d198b9..d97b78b6dd 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java @@ -16,30 +16,19 @@ * under the License. */ -package org.wso2.carbon.apimgt.webapp.publisher.config; +package org.wso2.carbon.device.mgt.jaxrs.exception; + +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; /** - * This class represents the information related to permissions. + * Custom exception class for wrapping BadRequest related exceptions. */ -public class PermissionConfiguration { +public class BadRequestException extends WebApplicationException { - private String scopeName; - private String[] permissions; - - public String getScopeName() { - return scopeName; + public BadRequestException(ErrorResponse error) { + super(Response.status(Response.Status.BAD_REQUEST).entity(error).build()); } - - public void setScopeName(String scope) { - this.scopeName = scope; - } - - public String[] getPermissions() { - return permissions; - } - - public void setPermissions(String[] permissions) { - this.permissions = permissions; - } - -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java new file mode 100644 index 0000000000..9664057f61 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.jaxrs.exception; + +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; + +import javax.validation.ConstraintViolation; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; +import java.util.Set; + +public class ConstraintViolationException extends WebApplicationException { + private String message; + + public ConstraintViolationException(Set> violations) { + super(Response.status(Response.Status.BAD_REQUEST) + .entity(DeviceMgtUtil.getConstraintViolationErrorDTO(violations)) + .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON) + .build()); + + //Set the error message + StringBuilder stringBuilder = new StringBuilder(); + for (ConstraintViolation violation : violations) { + stringBuilder.append(violation.getRootBeanClass().getSimpleName()); + stringBuilder.append("."); + stringBuilder.append(violation.getPropertyPath()); + stringBuilder.append(": "); + stringBuilder.append(violation.getMessage()); + stringBuilder.append(", "); + } + message = stringBuilder.toString(); + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java new file mode 100644 index 0000000000..ff4e0be32a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java @@ -0,0 +1,86 @@ +/* + * 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.jaxrs.exception; + +import java.util.ArrayList; +import java.util.List; + +public class ErrorDTO { + + private Long code = null; + private String message = null; + private String description = null; + + public void setMoreInfo(String moreInfo) { + this.moreInfo = moreInfo; + } + + public void setCode(Long code) { + this.code = code; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setError(List error) { + this.error = error; + } + + private String moreInfo = null; + + public String getMessage() { + return message; + } + + public Long getCode() { + return code; + } + + public String getDescription() { + return description; + } + + public String getMoreInfo() { + return moreInfo; + } + + public List getError() { + return error; + } + + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.append("class ErrorDTO {\n"); + stringBuilder.append(" code: ").append(code).append("\n"); + stringBuilder.append(" message: ").append(message).append("\n"); + stringBuilder.append(" description: ").append(description).append("\n"); + stringBuilder.append(" moreInfo: ").append(moreInfo).append("\n"); + stringBuilder.append(" error: ").append(error).append("\n"); + stringBuilder.append("}\n"); + return stringBuilder.toString(); + } + + private List error = new ArrayList<>(); + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java new file mode 100644 index 0000000000..912f624632 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java @@ -0,0 +1,51 @@ +/* + * 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.jaxrs.exception; + +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +/** + * Exception class that is corresponding to 401 Forbidden response + */ + +public class ForbiddenException extends WebApplicationException { + + private String message; + + public ForbiddenException() { + super(Response.status(Response.Status.FORBIDDEN) + .build()); + } + + public ForbiddenException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.FORBIDDEN) + .entity(errorDTO) + .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java new file mode 100644 index 0000000000..be3d037a8d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java @@ -0,0 +1,113 @@ +/* + * 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.jaxrs.exception; + +import com.google.gson.JsonParseException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; + +import javax.naming.AuthenticationException; +import javax.ws.rs.ClientErrorException; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; + +/** + * Handle the cxf level exceptions. + */ +public class GlobalThrowableMapper implements ExceptionMapper { + private static final Log log = LogFactory.getLog(GlobalThrowableMapper.class); + + private ErrorDTO e500 = new ErrorDTO(); + + GlobalThrowableMapper() { + e500.setCode((long) 500); + e500.setMessage("Internal server error."); + e500.setMoreInfo(""); + e500.setDescription("The server encountered an internal error. Please contact administrator."); + + } + + @Override + public Response toResponse(Throwable e) { + + if (e instanceof JsonParseException) { + String errorMessage = "Malformed request body."; + if (log.isDebugEnabled()) { + log.error(errorMessage, e); + } + return DeviceMgtUtil.buildBadRequestException(errorMessage).getResponse(); + } + if (e instanceof NotFoundException) { + return ((NotFoundException) e).getResponse(); + } + if (e instanceof UnexpectedServerErrorException) { + if (log.isDebugEnabled()) { + log.error("Unexpected server error.", e); + } + return ((UnexpectedServerErrorException) e).getResponse(); + } + if (e instanceof ConstraintViolationException) { + if (log.isDebugEnabled()) { + log.error("Constraint violation.", e); + } + return ((ConstraintViolationException) e).getResponse(); + } + if (e instanceof IllegalArgumentException) { + ErrorDTO errorDetail = new ErrorDTO(); + errorDetail.setCode((long) 400); + errorDetail.setMoreInfo(""); + errorDetail.setMessage(""); + errorDetail.setDescription(e.getMessage()); + return Response + .status(Response.Status.BAD_REQUEST) + .entity(errorDetail) + .build(); + } + if (e instanceof ClientErrorException) { + if (log.isDebugEnabled()) { + log.error("Client error.", e); + } + return ((ClientErrorException) e).getResponse(); + } + if (e instanceof AuthenticationException) { + ErrorDTO errorDetail = new ErrorDTO(); + errorDetail.setCode((long) 401); + errorDetail.setMoreInfo(""); + errorDetail.setMessage(""); + errorDetail.setDescription(e.getMessage()); + return Response + .status(Response.Status.UNAUTHORIZED) + .entity(errorDetail) + .build(); + } + if (e instanceof ForbiddenException) { + if (log.isDebugEnabled()) { + log.error("Resource forbidden.", e); + } + return ((ForbiddenException) e).getResponse(); + } + //unknown exception log and return + if (log.isDebugEnabled()) { + log.error("An Unknown exception has been captured by global exception mapper.", e); + } + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header("Content-Type", "application/json") + .entity(e500).build(); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java new file mode 100644 index 0000000000..ac9fc5c568 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java @@ -0,0 +1,47 @@ +/* + * 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.jaxrs.exception; + + +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class NotFoundException extends WebApplicationException { + private String message; + private static final long serialVersionUID = 147943572342342340L; + + public NotFoundException(ErrorResponse error) { + super(Response.status(Response.Status.NOT_FOUND).entity(error).build()); + } + public NotFoundException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.NOT_FOUND) + .entity(errorDTO) + .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java new file mode 100644 index 0000000000..40d5d74e68 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java @@ -0,0 +1,49 @@ +/* + * 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.jaxrs.exception; + + +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import org.wso2.carbon.device.mgt.jaxrs.util.Constants; + +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +public class UnexpectedServerErrorException extends WebApplicationException { + private String message; + private static final long serialVersionUID = 147943579458906890L; + + public UnexpectedServerErrorException(ErrorResponse error) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build()); + } + public UnexpectedServerErrorException(ErrorDTO errorDTO) { + super(Response.status(Response.Status.INTERNAL_SERVER_ERROR) + .entity(errorDTO) + .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON) + .build()); + message = errorDTO.getDescription(); + } + + @Override + public String getMessage() { + return message; + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java new file mode 100644 index 0000000000..480911b39b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java @@ -0,0 +1,122 @@ +/* + * 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.jaxrs.exception; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.jaxrs.lifecycle.ResourceProvider; +import org.apache.cxf.jaxrs.model.ClassResourceInfo; +import org.apache.cxf.jaxrs.model.OperationResourceInfo; +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageContentsList; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; + +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; +import java.lang.reflect.Method; +import java.util.List; +import java.util.Set; + +public class ValidationInterceptor extends AbstractPhaseInterceptor { + private Log log = LogFactory.getLog(getClass()); + private Validator validator = null; //validator interface is thread-safe + + public ValidationInterceptor() { + super(Phase.PRE_INVOKE); + ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory(); + validator = defaultFactory.getValidator(); + if (validator == null) { + log.warn("Bean Validation provider could not be found, no validation will be performed"); + } else { + log.debug("Validation In-Interceptor initialized successfully"); + } + } + + @Override + public void handleMessage(Message message) throws Fault { + final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class); + if (operationResource == null) { + log.info("OperationResourceInfo is not available, skipping validation"); + return; + } + + final ClassResourceInfo classResource = operationResource.getClassResourceInfo(); + if (classResource == null) { + log.info("ClassResourceInfo is not available, skipping validation"); + return; + } + + final ResourceProvider resourceProvider = classResource.getResourceProvider(); + if (resourceProvider == null) { + log.info("ResourceProvider is not available, skipping validation"); + return; + } + + final List arguments = MessageContentsList.getContentsList(message); + final Method method = operationResource.getAnnotatedMethod(); + final Object instance = resourceProvider.getInstance(message); + if (method != null && arguments != null) { + //validate the parameters(arguments) over the invoked method + validate(method, arguments.toArray(), instance); + + //validate the fields of each argument + for (Object arg : arguments) { + if (arg != null) + validate(arg); + } + } + + } + + public void validate(final Method method, final Object[] arguments, final T instance) { + if (validator == null) { + log.warn("Bean Validation provider could not be found, no validation will be performed"); + return; + } + + ExecutableValidator methodValidator = validator.forExecutables(); + Set> violations = methodValidator.validateParameters(instance, + method, arguments); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + } + + public void validate(final T object) { + if (validator == null) { + log.warn("Bean Validation provider could be found, no validation will be performed"); + return; + } + + Set> violations = validator.validate(object); + + if (!violations.isEmpty()) { + throw new ConstraintViolationException(violations); + } + } + + public void handleFault(org.apache.cxf.message.Message messageParam) { + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java index 4adaa9ac14..f91a9ccdb6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ActivityInfoProviderService.java @@ -20,11 +20,12 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -32,7 +33,7 @@ import javax.ws.rs.core.Response; /** * Activity related REST-API implementation. */ -@API(name = "Activities", version = "1.0.0", context = "/devicemgt_admin/activities", tags = {"devicemgt_admin"}) +@API(name = "Activity Info Provider", version = "1.0.0", context = "/api/device-mgt/v1.0/activities", tags = {"devicemgt_admin"}) @Path("/activities") @Api(value = "Activity Info Provider", description = "Activity related information manipulation. For example operation details " + @@ -91,16 +92,15 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission( - scope = "activity-view", - permissions = {"/permission/admin/device-mgt/admin/activities/view"} - ) + @Scope(key = "activity:view", name = "View Activities", description = "") Response getActivity( @ApiParam( name = "id", value = "Activity id of the operation/activity to be retrieved.", required = true) - @PathParam("id") String id, + @PathParam("id") + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", @@ -153,10 +153,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission( - scope = "activity-view", - permissions = {"/permission/admin/device-mgt/admin/activities/view"} - ) + @Scope(key = "activity:view", name = "View Activities", description = "") Response getActivities( @ApiParam( name = "since", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java index fa6ed7527b..3708677b75 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/ConfigurationManagementService.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -31,7 +31,7 @@ import javax.ws.rs.core.Response; /** * General Tenant Configuration REST-API. */ -@API(name = "Configuration", version = "1.0.0", context = "/devicemgt_admin/configuration", tags = {"devicemgt_admin"}) +@API(name = "Configuration Management", version = "1.0.0", context = "/api/device-mgt/v1.0/configuration", tags = {"devicemgt_admin"}) @Path("/configuration") @Api(value = "Configuration Management", description = "General Tenant Configuration management capabilities are exposed " + @@ -80,12 +80,8 @@ public interface ConfigurationManagementService { message = "Internal Server Error. \n Server error occurred while fetching the general " + "platform configuration.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "configuration-view", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"} - ) + }) + @Scope(key = "configuration:view", name = "View Configurations", description = "") Response getConfiguration( @ApiParam( name = "If-Modified-Since", @@ -130,12 +126,8 @@ public interface ConfigurationManagementService { message = "Internal Server Error. \n " + "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "configuration-modify", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"} - ) + }) + @Scope(key = "configuration:modify", name = "Modify Configurations", description = "") Response updateConfiguration( @ApiParam( name = "configuration", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java index 05df689189..b4714623b2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Feature; import org.wso2.carbon.device.mgt.common.app.mgt.Application; @@ -31,6 +31,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -38,7 +39,7 @@ import javax.ws.rs.core.Response; /** * Device related REST-API. This can be used to manipulated device related details. */ -@API(name = "Device", version = "1.0.0", context = "/api/device-mgt/admin/devices", tags = {"devicemgt_admin"}) +@API(name = "Device Management", version = "1.0.0", context = "/api/device-mgt/v1.0/devices", tags = {"devicemgt_admin"}) @Path("/devices") @Api(value = "Device Management", description = "This API carries all device management related operations " + @@ -91,71 +92,74 @@ public interface DeviceManagementService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission( - scope = "device-list", - permissions = {"/permission/admin/device-mgt/admin/devices/list"} - ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getDevices( @ApiParam( name = "name", value = "The device name, such as shamu, bullhead or angler.", required = false) - String name, + @Size(max = 45) + String name, @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = false) @QueryParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "user", value = "Username of owner of the devices.", required = false) @QueryParam("user") - String user, + @Size(max = 45) + String user, @ApiParam( name = "roleName", value = "Role name of the devices to be fetched.", required = false) @QueryParam("roleName") - String roleName, + @Size(max = 45) + String roleName, @ApiParam( name = "ownership", allowableValues = "BYOD, COPE", value = "Ownership of the devices to be fetched registered under.", required = false) @QueryParam("ownership") - String ownership, + @Size(max = 45) + String ownership, @ApiParam( name = "status", value = "Enrollment status of devices to be fetched.", required = false) @QueryParam("status") - String status, + @Size(max = 45) + String status, @ApiParam( name = "since", value = "Last modified timestamp", required = false) @QueryParam("since") - String since, + String since, @ApiParam( name = "If-Modified-Since", value = "Timestamp of the last modified date", required = false) @HeaderParam("If-Modified-Since") - String timestamp, + String timestamp, @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.", required = false) @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) @QueryParam("limit") - int limit); + int limit); @GET @@ -203,32 +207,28 @@ public interface DeviceManagementService { "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - @Permission( - scope = "device-view", - permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getDevice( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "The device identifier of the device.", required = true) @PathParam("id") - String id, + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); + String ifModifiedSince); @GET @Path("/{type}/{id}/features") @@ -289,31 +289,28 @@ public interface DeviceManagementService { "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) - @Permission( - scope = "device-search", - permissions = {"/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getFeaturesOfDevice( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "The device identifier of the device.", required = true) @PathParam("id") - String id, + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); + String ifModifiedSince); @POST @Path("/search-devices") @@ -368,28 +365,25 @@ public interface DeviceManagementService { "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) - @Permission( - scope = "device-search", - permissions = {"/permission/admin/device-mgt/admin/devices/list" } - ) + @Scope(key = "device:view", name = "View Devices", description = "") Response searchDevices( @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.", required = false) @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) @QueryParam("limit") - int limit, + int limit, @ApiParam( name = "searchContext", value = "List of search conditions.", required = true) - SearchContext searchContext); + SearchContext searchContext); @GET @Path("/{type}/{id}/applications") @@ -450,43 +444,40 @@ public interface DeviceManagementService { "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) - @Permission( - scope = "operation-view", - permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Scope(key = "device:view", name = "View Devices", description = "") + Response getInstalledApplications( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "The device identifier of the device.", required = true) @PathParam("id") - String id, + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince, + String ifModifiedSince, @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.", required = false) @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) @QueryParam("limit") - int limit); + int limit); @GET @@ -550,45 +541,41 @@ public interface DeviceManagementService { "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) - @Permission( - scope = "operation-view", - permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getDeviceOperations( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "The device identifier of the device.", required = true) @PathParam("id") - String id, + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time " + "specified", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince, + String ifModifiedSince, @ApiParam( name = "offset", value = "Starting point within the complete list of items qualified.", required = false) @QueryParam("offset") - int offset, + int offset, @ApiParam( name = "limit", value = "Maximum size of resource array to return.", required = false) @QueryParam("limit") - int limit); + int limit); @GET @Path("/{type}/{id}/effective-policy") @@ -652,27 +639,29 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getEffectivePolicyOfDevice( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "Device Identifier", required = true) @PathParam("id") - String id, + @Size(max = 45) + String id, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time " + "specified", required = false) @HeaderParam("If-Modified-Since") - String ifModifiedSince); - + String ifModifiedSince); @GET @@ -702,16 +691,20 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) + @Scope(key = "device:view", name = "View Devices", description = "") Response getComplianceDataOfDevice( @ApiParam( name = "type", value = "The device type, such as ios, android or windows.", required = true) @PathParam("type") - String type, + @Size(max = 45) + String type, @ApiParam( name = "id", value = "Device Identifier", required = true) - @PathParam("id") String id); + @PathParam("id") + @Size(max = 45) + String id); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java index 41cbb1a993..2da0537b6b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -28,7 +28,7 @@ import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API(name = "Device Type Management", version = "1.0.0", context = "/admin/device-types", tags = {"devicemgt_admin"}) +@API(name = "Device Type Management", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/device-types", tags = {"devicemgt_admin"}) @Path("/device-types") @Api(value = "Device Type Management", description = "This API corresponds to all tasks related to device " + @@ -78,10 +78,7 @@ public interface DeviceTypeManagementService { response = ErrorResponse.class) } ) - @Permission( - scope = "read:device-types", - permissions = {"/permission/admin/device-mgt/admin/device-types/view"} - ) + @Scope(key = "device-type:admin:view", name = "View device types", description = "") Response getDeviceTypes( @ApiParam( name = "If-Modified-Since", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index 46588ccbc9..2fa4297881 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -18,7 +18,7 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.api; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java index 5e4d06f10c..34bc726c66 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/NotificationManagementService.java @@ -20,13 +20,13 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; -import org.wso2.carbon.device.mgt.jaxrs.NotificationContext; import org.wso2.carbon.device.mgt.jaxrs.NotificationList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import javax.validation.constraints.Max; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -34,7 +34,7 @@ import javax.ws.rs.core.Response; /** * Notifications related REST-API. */ -@API(name = "Device Notification Management API", version = "1.0.0", context = "/devicemgt_admin/notifications", +@API(name = "Device Notification Management", version = "1.0.0", context = "/api/device-mgt/v1.0/notifications", tags = {"devicemgt_admin"}) @Api(value = "Device Notification Management", description = "Device notification related operations can be found here.") @Path("/notifications") @@ -89,21 +89,15 @@ public interface NotificationManagementService { message = "Internal Server Error. " + "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "device-notification-view", - permissions = { - "/permission/admin/device-mgt/admin/notifications/view", - "/permission/admin/device-mgt/user/notifications/view" } - ) + }) + @Scope(key = "notification:view", name = "View and manage notifications", description = "") Response getNotifications( @ApiParam( name = "status", value = "Status of the notification.", allowableValues = "NEW, CHECKED", required = false) - @QueryParam("status") + @QueryParam("status") @Size(max = 45) String status, @ApiParam( name = "If-Modified-Since", @@ -148,15 +142,12 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Permission( - scope = "", - permissions = { "" } - ) + @Scope(key = "notification:view", name = "View and manage notifications", description = "") Response updateNotificationStatus( @ApiParam( name = "id", value = "Notification ID.", required = true) - @PathParam("id") + @PathParam("id") @Max(45) int id); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java index 36301bd8f9..1ede29f3e8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/PolicyManagementService.java @@ -19,12 +19,14 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; -import org.wso2.carbon.policy.mgt.common.Policy; import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper; +import org.wso2.carbon.policy.mgt.common.Policy; +import javax.validation.Valid; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -34,6 +36,9 @@ import java.util.List; * Policy related REST-API. This can be used to manipulated policies and associate them with devices, users, roles, * groups. */ +@API(name = "Device Policy Management", version = "1.0.0", context = "/api/device-mgt/v1.0/policies", + tags = {"devicemgt_admin"}) + @Api(value = "Device Policy Management", description = "This API carries all the necessary functionalities " + "around device policy management") @Path("/policies") @@ -94,18 +99,14 @@ public interface PolicyManagementService { message = "Internal Server Error. \n " + "Server error occurred while adding a new policy.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/add"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response addPolicy( @ApiParam( name = "policy", value = "Policy details related to the operation.", required = true) - PolicyWrapper policy); + @Valid PolicyWrapper policy); @GET @ApiOperation( @@ -152,12 +153,8 @@ public interface PolicyManagementService { message = ("Internal Server Error. \n Server error occurred while fetching " + "policies."), response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"} - ) + }) + @Scope(key = "policy:view", name = "Views policies", description = "") Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -223,10 +220,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Permission( - scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"} - ) + @Scope(key = "policy:view", name = "View policies", description = "") Response getPolicy( @ApiParam( name = "id", @@ -289,12 +283,8 @@ public interface PolicyManagementService { message = "Internal Server Error. \n " + "Server error occurred while updating the policy.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/update"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response updatePolicy( @ApiParam( name = "id", @@ -306,7 +296,7 @@ public interface PolicyManagementService { name = "policy", value = "Policy details related to the operation.", required = true) - PolicyWrapper policy); + @Valid PolicyWrapper policy); @POST @Path("/remove-policy") @@ -339,12 +329,8 @@ public interface PolicyManagementService { message = "Internal Server Error. \n " + "Server error occurred while bulk removing policies.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/remove"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response removePolicies( @ApiParam( name = "policyIds", @@ -379,13 +365,8 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in activating policies.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", permissions = { - "/permission/admin/device-mgt/admin/policies/update", - "/permission/admin/device-mgt/admin/policies/add"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response activatePolicies( @ApiParam( name = "policyIds", @@ -393,7 +374,7 @@ public interface PolicyManagementService { required = true) List policyIds); - @POST + @PUT @Path("/deactivate-policy") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -420,14 +401,8 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", - permissions = { - "/permission/admin/device-mgt/admin/policies/update", - "/permission/admin/device-mgt/admin/policies/add"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -459,12 +434,8 @@ public interface PolicyManagementService { code = 500, message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/update"} - ) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response applyChanges(); @@ -492,11 +463,8 @@ public interface PolicyManagementService { code = 500, message = "Exception in updating policy priorities.", response = ErrorResponse.class) - } - ) - @Permission( - scope = "", - permissions = {}) + }) + @Scope(key = "policy:manage", name = "Add policies", description = "") Response updatePolicyPriorities( @ApiParam( name = "priorityUpdatedPolicies", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java index a42758e215..83b8e5851f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/RoleManagementService.java @@ -20,18 +20,17 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; -import org.wso2.carbon.user.mgt.common.UIPermissionNode; +import org.wso2.carbon.device.mgt.jaxrs.beans.Scope; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; -@API(name = "Role", version = "1.0.0", context = "/devicemgt_admin/roles", tags = {"devicemgt_admin"}) +@API(name = "Role Management", version = "1.0.0", context = "/api/device-mgt/v1.0/roles", tags = {"devicemgt_admin"}) @Path("/roles") @Api(value = "Role Management", description = "Role management related operations can be found here.") @@ -77,11 +76,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) - @Permission(scope = "roles-view", permissions = { - "/permission/admin/device-mgt/admin/roles/list", - "/permission/admin/device-mgt/admin/users/view", - "/permission/admin/device-mgt/admin/policies/add", - "/permission/admin/device-mgt/admin/policies/update"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") Response getRoles( @ApiParam( name = "filter", @@ -110,16 +105,16 @@ public interface RoleManagementService { @QueryParam("limit") int limit); @GET - @Path("/{roleName}/permissions") + @Path("/scopes") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Getting permission details of a role.", + value = "Getting authorization scopes.", notes = "In an organization an individual is associated a with set of responsibilities based on their " + - "role. In EMM you are able to configure permissions based on the responsibilities carried " + - "out by a role. Therefore if you wish to retrieve the permission details of a role, you can do " + + "role. In EMM you are able to configure scopes based on the responsibilities carried " + + "out by a role. Therefore if you wish to retrieve the scopes details of roles, you can do " + "so using this REST API.", - response = UIPermissionNode.class, + response = List.class, responseContainer = "List", tags = "Role Management" ) @@ -127,8 +122,8 @@ public interface RoleManagementService { value = { @ApiResponse( code = 200, - message = "OK. \n Successfully fetched the permission list of the given role.", - response = UIPermissionNode.class, + message = "OK. \n Successfully fetched the scopes list.", + response = List.class, responseContainer = "List", responseHeaders = { @ResponseHeader( @@ -163,19 +158,63 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) - Response getPermissionsOfRole( - @ApiParam( - name = "roleName", - value = "Name of the role.", - required = true) - @PathParam("roleName") String roleName, + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") + Response getScopes( @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", required = false) @HeaderParam("If-Modified-Since") String ifModifiedSince); + @PUT + @Path("/scopes") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "PUT", + value = "Updating authorization scopes.", + notes = "This REST API can be used to update the associated roles of the scopes", + tags = "Role Management" + ) + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Scopes has been updated successfully", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "Content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests.")}), + @ApiResponse( + code = 400, + message = "Bad Request. \n Invalid request or validation error.", + response = ErrorResponse.class), + @ApiResponse( + code = 404, + message = "Not Found. \n Scopes to be updated does not exist.", + response = ErrorResponse.class), + @ApiResponse( + code = 415, + message = "Unsupported media type. \n The entity of the request was in a not supported format.", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while updating the scopes.", + response = ErrorResponse.class) + }) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") + Response updateScopes( + @ApiParam( + name = "Scopes", + value = "List of scopes to be updated", + required = true) List scopes); + @GET @Path("/{roleName}") @ApiOperation( @@ -226,7 +265,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") Response getRole( @ApiParam( name = "roleName", @@ -286,7 +325,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response addRole( @ApiParam( name = "role", @@ -336,7 +375,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response updateRole( @ApiParam( name = "roleName", @@ -373,13 +412,17 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response deleteRole( @ApiParam( name = "roleName", value = "Name of the role to de deleted.", required = true) - @PathParam("roleName") String roleName); + @PathParam("roleName") String roleName, + @ApiParam( + name = "role", + value = "Details about the role to be added.", + required = true) RoleInfo role); @PUT @Path("/{roleName}/users") @@ -431,7 +474,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response updateUsersOfRole( @ApiParam( name = "roleName", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java index de93bea82b..27fdf848e0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/UserManagementService.java @@ -20,7 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.*; import javax.ws.rs.*; @@ -29,7 +29,7 @@ import javax.ws.rs.core.Response; import java.util.List; -@API(name = "User Management API", version = "1.0.0", context = "/devicemgt_admin/users", tags = {"devicemgt_admin"}) +@API(name = "User Management", version = "1.0.0", context = "/api/device-mgt/v1.0/users", tags = {"devicemgt_admin"}) @Path("/users") @Api(value = "User Management", description = "User management related operations can be found here.") @@ -83,7 +83,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while adding a new user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"}) + @Scope(key = "user:manage", name = "Add users", description = "") Response addUser( @ApiParam( name = "user", @@ -135,7 +135,7 @@ public interface UserManagementService { " fetching the requested user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + @Scope(key = "user:view", name = "View users", description = "") Response getUser( @ApiParam( name = "username", @@ -192,7 +192,7 @@ public interface UserManagementService { "Server error occurred while updating the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/update"}) + @Scope(key = "user:manage", name = "Add users", description = "") Response updateUser( @ApiParam( name = "username", @@ -227,7 +227,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/remove"}) + @Scope(key = "user:manage", name = "Add users", description = "") Response removeUser( @ApiParam(name = "username", value = "Username of the user to be deleted.", required = true) @PathParam("username") String username); @@ -276,7 +276,7 @@ public interface UserManagementService { " assigned to the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + @Scope(key = "user:view", name = "View users", description = "") Response getRolesOfUser( @ApiParam(name = "username", value = "Username of the user.", required = true) @PathParam("username") String username); @@ -319,7 +319,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) + @Scope(key = "user:view", name = "View users", description = "") Response getUsers( @ApiParam( name = "filter", @@ -386,7 +386,7 @@ public interface UserManagementService { "list that matches the given filter.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) + @Scope(key = "user:view", name = "View users", description = "") Response getUserNames( @ApiParam( name = "filter", @@ -440,7 +440,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) + @Scope(key = "user:view", name = "View users", description = "") Response resetPassword( @ApiParam( name = "username", @@ -483,7 +483,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-invite", permissions = {"/permission/admin/device-mgt/admin/user/invite"}) + @Scope(key = "user:manage", name = "Add users", description = "") Response inviteExistingUsersToEnrollDevice( @ApiParam( name = "users", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java index 49f15dccb1..546f6d96b1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/ApplicationManagementAdminService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -31,7 +32,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API(name = "Application", version = "1.0.0", context = "/devicemgt_admin/applications", tags = {"devicemgt_admin"}) +@API(name = "Application Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/applications", tags = {"devicemgt_admin"}) @Path("/admin/applications") @Api(value = "Application Management Administrative Service", description = "This an API intended to be used by " + @@ -73,6 +74,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) + @Scope(key = "application:manage", name = "Install/Uninstall applications", description = "") Response installApplication( @ApiParam( name = "applicationWrapper", @@ -111,6 +113,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) + @Scope(key = "application:manage", name = "Install/Uninstall applications", description = "") Response uninstallApplication( @ApiParam( name = "applicationWrapper", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java index 89b8d9185b..66a3c75f05 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java @@ -20,14 +20,16 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API(name = "DeviceManagementAdmin", version = "1.0.0", context = "/devicemgt_admin/applications", +@API(name = "Device Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/devices", tags = {"devicemgt_admin"}) @Path("/admin/devices") @Api(value = "Device Management Administrative Service", description = "This an API intended to be used by " + @@ -83,17 +85,22 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) + @Scope(key = "device:admin:view", name = "View Devices", description = "") Response getDevicesByName( @ApiParam( name = "name", value = "Name of the device.", required = true) - @QueryParam("name") String name, + @QueryParam("name") + @Size(max = 45) + String name, @ApiParam( name = "type", value = "Type of the device.", required = true) - @QueryParam("type") String type, + @QueryParam("type") + @Size(min = 2, max = 45) + String type, @ApiParam( name = "tenant-domain", value = "Name of the tenant.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 4d5915684b..0580d8504d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -19,7 +19,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; import javax.ws.rs.*; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java index 66ca21d1fc..6307ee00e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/UserManagementAdminService.java @@ -19,14 +19,18 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; import io.swagger.annotations.*; -import org.wso2.carbon.apimgt.annotations.api.Permission; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +@API(name = "User Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/users", tags = {"devicemgt_admin"}) + @Path("/admin/users") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @@ -64,13 +68,15 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) + @Scope(key = "user:admin:reset-password", name = "View users", description = "") Response resetUserPassword( @ApiParam( name = "username", value = "Username of the user.", required = true) - @PathParam("username") String username, + @PathParam("username") + @Size(max = 45) + String username, @ApiParam( name = "credentials", value = "Credential.", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index 444854e1e4..9b0c4e9975 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java @@ -29,6 +29,7 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.ActivityInfoProviderService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -47,7 +48,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService @GET @Override @Path("/{id}") - public Response getActivity(@PathParam("id") String id, + public Response getActivity(@PathParam("id") + @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { Activity activity; DeviceManagementProviderService dmService; @@ -81,7 +83,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService long timestamp = 0; boolean isIfModifiedSinceSet = false; boolean isSinceSet = false; - + RequestValidationUtil.validatePaginationParameters(offset, limit); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifSinceDate; SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java index 0c082722fd..064984f19d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ConfigurationServiceImpl.java @@ -26,7 +26,6 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.ConfigurationManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; -import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.device.mgt.jaxrs.util.MDMAppConstants; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 2266f51d4a..106e7b0fbc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java @@ -44,6 +44,7 @@ import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData; import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -62,25 +63,25 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Override public Response getDevices( - @QueryParam("name") String name, - @QueryParam("type") String type, - @QueryParam("user") String user, - @QueryParam("roleName") String roleName, - @QueryParam("ownership") String ownership, - @QueryParam("status") String status, + @QueryParam("name") @Size(max = 45) String name, + @QueryParam("type") @Size(max = 45) String type, + @QueryParam("user") @Size(max = 45) String user, + @QueryParam("roleName") @Size(max = 45) String roleName, + @QueryParam("ownership") @Size(max = 45) String ownership, + @QueryParam("status") @Size(max = 45) String status, @QueryParam("since") String since, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { try { // RequestValidationUtil.validateSelectionCriteria(type, user, roleName, ownership, status); - + RequestValidationUtil.validatePaginationParameters(offset, limit); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceList devices = new DeviceList(); - if(name != null && !name.isEmpty()){ + if (name != null && !name.isEmpty()) { request.setDeviceName(name); } if (type != null && !type.isEmpty()) { @@ -154,6 +155,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { public Response getDeviceByUser(@QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceList devices = new DeviceList(); @@ -179,8 +181,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{type}/{id}") @Override public Response getDevice( - @PathParam("type") String type, - @PathParam("id") String id, + @PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { Device device; try { @@ -206,8 +208,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{type}/{id}/features") @Override public Response getFeaturesOfDevice( - @PathParam("type") String type, - @PathParam("id") String id, + @PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { List features; DeviceManagementProviderService dms; @@ -257,8 +259,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{type}/{id}/applications") @Override public Response getInstalledApplications( - @PathParam("type") String type, - @PathParam("id") String id, + @PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { @@ -286,12 +288,13 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @Path("/{type}/{id}/operations") @Override public Response getDeviceOperations( - @PathParam("type") String type, - @PathParam("id") String id, + @PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { OperationList operationsList = new OperationList(); + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceManagementProviderService dms; @@ -316,8 +319,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Path("/{type}/{id}/effective-policy") @Override - public Response getEffectivePolicyOfDevice(@PathParam("type") String type, - @PathParam("id") String id, + public Response getEffectivePolicyOfDevice(@PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id, @HeaderParam("If-Modified-Since") String ifModifiedSince) { try { RequestValidationUtil.validateDeviceIdentifier(type, id); @@ -337,8 +340,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @GET @Path("{type}/{id}/compliance-data") - public Response getComplianceDataOfDevice(@PathParam("type") String type, - @PathParam("id") String id) { + public Response getComplianceDataOfDevice(@PathParam("type") @Size(max = 45) String type, + @PathParam("id") @Size(max = 45) String id) { RequestValidationUtil.validateDeviceIdentifier(type, id); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index c504da33d1..3bc4fec7df 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java @@ -31,6 +31,8 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.UnexpectedServerErrorException; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import javax.validation.constraints.Max; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -46,10 +48,11 @@ public class NotificationManagementServiceImpl implements NotificationManagement @GET @Override public Response getNotifications( - @QueryParam("status") String status, + @QueryParam("status") @Size(max = 45) String status, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; @@ -78,7 +81,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement @PUT @Path("/{id}/mark-checked") public Response updateNotificationStatus( - @PathParam("id") int id) { + @PathParam("id") @Max(45)int id) { String msg; Notification.Status status = Notification.Status.CHECKED; Notification notification; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index 487cdc1517..f2aeae680d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java @@ -41,6 +41,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.core.PolicyManagerService; +import javax.validation.Valid; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -59,7 +60,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @POST @Override - public Response addPolicy(PolicyWrapper policyWrapper) { + public Response addPolicy(@Valid PolicyWrapper policyWrapper) { RequestValidationUtil.validatePolicyDetails(policyWrapper); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); @@ -111,7 +112,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } } - private Policy getPolicyFromWrapper(PolicyWrapper policyWrapper) throws DeviceManagementException { + private Policy getPolicyFromWrapper(@Valid PolicyWrapper policyWrapper) throws DeviceManagementException { Policy policy = new Policy(); policy.setPolicyName(policyWrapper.getPolicyName()); policy.setDescription(policyWrapper.getDescription()); @@ -140,6 +141,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policies; List filteredPolicies; @@ -186,7 +188,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @PUT @Path("/{id}") @Override - public Response updatePolicy(@PathParam("id") int id, PolicyWrapper policyWrapper) { + public Response updatePolicy(@PathParam("id") int id, @Valid PolicyWrapper policyWrapper) { RequestValidationUtil.validatePolicyDetails(policyWrapper); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index e0a832a77c..37fe8b214e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java @@ -20,21 +20,23 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.wso2.carbon.CarbonConstants; -import org.wso2.carbon.base.MultitenantConstants; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList; +import org.wso2.carbon.device.mgt.jaxrs.beans.Scope; import org.wso2.carbon.device.mgt.jaxrs.service.api.RoleManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil; import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil; import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer; -import org.wso2.carbon.user.api.*; +import org.wso2.carbon.user.api.AuthorizationManager; +import org.wso2.carbon.user.api.UserRealm; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; -import org.wso2.carbon.user.mgt.UserRealmProxy; -import org.wso2.carbon.user.mgt.common.UIPermissionNode; -import org.wso2.carbon.user.mgt.common.UserAdminException; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -61,6 +63,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { @QueryParam("user-store") String userStore, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); List filteredRoles; RoleList targetRoles = new RoleList(); @@ -87,64 +90,47 @@ public class RoleManagementServiceImpl implements RoleManagementService { } @GET - @Path("/{roleName}/permissions") + @Path("/scopes") @Override - public Response getPermissionsOfRole( - @PathParam("roleName") String roleName, + public Response getScopes( @HeaderParam("If-Modified-Since") String ifModifiedSince) { - RequestValidationUtil.validateRoleName(roleName); - try { - final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); - if (!userRealm.getUserStoreManager().isExistingRole(roleName)) { - return Response.status(Response.Status.NOT_FOUND).entity(new ErrorResponse.ErrorResponseBuilder().setMessage( - "No role exists with the name '" + roleName + "'").build()).build(); - } - final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm); - if (rolePermissions == null) { - if (log.isDebugEnabled()) { - log.debug("No permissions found for the role '" + roleName + "'"); - } + List scopes = new ArrayList<>(); + try { + ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); + if (scopeManagementService == null) { + log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); + } else { + scopes = DeviceMgtUtil.convertAPIScopestoScopes(scopeManagementService.getAllScopes()); } - return Response.status(Response.Status.OK).entity(rolePermissions).build(); - } catch (UserAdminException e) { - String msg = "Error occurred while retrieving the permissions of role '" + roleName + "'"; - log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); - } catch (UserStoreException e) { - String msg = "Error occurred while retrieving the underlying user realm attached to the " + - "current logged in user"; + return Response.status(Response.Status.OK).entity(scopes).build(); + } catch (ScopeManagementException e) { + String msg = "Error occurred while retrieving the scopes"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } - private UIPermissionNode getUIPermissionNode(String roleName, UserRealm userRealm) - throws UserAdminException { - org.wso2.carbon.user.core.UserRealm userRealmCore = null; - if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) { - userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm; - } - final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore); - final UIPermissionNode rolePermissions = - userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID); - UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; - - for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { - if (permissionNode.getResourcePath().equals("/permission/admin")) { - for (UIPermissionNode node : permissionNode.getNodeList()) { - if (node.getResourcePath().equals("/permission/admin/device-mgt")) { - deviceMgtPermissions[0] = node; - } else if (node.getResourcePath().equals("/permission/admin/login")) { - deviceMgtPermissions[1] = node; - } - } + @PUT + @Path("/scopes") + @Override + public Response updateScopes(List scopes) { + RequestValidationUtil.validateScopes(scopes); + try { + ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); + if (scopeManagementService == null) { + log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); + } else { + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(scopes)); } + return Response.status(Response.Status.OK).entity("Scopes has been successfully updated").build(); + } catch (ScopeManagementException e) { + String msg = "Error occurred while updating the scopes"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } - rolePermissions.setNodeList(deviceMgtPermissions); - return rolePermissions; } @GET @@ -159,7 +145,6 @@ public class RoleManagementServiceImpl implements RoleManagementService { RoleInfo roleInfo = new RoleInfo(); try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); - final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userStoreManager.isExistingRole(roleName)) { return Response.status(Response.Status.NOT_FOUND).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + @@ -167,16 +152,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { } roleInfo.setRoleName(roleName); roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName)); - // Get the permission nodes and hand picking only device management and login perms - final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm); - List permList = new ArrayList<>(); - this.iteratePermissions(rolePermissions, permList); - roleInfo.setPermissionList(rolePermissions); - String[] permListAr = new String[permList.size()]; - roleInfo.setPermissions(permList.toArray(permListAr)); return Response.status(Response.Status.OK).entity(roleInfo).build(); - } catch (UserStoreException | UserAdminException e) { + } catch (UserStoreException e) { String msg = "Error occurred while retrieving the user role '" + roleName + "'"; log.error(msg, e); return Response.serverError().entity( @@ -184,35 +162,18 @@ public class RoleManagementServiceImpl implements RoleManagementService { } } - private List iteratePermissions(UIPermissionNode uiPermissionNode, List list) { - for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) { - list.add(permissionNode.getResourcePath()); - if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) { - iteratePermissions(permissionNode, list); - } - } - return list; - } - @POST @Override public Response addRole(RoleInfo roleInfo) { RequestValidationUtil.validateRoleDetails(roleInfo); RequestValidationUtil.validateRoleName(roleInfo.getRoleName()); + try { UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); if (log.isDebugEnabled()) { log.debug("Persisting the role in the underlying user store"); } - Permission[] permissions = null; - if (roleInfo.getPermissions() != null && roleInfo.getPermissions().length > 0) { - permissions = new Permission[roleInfo.getPermissions().length]; - for (int i = 0; i < permissions.length; i++) { - String permission = roleInfo.getPermissions()[i]; - permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION); - } - } - userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions); + userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), null); //TODO fix what's returned in the entity return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity( @@ -268,14 +229,12 @@ public class RoleManagementServiceImpl implements RoleManagementService { userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); } - if (roleInfo.getPermissions() != null) { - // Delete all authorizations for the current role before authorizing the permission tree - authorizationManager.clearRoleAuthorization(roleName); - if (roleInfo.getPermissions().length > 0) { - for (int i = 0; i < roleInfo.getPermissions().length; i++) { - String permission = roleInfo.getPermissions()[i]; - authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION); - } + if (roleInfo.getScopes() != null) { + ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); + if (scopeManagementService == null) { + log.error("Scope management service initialization is failed, hence scopes will not be updated"); + } else { + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(roleInfo.getScopes())); } } //TODO: Need to send the updated role information in the entity back to the client @@ -286,14 +245,21 @@ public class RoleManagementServiceImpl implements RoleManagementService { log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (ScopeManagementException e) { + String msg = "Error occurred while updating scopes of role '" + roleName + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } @DELETE @Path("/{roleName}") @Override - public Response deleteRole(@PathParam("roleName") String roleName) { + public Response deleteRole(@PathParam("roleName") String roleName, RoleInfo roleInfo) { RequestValidationUtil.validateRoleName(roleName); + RequestValidationUtil.validateScopes(roleInfo.getScopes()); + try { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); @@ -311,12 +277,25 @@ public class RoleManagementServiceImpl implements RoleManagementService { // Delete all authorizations for the current role before deleting authorizationManager.clearRoleAuthorization(roleName); + //updating scopes + ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); + if (scopeManagementService == null) { + log.error("Scope management service initialization is failed, hence scopes will not be updated"); + } else { + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(roleInfo.getScopes())); + } + return Response.status(Response.Status.OK).build(); } catch (UserStoreException e) { String msg = "Error occurred while deleting the role '" + roleName + "'"; log.error(msg, e); return Response.serverError().entity( new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } catch (ScopeManagementException e) { + String msg = "Error occurred while updating scopes of role '" + roleName + "'"; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index ffad2e8d81..eda434e2f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; @@ -264,6 +265,7 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("Getting the list of users with all user-related information"); } List userList, offsetList; + RequestValidationUtil.validatePaginationParameters(offset, limit); String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter); int appliedLimit = (limit <= 0) ? -1 : (limit + offset); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 4956583627..cb4b1bb37c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -28,8 +28,10 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -44,12 +46,13 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @Override @GET - public Response getDevicesByName(@QueryParam("name") String name, - @QueryParam("type") String type, + public Response getDevicesByName(@QueryParam("name") @Size(max = 45) String name, + @QueryParam("type") @Size(min = 2, max = 45) String type, @QueryParam("tenant-domain") String tenantDomain, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); try { int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java index 8067c74498..5fad04b0d9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/UserManagementAdminServiceImpl.java @@ -22,6 +22,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.UserManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -34,7 +35,9 @@ public class UserManagementAdminServiceImpl implements UserManagementAdminServic @POST @Path("/{username}/credentials") @Override - public Response resetUserPassword(@PathParam("username") String user, PasswordResetWrapper credentials) { + public Response resetUserPassword(@PathParam("username") + @Size(max = 45) + String user, PasswordResetWrapper credentials) { return CredentialManagementResponseBuilder.buildResetPasswordResponse(user, credentials); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java index 5d0a585ca7..6fbc75264c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java @@ -18,10 +18,12 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; +import org.wso2.carbon.device.mgt.jaxrs.beans.Scope; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.jaxrs.beans.*; + import java.util.ArrayList; import java.util.List; @@ -312,4 +314,31 @@ public class RequestValidationUtil { } } + public static void validateScopes(List scopes) { + if (scopes == null || scopes.isEmpty()) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Scope details of the request body" + + " is incorrect or empty").build()); + } + } + + public static void validatePaginationParameters(int offset, int limit) { + if (offset < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter offset is s " + + "negative value.").build()); + } + if (limit < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter limit is a " + + "negative value.").build()); + } + if (limit - offset > 100) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request results list should" + + " be less than or equal 100 values.").build()); + } + + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java index 2ad4b54aa5..45cadd4738 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/swagger/extension/SecurityDefinitionConfigurator.java @@ -29,7 +29,7 @@ import java.util.HashMap; import java.util.Map; @SwaggerDefinition( - basePath = "/api/device-mgt/v1.0", + basePath = "/api-device-mgt-v1.0", host = "localhost:9443" ) public class SecurityDefinitionConfigurator implements ReaderListener { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java index f7bd1a47e6..451c58b178 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/Constants.java @@ -27,4 +27,18 @@ public class Constants { public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname"; public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname"; + public final class ErrorMessages { + private ErrorMessages () { throw new AssertionError(); } + + public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request"; + + } + + public final class DeviceConstants { + private DeviceConstants () { throw new AssertionError(); } + + public static final String APPLICATION_JSON = "application/json"; + public static final String HEADER_CONTENT_TYPE = "Content-Type"; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java index d9c998c622..aa748fdae5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java @@ -28,6 +28,7 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager; import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService; @@ -248,6 +249,16 @@ public class DeviceMgtAPIUtils { return gadgetDataService; } + public static ScopeManagementService getScopeManagementService() { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ScopeManagementService scopeManagementService = + (ScopeManagementService) ctx.getOSGiService(ScopeManagementService.class, null); + if (scopeManagementService == null) { + throw new IllegalStateException("Scope Management Service has not been initialized."); + } + return scopeManagementService; + } + public static int getTenantId(String tenantDomain) throws DeviceManagementException { RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java index 98461d153a..0c198a1587 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtUtil.java @@ -18,11 +18,17 @@ package org.wso2.carbon.device.mgt.jaxrs.util; +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorListItem; +import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature; +import org.wso2.carbon.device.mgt.jaxrs.exception.BadRequestException; import org.wso2.carbon.policy.mgt.common.Profile; +import javax.validation.ConstraintViolation; import java.util.ArrayList; import java.util.List; +import java.util.Set; public class DeviceMgtUtil { @@ -58,4 +64,77 @@ public class DeviceMgtUtil { return profileFeature; } + + public static List convertScopestoAPIScopes(List scopes) { + List convertedScopes = new ArrayList<>(); + Scope convertedScope; + for (org.wso2.carbon.device.mgt.jaxrs.beans.Scope scope : scopes) { + convertedScope = new Scope(); + convertedScope.setKey(scope.getKey()); + convertedScope.setName(scope.getName()); + convertedScope.setDescription(scope.getDescription()); + convertedScope.setRoles(scope.getRoles()); + convertedScopes.add(convertedScope); + } + return convertedScopes; + } + + public static List convertAPIScopestoScopes(List scopes) { + List convertedScopes = new ArrayList<>(); + org.wso2.carbon.device.mgt.jaxrs.beans.Scope convertedScope; + for (Scope scope : scopes) { + convertedScope = new org.wso2.carbon.device.mgt.jaxrs.beans.Scope(); + convertedScope.setKey(scope.getKey()); + convertedScope.setName(scope.getName()); + convertedScope.setDescription(scope.getDescription()); + convertedScope.setRoles(scope.getRoles()); + convertedScopes.add(convertedScope); + } + return convertedScopes; + } + + /** + * Returns a new BadRequestException + * + * @param description description of the exception + * @return a new BadRequestException with the specified details as a response DTO + */ + public static BadRequestException buildBadRequestException(String description) { + ErrorResponse errorResponse = getErrorResponse(Constants. + ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT,400l, description); + return new BadRequestException(errorResponse); + } + + /** + * Returns generic ErrorResponse. + * @param message specific error message + * @param code + * @param description + * @return generic Response with error specific details. + */ + public static ErrorResponse getErrorResponse(String message, Long code, String description) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setCode(code); + errorResponse.setMoreInfo(""); + errorResponse.setMessage(message); + errorResponse.setDescription(description); + return errorResponse; + } + + public static ErrorResponse getConstraintViolationErrorDTO(Set> violations) { + ErrorResponse errorResponse = new ErrorResponse(); + errorResponse.setDescription("Validation Error"); + errorResponse.setMessage("Bad Request"); + errorResponse.setCode(400l); + errorResponse.setMoreInfo(""); + List errorListItems = new ArrayList<>(); + for (ConstraintViolation violation : violations) { + ErrorListItem errorListItemDTO = new ErrorListItem(); + errorListItemDTO.setCode(400 + "_" + violation.getPropertyPath()); + errorListItemDTO.setMessage(violation.getPropertyPath() + ": " + violation.getMessage()); + errorListItems.add(errorListItemDTO); + } + errorResponse.setErrorItems(errorListItems); + return errorResponse; + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 9e0684004d..050e9089cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -30,379 +30,385 @@ - - Device Management - /device-mgt - / - GET - - - - Device Management Admin - /device-mgt/admin - / - GET - - - Devices - /device-mgt/admin/devices - / - GET - - - - List devices - /device-mgt/admin/devices/List - /devices - GET - - - Search devices - /device-mgt/admin/devices/Search - /devices/search-devices - POST - - - View device - /device-mgt/admin/devices/View - /devices/*/* - GET - - - View device applications - /device-mgt/admin/devices/View-Applications - /devices/*/*/applications - GET - - - View device effective-policy - /device-mgt/admin/devices/View-Active-Policy - /devices/*/*/effective-policy - GET - - - View devices feature - /device-mgt/admin/devices/View-Features - /devices/*/*/features - GET - - - View device operations - /device-mgt/admin/devices/View-Operations - /devices/*/*/operations - GET - - - View Compliance Data - /device-mgt/admin/devices/View-Compliance-Data - /devices/*/*/compliance-data - GET - - - List all devices - /device-mgt/admin/devices/Admin-View - /admin/devices - GET - - - View device types - /device-mgt/admin/devices/Admin-DeviceType-View - /device-types - GET - - - - Policies - /device-mgt/admin/policies - / - GET - - - - List policies - /device-mgt/admin/policies/List - /policies - GET - - - Add Policy - /device-mgt/admin/policies/Add - /policies - POST - - - Activate policy - /device-mgt/admin/policies/Activate-Policy - /policies/activate-policy - PUT - - - Deactivate Policy - /device-mgt/admin/policies/Deactivate-Policy - /policies/deactivate-policy - PUT - - - Remove Policy - /device-mgt/admin/policies/Remove - /policies/remove-policy - POST - - - View Policy - /device-mgt/admin/policies/View - /policies/* - GET - - - Update Policy - /device-mgt/admin/policies/Update - /policies/* - PUT - - - Update Policy - /device-mgt/admin/policies/Update - /policies/apply-changes - PUT - - - Update Policy - /device-mgt/admin/policies/Change-Priority - /policies/priorities - PUT - - - - Notifications - /device-mgt/admin/notifications - / - GET - - - - View notifications - /device-mgt/admin/notifications/View - /notifications - GET - - - Mark checked notifications - /device-mgt/admin/notifications/View - /notifications/*/mark-checked - PUT - - - - Users - /device-mgt/admin/users - / - GET - - - - List users - /device-mgt/admin/users/List - /users - GET - - - Add user - /device-mgt/admin/users/Add - /users - POST - - - List users - /device-mgt/admin/users/Search - /users/search/usernames - GET - - - Remove user - /device-mgt/admin/users/Remove - /users/* - DELETE - - - View user - /device-mgt/admin/users/View - /users/* - GET - - - Update user - /device-mgt/admin/users/Update - /users/* - PUT - - - Update user credentials - /device-mgt/admin/users/Change-Password - /users/*/credentials - PUT - - - View assigned role - /device-mgt/admin/roles/Assigned-Roles - /users/*/roles - GET - - - Change any user credentials - /device-mgt/admin/users/Change-Password-Any - /admin/users/*/credentials - POST - - - Send invitation mail - /device-mgt/admin/users/Send-invitations - /users/send-invitation - POST - - - - Roles - /device-mgt/admin/roles - / - GET - - - - List roles - /device-mgt/admin/roles/List - /roles - GET - - - Add role - /device-mgt/admin/roles/Add - /roles - POST - - - Remove role - /device-mgt/admin/roles/Remove - /roles/* - DELETE - - - View role - /device-mgt/admin/roles/View - /roles/* - GET - - - Update role - /device-mgt/admin/roles/Update - /roles/* - PUT - - - View role permissions - /device-mgt/admin/roles/View-Permission - /roles/*/permissions - GET - - - Add Users to role - /device-mgt/admin/roles/Add-Users - /roles/*/users - PUT - - - - Configurations - /device-mgt/admin/general-configs - / - GET - - - - View configuration - /device-mgt/admin/general-configuration/View - /configuration - GET - - - Update configuration - /device-mgt/admin/general-configuration/Update - /configuration - PUT - - - - Activities - /device-mgt/admin/activities - / - GET - - - - View Activities - /device-mgt/admin/activities/View - /activities - GET - - - View Activity Details - /device-mgt/admin/activities/View - /activities/* - GET - - - - Applications - /device-mgt/admin/applications - / - GET - - - - Install Applications - /device-mgt/admin/application/Install - /admin/applications/install-application - POST - - - Uninstall-Applications - /device-mgt/admin/application/Uninstall - /admin/applications/uninstall-application - POST - - - - - - Device Management User - /device-mgt/user - / - GET - - - User Devices - /device-mgt/user/devices - / - GET - - - User Policies - /device-mgt/user/policies - / - GET - - - User Notifications - /device-mgt/user/notifications - / - GET - - - User Operations - /device-mgt/user/operations - / - GET - - + + Device Management + /device-mgt + / + GET + + + + Device Management Admin + /device-mgt/admin + / + GET + + + Devices + /device-mgt/admin/devices + / + GET + + + + List devices + /device-mgt/admin/devices/List + /devices + GET + + + Search devices + /device-mgt/admin/devices/Search + /devices/search-devices + POST + + + View device + /device-mgt/admin/devices/View + /devices/*/* + GET + + + View device info + /device-mgt/admin/devices/View + /devices/*/*/info + GET + + + View device applications + /device-mgt/admin/devices/View-Applications + /devices/*/*/applications + GET + + + View device effective-policy + /device-mgt/admin/devices/View-Active-Policy + /devices/*/*/effective-policy + GET + + + View devices feature + /device-mgt/admin/devices/View-Features + /devices/*/*/features + GET + + + View device operations + /device-mgt/admin/devices/View-Operations + /devices/*/*/operations + GET + + + View Compliance Data + /device-mgt/admin/devices/View-Compliance-Data + /devices/*/*/compliance-data + GET + + + List all devices + /device-mgt/admin/devices/Admin-View + /admin/devices + GET + + + View device types + /device-mgt/admin/devices/Admin-DeviceType-View + /admin/device-types + GET + + + + Policies + /device-mgt/admin/policies + / + GET + + + + List policies + /device-mgt/admin/policies/List + /policies + GET + + + Add Policy + /device-mgt/admin/policies/Add + /policies + POST + + + Activate policy + /device-mgt/admin/policies/Activate-Policy + /policies/activate-policy + PUT + + + Deactivate Policy + /device-mgt/admin/policies/Deactivate-Policy + /policies/deactivate-policy + PUT + + + Remove Policy + /device-mgt/admin/policies/Remove + /policies/remove-policy + POST + + + View Policy + /device-mgt/admin/policies/View + /policies/* + GET + + + Update Policy + /device-mgt/admin/policies/Update + /policies/* + PUT + + + Update Policy + /device-mgt/admin/policies/Update + /policies/apply-changes + PUT + + + Update Policy + /device-mgt/admin/policies/Change-Priority + /policies/priorities + PUT + + + + Notifications + /device-mgt/admin/notifications + / + GET + + + + View notifications + /device-mgt/admin/notifications/View + /notifications + GET + + + Mark checked notifications + /device-mgt/admin/notifications/View + /notifications/*/mark-checked + PUT + + + + Users + /device-mgt/admin/users + / + GET + + + + List users + /device-mgt/admin/users/List + /users + GET + + + Add user + /device-mgt/admin/users/Add + /users + POST + + + List users + /device-mgt/admin/users/Search + /users/search/usernames + GET + + + Remove user + /device-mgt/admin/users/Remove + /users/* + DELETE + + + View user + /device-mgt/admin/users/View + /users/* + GET + + + Update user + /device-mgt/admin/users/Update + /users/* + PUT + + + Update user credentials + /device-mgt/admin/users/Change-Password + /users/*/credentials + PUT + + + View assigned role + /device-mgt/admin/roles/Assigned-Roles + /users/*/roles + GET + + + Change any user credentials + /device-mgt/admin/users/Change-Password-Any + /admin/users/*/credentials + POST + + + Send invitation mail + /device-mgt/admin/users/Send-invitations + /users/send-invitation + POST + + + + Roles + /device-mgt/admin/roles + / + GET + + + + List roles + /device-mgt/admin/roles/List + /roles + GET + + + Add role + /device-mgt/admin/roles/Add + /roles + POST + + + Remove role + /device-mgt/admin/roles/Remove + /roles/* + DELETE + + + View role + /device-mgt/admin/roles/View + /roles/* + GET + + + Update role + /device-mgt/admin/roles/Update + /roles/* + PUT + + + View role permissions + /device-mgt/admin/roles/View-Permission + /roles/*/permissions + GET + + + Add Users to role + /device-mgt/admin/roles/Add-Users + /roles/*/users + PUT + + + + Configurations + /device-mgt/admin/general-configs + / + GET + + + + View configuration + /device-mgt/admin/general-configuration/View + /configuration + GET + + + Update configuration + /device-mgt/admin/general-configuration/Update + /configuration + PUT + + + + Activities + /device-mgt/admin/activities + / + GET + + + + View Activities + /device-mgt/admin/activities/View + /activities + GET + + + View Activity Details + /device-mgt/admin/activities/View + /activities/* + GET + + + + Applications + /device-mgt/admin/applications + / + GET + + + + Install Applications + /device-mgt/admin/application/Install + /admin/applications/install-application + POST + + + Uninstall-Applications + /device-mgt/admin/application/Uninstall + /admin/applications/uninstall-application + POST + + + + + + Device Management User + /device-mgt/user + / + GET + + + User Devices + /device-mgt/user/devices + / + GET + + + User Policies + /device-mgt/user/policies + / + GET + + + User Notifications + /device-mgt/user/notifications + / + GET + + + User Operations + /device-mgt/user/operations + / + GET + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index d225d36995..8405fb99fc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -17,12 +17,11 @@ ~ under the License. --> - + @@ -51,6 +50,8 @@ + + @@ -80,6 +81,12 @@ + + + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml index d8950c54e6..adfb7059fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml @@ -50,6 +50,7 @@ javax.xml.bind.annotation, com.fasterxml.jackson.annotation, + org.wso2.carbon.apimgt.api.model, io.swagger.annotations.*;resolution:=optional @@ -68,6 +69,10 @@ com.fasterxml.jackson.core jackson-annotations + + org.wso2.carbon.apimgt + org.wso2.carbon.apimgt.api + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java index 1eb5e28e46..1849a97c0d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java @@ -29,12 +29,12 @@ public class DeviceTypeIdentifier implements Serializable { private static final int DEFAULT_SHARE_WITH_ALL_TENANTS_ID = -1; public DeviceTypeIdentifier(String deviceType, int tenantId) { - this.deviceType = deviceType; + this.deviceType = deviceType.toLowerCase(); this.tenantId = tenantId; } public DeviceTypeIdentifier(String deviceType) { - this.deviceType = deviceType; + this.deviceType = deviceType.toLowerCase(); this.tenantId = DEFAULT_SHARE_WITH_ALL_TENANTS_ID; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java index 2ba839243c..70e666431c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/EnrolmentInfo.java @@ -40,11 +40,9 @@ public class EnrolmentInfo implements Serializable { @ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.", required = true) private int id; - @ApiModelProperty(name = "device", value = "Enrolled device.", required = true) - private Device device; - @ApiModelProperty(name = "dateOfEnrolment", value = "Date of the device enrollment.", required = true ) + @ApiModelProperty(name = "dateOfEnrolment", value = "Date of the device enrollment. This value is not necessary.", required = false ) private Long dateOfEnrolment; - @ApiModelProperty(name = "dateOfLastUpdate", value = "Date of the device's last update.", required = true ) + @ApiModelProperty(name = "dateOfLastUpdate", value = "Date of the device's last update. This value is not necessary.", required = false ) private Long dateOfLastUpdate; @ApiModelProperty(name = "ownership", value = "Defines the ownership details. The ownership type can be any of the" + " following values.\n" + @@ -60,8 +58,7 @@ public class EnrolmentInfo implements Serializable { public EnrolmentInfo() { } - public EnrolmentInfo(Device device, String owner, OwnerShip ownership, Status status) { - this.device = device; + public EnrolmentInfo(String owner, OwnerShip ownership, Status status) { this.owner = owner; this.ownership = ownership; this.status = status; @@ -115,14 +112,6 @@ public class EnrolmentInfo implements Serializable { this.owner = owner; } - public Device getDevice() { - return device; - } - - public void setDevice(Device device) { - this.device = device; - } - @Override public boolean equals(Object obj) { if (obj instanceof EnrolmentInfo) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java index 433553b2da..148cc1781a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java @@ -41,7 +41,7 @@ public class PaginationResult implements Serializable { @ApiModelProperty(name = "draw", value = "The draw counter that this object is a response to, from the draw parameter sent as part of the data request", required = true) private int draw; - @ApiModelProperty(name = "data", value = "The details of the SSL certificate", required = true) + @ApiModelProperty(name = "data", value = "This holds the database records that matches given criteria", required = true) private List data; public int getRecordsTotal() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java index 82e3108149..ecbafd974c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/app/mgt/Application.java @@ -150,6 +150,9 @@ public class Application implements Serializable { if (applicationIdentifier != null ? !applicationIdentifier.equals(that.applicationIdentifier) : that.applicationIdentifier != null) { return false; } + if (version != null ? !version.equals(that.version) : that.version != null) { + return false; + } return true; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java index ad92cb27d8..6ba2f675c0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java @@ -24,47 +24,25 @@ import javax.xml.bind.annotation.XmlRootElement; /** * This class represents the information related to permission. */ -@XmlRootElement (name = "Permission") public class Permission { - private String name; // permission name - private String path; // permission string private String url; // url of the resource + private String urlTemplate; // resource template private String method; // http method - private String scope; //scope of the resource + private String context; - public String getName() { - return name; + public String getContext() { + return context; } - @XmlElement (name = "name", required = true) - public void setName(String name) { - this.name = name; + public void setContext(String context) { + this.context = context; } - public String getPath() { - return path; - } - - @XmlElement (name = "path", required = true) - public void setPath(String path) { - this.path = path; - } - - public String getScope() { - return scope; - } - - @XmlElement(name = "scope", required = false) - public void setScope(String scope) { - this.scope = scope; - } - public String getUrl() { return url; } - @XmlElement (name = "url", required = true) public void setUrl(String url) { this.url = url; } @@ -73,8 +51,15 @@ public class Permission { return method; } - @XmlElement (name = "method", required = true) public void setMethod(String method) { this.method = method; } + + public String getUrlTemplate() { + return urlTemplate; + } + + public void setUrlTemplate(String urlTemplate) { + this.urlTemplate = urlTemplate; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java index 30b771565d..10bb59bcb4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java @@ -29,11 +29,10 @@ public interface PermissionManagerService { /** * * @param permission - Permission to be added - * @return The status of the operation. * @throws PermissionManagementException If some unusual behaviour is observed while adding the * permission. */ - boolean addPermission(Permission permission) throws PermissionManagementException; + void addPermission(Permission permission) throws PermissionManagementException; /** * diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java new file mode 100644 index 0000000000..ed5082a72c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java @@ -0,0 +1,57 @@ +/* +* Copyright (c) 2014, 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. +* 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.common.scope.mgt; + +/** + * This exception is used to throw when there is an issue in scope management service. + */ +public class ScopeManagementException extends Exception { + + private static final long serialVersionUID = -315127931137779899L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public ScopeManagementException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public ScopeManagementException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public ScopeManagementException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public ScopeManagementException() { + super(); + } + + public ScopeManagementException(Throwable cause) { + super(cause); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java new file mode 100644 index 0000000000..b90011aaf0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +* +* WSO2 Inc. licenses this file to you under the Apache License, +* Version 2.0 (the "License"); you may not use this file except +* in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ + +package org.wso2.carbon.device.mgt.common.scope.mgt; + +import java.util.List; +import org.wso2.carbon.apimgt.api.model.Scope; + +/** + * This interface contains the basic operations related to scope management. + */ +public interface ScopeManagementService { + + /** + * This method is used to update the given list of scopes. + * + * @param scopes List of scopes to be updated. + * @throws ScopeManagementException + */ + void updateScopes(List scopes) throws ScopeManagementException; + + /** + * This method is used to retrieve all the scopes. + * + * @return List of scopes. + * @throws ScopeManagementException + */ + List getAllScopes() throws ScopeManagementException; + + /** + * This method is to retrieve the roles of the given scope + * @param scopeKey key of the scope + * @return List of roles + * @throws ScopeManagementException + */ + String getRolesOfScope(String scopeKey) throws ScopeManagementException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index b96ddcac8d..e317b1d1b9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml @@ -91,6 +91,10 @@ !org.wso2.carbon.device.mgt.core.internal, org.wso2.carbon.device.mgt.core.* + + javax.ws.rs-api, + scribe;scope=compile|runtime;inline=false; + * @@ -228,6 +232,7 @@ commons-collections.wso2 commons-collections + org.wso2.carbon.devicemgt org.wso2.carbon.email.sender.core @@ -236,15 +241,12 @@ mysql mysql-connector-java - 5.1.34 test - com.google.code.gson gson - 1.7.1 @@ -253,6 +255,26 @@ provided + + org.wso2.orbit.org.scannotation + scannotation + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.apimgt.annotations + + + + javax.ws.rs + javax.ws.rs-api + + + + javax.ws.rs + jsr311-api + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java index 379ca8c3d6..62e38e6a66 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java @@ -26,7 +26,7 @@ public final class DeviceManagementConstants { throw new AssertionError(); } - public static final String PROPERTY_SETUP = "setup"; + public static final String SETUP_PROPERTY = "setup"; public static final String DEFAULT_LICENSE_CONFIG_XML_NAME = "license-config.xml"; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index d55f553920..504d29d5f1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -52,7 +52,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getType(); + String deviceType = provider.getType().toLowerCase(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); String tenantDomain = provisioningConfig.getProviderTenantDomain(); @@ -87,7 +87,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceTypeName = provider.getType(); + String deviceTypeName = provider.getType().toLowerCase(); DeviceTypeIdentifier deviceTypeIdentifier; ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); if (provisioningConfig.isSharedWithAllTenants()) { @@ -103,10 +103,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public DeviceManagementService getDeviceManagementService(String type, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type, tenantId); + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase(), tenantId); DeviceManagementService provider = providers.get(deviceTypeIdentifier); if (provider == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(type); + deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase()); provider = providers.get(deviceTypeIdentifier); } return provider; @@ -153,10 +153,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public OperationManager getOperationManager(String deviceType, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType, tenantId); + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase(), tenantId); OperationManager operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); if (operationManager == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType); + deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase()); operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); } return operationManager; @@ -164,14 +164,15 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis @Override public void notifyObserver() { + String deviceTypeName; synchronized (providers) { for (DeviceManagementService provider : providers.values()) { try { provider.init(); - + deviceTypeName = provider.getType().toLowerCase(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); int tenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); - DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provisioningConfig.isSharedWithAllTenants()); + DeviceManagerUtil.registerDeviceType(deviceTypeName, tenantId, provisioningConfig.isSharedWithAllTenants()); registerPushNotificationStrategy(provider); //TODO: //This is a temporory fix. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java index 18f61261f0..d03d7b1612 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java @@ -97,8 +97,8 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem if (deviceIds.size() > 0) { type = deviceIds.get(0).getType().toLowerCase(); } - Activity activity = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). - addOperation(type, operation, deviceIds); + Activity activity = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider(). + addOperation(type, operation, deviceIds); DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().notifyOperationToDevices (operation, deviceIds); return activity; @@ -217,13 +217,14 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem appIdsToRemove.add(installedApp.getId()); } } - + applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId); Application installedApp; List applicationIds = new ArrayList<>(); for (Application application : applications) { if (!installedAppList.contains(application)) { - installedApp = applicationDAO.getApplication(application.getApplicationIdentifier(), tenantId); + installedApp = applicationDAO.getApplication(application.getApplicationIdentifier(), + application.getVersion(), tenantId); if (installedApp == null) { appsToAdd.add(application); } else { @@ -244,7 +245,7 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem if (log.isDebugEnabled()) { log.debug("num of remove app Ids:" + appIdsToRemove.size()); } - applicationMappingDAO.removeApplicationMapping(device.getId(), appIdsToRemove, tenantId); + DeviceManagementDAOFactory.commitTransaction(); } catch (DeviceManagementDAOException e) { DeviceManagementDAOFactory.rollbackTransaction(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java index 27bbcc13ef..60b791a5fa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java @@ -63,7 +63,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori throws DeviceAccessAuthorizationException { int tenantId = this.getTenantId(); if (username == null || username.isEmpty()) { - return false; + return !DeviceManagementDataHolder.getInstance().requireDeviceAuthorization(deviceIdentifier.getType()); } //check for admin and ownership permissions if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) { @@ -243,9 +243,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori } private boolean addAdminPermissionToRegistry() throws PermissionManagementException { - Permission permission = new Permission(); - permission.setPath(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION)); - return PermissionUtils.putPermission(permission); + return PermissionUtils.putPermission(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION)); } private Map getOwnershipOfDevices(List devices) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java index 0891164cb0..20e4eba5c2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.config; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; +import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; @@ -37,6 +38,7 @@ public final class DeviceManagementConfig { private TaskConfiguration taskConfiguration; private IdentityConfigurations identityConfigurations; private PolicyConfiguration policyConfiguration; + private PaginationConfiguration paginationConfiguration; private List pushNotificationProviders; @@ -87,5 +89,14 @@ public final class DeviceManagementConfig { this.pushNotificationProviders = pushNotificationProviders; } + @XmlElement(name = "PaginationConfiguration", required = true) + public PaginationConfiguration getPaginationConfiguration() { + return paginationConfiguration; + } + + public void setPaginationConfiguration(PaginationConfiguration paginationConfiguration) { + this.paginationConfiguration = paginationConfiguration; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java new file mode 100644 index 0000000000..f60f33d98f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.config.pagination; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class represents the information related to Pagination configuration. + */ +@XmlRootElement(name = "PaginationConfiguration") +public class PaginationConfiguration { + + private int deviceListPageSize; + private int operationListPageSize; + private int notificationListPageSize; + private int activityListPageSize; + + public int getDeviceListPageSize() { + return deviceListPageSize; + } + + @XmlElement(name = "DeviceListPageSize", required = true) + public void setDeviceListPageSize(int deviceListPageSize) { + this.deviceListPageSize = deviceListPageSize; + } + + public int getOperationListPageSize() { + return operationListPageSize; + } + + @XmlElement(name = "OperationListPageSize", required = true) + public void setOperationListPageSize(int operationListPageSize) { + this.operationListPageSize = operationListPageSize; + } + + public int getNotificationListPageSize() { + return notificationListPageSize; + } + + @XmlElement(name = "NotificationListPageSize", required = true) + public void setNotificationListPageSize(int notificationListPageSize) { + this.notificationListPageSize = notificationListPageSize; + } + + public int getActivityListPageSize() { + return activityListPageSize; + } + + @XmlElement(name = "ActivityListPageSize", required = true) + public void setActivityListPageSize(int activityListPageSize) { + this.activityListPageSize = activityListPageSize; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java new file mode 100644 index 0000000000..a847255a6e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java @@ -0,0 +1,332 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.config.permission; + +import org.apache.catalina.core.StandardContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.scannotation.AnnotationDB; +import org.wso2.carbon.apimgt.annotations.api.API; + +import javax.servlet.ServletContext; +import javax.ws.rs.*; +import java.io.File; +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.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.StringTokenizer; + +public class AnnotationProcessor { + + private static final Log log = LogFactory.getLog(AnnotationProcessor.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"; + private static final String WILD_CARD = "/*"; + private static final String URL_SEPARATOR = "/"; + + private static final String STRING_ARR = "string_arr"; + private static final String STRING = "string"; + + private Method[] pathClazzMethods; + private Class pathClazz; + Class apiClazz; + private ClassLoader classLoader; + private ServletContext servletContext; + + + public AnnotationProcessor(final StandardContext context) { + servletContext = context.getServletContext(); + classLoader = servletContext.getClassLoader(); + } + + /** + * Scan the context for classes with annotations + * + * @return + * @throws IOException + */ + public Set scanStandardContext(String className) throws IOException { + ExtendedAnnotationDB db = new ExtendedAnnotationDB(); + db.addIgnoredPackages(PACKAGE_ORG_APACHE); + db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); + db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); + URL classPath = findWebInfClassesPath(servletContext); + db.scanArchives(classPath); + + //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 + * + * @param entityClasses + * @return + */ + public List + extractPermissions(Set entityClasses) { + + List permissions = new ArrayList<>(); + + if (entityClasses != null && !entityClasses.isEmpty()) { + + for (final String className : entityClasses) { + + List resourcePermissions = + AccessController.doPrivileged(new PrivilegedAction>() { + public List run() { + Class clazz; + List apiPermissions = + new ArrayList<>(); + try { + clazz = classLoader.loadClass(className); + + apiClazz = (Class) + classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API + .class.getName()); + + Annotation apiAnno = clazz.getAnnotation(apiClazz); + List resourceList; + + if (apiAnno != null) { + + if (log.isDebugEnabled()) { + log.debug("Application Context root = " + servletContext.getContextPath()); + } + + try { + String rootContext = servletContext.getContextPath(); + pathClazz = (Class) classLoader.loadClass(Path.class.getName()); + pathClazzMethods = pathClazz.getMethods(); + + Annotation rootContectAnno = clazz.getAnnotation(pathClazz); + String subContext = ""; + if (rootContectAnno != null) { + subContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING); + if (subContext != null && !subContext.isEmpty()) { + if (subContext.trim().startsWith("/")) { + rootContext = rootContext + subContext; + } else { + rootContext = rootContext + "/" + subContext; + } + } + if (log.isDebugEnabled()) { + log.debug("API Root Context = " + rootContext); + } + } + + Method[] annotatedMethods = clazz.getDeclaredMethods(); + apiPermissions = getApiResources(rootContext, annotatedMethods); + } catch (Throwable throwable) { + log.error("Error encountered while scanning for annotations", throwable); + } + } + } catch (ClassNotFoundException e) { + log.error("Error when passing the api annotation for device type apis."); + } + return apiPermissions; + } + }); + permissions.addAll(resourcePermissions); + } + } + return permissions; + } + + + /** + * Get Resources for each API + * + * @param resourceRootContext + * @param annotatedMethods + * @return + * @throws Throwable + */ + private List + getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable { + + List permissions = new ArrayList<>(); + String subCtx; + for (Method method : annotatedMethods) { + Annotation[] annotations = method.getDeclaredAnnotations(); + org.wso2.carbon.device.mgt.common.permission.mgt.Permission permission = + new org.wso2.carbon.device.mgt.common.permission.mgt.Permission(); + + if (isHttpMethodAvailable(annotations)) { + Annotation methodContextAnno = method.getAnnotation(pathClazz); + if (methodContextAnno != null) { + subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING); + } else { + subCtx = WILD_CARD; + } + permission.setContext(makeContextURLReady(resourceRootContext)); + permission.setUrlTemplate(makeContextURLReady(subCtx)); + + // this check is added to avoid url resolving conflict which happens due + // to adding of '*' notation for dynamic path variables. + if (WILD_CARD.equals(subCtx)) { + subCtx = makeContextURLReady(resourceRootContext); + } else { + subCtx = makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx); + } + permission.setUrl(replaceDynamicPathVariables(subCtx)); + String httpMethod; + for (int i = 0; i < annotations.length; i++) { + httpMethod = getHTTPMethodAnnotation(annotations[i]); + if (httpMethod != null) { + permission.setMethod(httpMethod); + break; + } + } + permissions.add(permission); + } + } + return permissions; + } + + /** + * Read Method annotations indicating HTTP Methods + * @param annotation + */ + private String getHTTPMethodAnnotation(Annotation annotation) { + if (annotation.annotationType().getName().equals(GET.class.getName())) { + return HttpMethod.GET; + } else if (annotation.annotationType().getName().equals(POST.class.getName())) { + return HttpMethod.POST; + } else if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) { + return HttpMethod.OPTIONS; + } else if (annotation.annotationType().getName().equals(DELETE.class.getName())) { + return HttpMethod.DELETE; + } else if (annotation.annotationType().getName().equals(PUT.class.getName())) { + return HttpMethod.PUT; + } + return null; + } + + private boolean isHttpMethodAvailable(Annotation[] annotations) { + for (Annotation annotation : annotations) { + if (annotation.annotationType().getName().equals(GET.class.getName())) { + return true; + } else if (annotation.annotationType().getName().equals(POST.class.getName())) { + return true; + } else if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) { + return true; + } else if (annotation.annotationType().getName().equals(DELETE.class.getName())) { + return true; + } else if (annotation.annotationType().getName().equals(PUT.class.getName())) { + return true; + } + } + return false; + } + + /** + * Append '/' to the context and make it URL ready + * + * @param context + * @return + */ + private String makeContextURLReady(String context) { + if (context != null && ! context.isEmpty()) { + if (context.startsWith("/")) { + return context; + } else { + return "/" + context; + } + } + return ""; + } + + /** + * When an annotation and method is passed, this method invokes that executes said method against the annotation + * + * @param method + * @param annotation + * @param returnType + * @return + * @throws Throwable + */ + 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; + } + } + + + /** + * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory + * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory + * + * @param servletContext + * @return null if cannot determin /WEB-INF/classes + */ + public static URL findWebInfClassesPath(ServletContext servletContext) + { + String path = servletContext.getRealPath("/WEB-INF/classes"); + if (path == null) return null; + File fp = new File(path); + if (fp.exists() == false) return null; + try + { + URI uri = fp.toURI(); + return uri.toURL(); + } + catch (MalformedURLException e) + { + throw new RuntimeException(e); + } + } + + private String replaceDynamicPathVariables(String path) { + StringBuilder replacedPath = new StringBuilder(); + StringTokenizer st = new StringTokenizer(path, URL_SEPARATOR); + String currentToken; + while (st.hasMoreTokens()) { + currentToken = st.nextToken(); + if (currentToken.charAt(0) == '{') { + if (currentToken.charAt(currentToken.length() - 1) == '}') { + replacedPath.append(WILD_CARD); + } + } else { + replacedPath.append(URL_SEPARATOR); + replacedPath.append(currentToken); + } + } + return replacedPath.toString(); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java new file mode 100644 index 0000000000..dbbd97e3a6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java @@ -0,0 +1,92 @@ +/* +* Copyright (c) 2014, 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. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.core.config.permission; + +import org.scannotation.AnnotationDB; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +public class ExtendedAnnotationDB extends AnnotationDB { + + public ExtendedAnnotationDB() { + super(); + } + + public void scanArchives(URL... urls) throws IOException { + URL[] arr$ = urls; + int len$ = urls.length; + + for(int i$ = 0; i$ < len$; ++i$) { + URL url = arr$[i$]; + Filter filter = new Filter() { + public boolean accepts(String filename) { + if(filename.endsWith(".class")) { + if(filename.startsWith("/") || filename.startsWith("\\")) { + filename = filename.substring(1); + } + + if(!ExtendedAnnotationDB.this.ignoreScan(filename.replace('/', '.'))) { + return true; + } + } + return false; + } + }; + StreamIterator it = ExtendedIteratorFactory.create(url, filter); + + InputStream stream; + while((stream = it.next()) != null) { + this.scanClass(stream); + } + } + + } + + private boolean ignoreScan(String intf) { + String[] arr$; + int len$; + int i$; + String ignored; + if(this.scanPackages != null) { + arr$ = this.scanPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return false; + } + } + + return true; + } else { + arr$ = this.ignoredPackages; + len$ = arr$.length; + + for(i$ = 0; i$ < len$; ++i$) { + ignored = arr$[i$]; + if(intf.startsWith(ignored + ".")) { + return true; + } + } + return false; + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java new file mode 100644 index 0000000000..1394375656 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java @@ -0,0 +1,32 @@ +/* +* Copyright (c) 2014, 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. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.core.config.permission; + +import org.scannotation.archiveiterator.*; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class ExtendedFileProtocolIteratorFactory implements DirectoryIteratorFactory { + + @Override + public StreamIterator create(URL url, Filter filter) throws IOException { + File f = new File(java.net.URLDecoder.decode(url.getPath(), "UTF-8")); + return f.isDirectory()?new FileIterator(f, filter):new JarIterator(url.openStream(), filter); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java new file mode 100644 index 0000000000..18c8b7620c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java @@ -0,0 +1,54 @@ +/* +* Copyright (c) 2014, 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. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package org.wso2.carbon.device.mgt.core.config.permission; + +import org.scannotation.archiveiterator.DirectoryIteratorFactory; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.JarIterator; +import org.scannotation.archiveiterator.StreamIterator; + +import java.io.IOException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; + +public class ExtendedIteratorFactory { + + private static final ConcurrentHashMap registry = new ConcurrentHashMap(); + + public static StreamIterator create(URL url, Filter filter) throws IOException { + String urlString = url.toString(); + if(urlString.endsWith("!/")) { + urlString = urlString.substring(4); + urlString = urlString.substring(0, urlString.length() - 2); + url = new URL(urlString); + } + + if(!urlString.endsWith("/")) { + return new JarIterator(url.openStream(), filter); + } else { + DirectoryIteratorFactory factory = registry.get(url.getProtocol()); + if(factory == null) { + throw new IOException("Unable to scan directory of protocol: " + url.getProtocol()); + } else { + return factory.create(url, filter); + } + } + } + + static { + registry.put("file", new ExtendedFileProtocolIteratorFactory()); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java index f974ea5f20..7911ff7cdf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java @@ -25,29 +25,27 @@ import javax.xml.bind.annotation.XmlRootElement; import java.util.List; /** - * This class represents the information related to permission configuration. + * This class represents the information related to permissions. */ -@XmlRootElement (name = "PermissionConfiguration") public class PermissionConfiguration { - private List permissions; - private String apiVersion; + private String scopeName; + private String[] permissions; - public String getApiVersion() { - return apiVersion; + public String getScopeName() { + return scopeName; } - @XmlElement (name = "APIVersion", required = true) - public void setApiVersion(String apiVersion) { - this.apiVersion = apiVersion; + public void setScopeName(String scope) { + this.scopeName = scope; } - public List getPermissions() { + public String[] getPermissions() { return permissions; } - @XmlElement (name = "Permission", required = true) - public void setPermissions(List permissions) { + public void setPermissions(String[] permissions) { this.permissions = permissions; } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java index f274eee845..fbde8047e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java @@ -26,6 +26,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; +import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; +import org.wso2.carbon.device.mgt.core.config.permission.AnnotationProcessor; import org.wso2.carbon.device.mgt.core.config.permission.PermissionConfiguration; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils; @@ -35,8 +37,10 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.util.List; +import java.util.Set; /** * This listener class will initiate the permission addition of permissions defined in @@ -45,7 +49,8 @@ import java.util.List; @SuppressWarnings("unused") public class WebAppDeploymentLifecycleListener implements LifecycleListener { - private static final String PERMISSION_CONFIG_PATH = "META-INF" + File.separator + "permissions.xml"; + private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled"; + private static final Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class); @Override @@ -54,34 +59,27 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener { StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); ServletContext servletContext = context.getServletContext(); String contextPath = context.getServletContext().getContextPath(); - try { - InputStream permissionStream = servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH); - if (permissionStream != null) { - /* Un-marshaling Device Management configuration */ - JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class); - Unmarshaller unmarshaller = cdmContext.createUnmarshaller(); - PermissionConfiguration permissionConfiguration = (PermissionConfiguration) - unmarshaller.unmarshal(permissionStream); - List permissions = permissionConfiguration.getPermissions(); - String apiVersion = permissionConfiguration.getApiVersion(); - if (permissionConfiguration != null && permissions != null) { + String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); + boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); + + if (isManagedApi) { + try { + AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); + Set annotatedAPIClasses = annotationProcessor. + scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); + List permissions = annotationProcessor.extractPermissions(annotatedAPIClasses); + PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance(); + if (permissions != null) { for (Permission permission : permissions) { - // update the permission path to absolute permission path - permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath())); - permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion, - permission.getUrl()).toLowerCase()); - permission.setMethod(permission.getMethod().toUpperCase()); - PermissionManagerServiceImpl.getInstance().addPermission(permission); + permissionManagerService.addPermission(permission); } } + } catch (PermissionManagementException e) { + log.error("Exception occurred while adding the permissions from webapp : " + + servletContext.getContextPath(), e); + } catch (IOException e) { + log.error("Cannot find API annotation Class in the webapp '" + contextPath + "' class path", e); } - } catch (JAXBException e) { - log.error( - "Exception occurred while parsing the permission configuration of webapp : " - + context.getServletContext().getContextPath(), e); - } catch (PermissionManagementException e) { - log.error("Exception occurred while adding the permissions from webapp : " - + servletContext.getContextPath(), e); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/ApplicationDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/ApplicationDAO.java index 5cc8b3c7d6..e5e91f28bc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/ApplicationDAO.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/ApplicationDAO.java @@ -32,5 +32,7 @@ public interface ApplicationDAO { Application getApplication(String identifier, int tenantId) throws DeviceManagementDAOException; + Application getApplication(String identifier, String version,int tenantId) throws DeviceManagementDAOException; + List getInstalledApplications(int deviceId) throws DeviceManagementDAOException; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java index a9312623ae..c391f1057f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationDAOImpl.java @@ -228,6 +228,34 @@ public class ApplicationDAOImpl implements ApplicationDAO { } } + @Override + public Application getApplication(String identifier, String version, int tenantId) throws DeviceManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + Application application = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement("SELECT ID, NAME, APP_IDENTIFIER, PLATFORM, CATEGORY, VERSION, TYPE, " + + "LOCATION_URL, IMAGE_URL, APP_PROPERTIES, MEMORY_USAGE, IS_ACTIVE, TENANT_ID FROM DM_APPLICATION WHERE APP_IDENTIFIER = ? " + + "AND VERSION = ? AND TENANT_ID = ?"); + stmt.setString(1, identifier); + stmt.setString(2, version); + stmt.setInt(3, tenantId); + rs = stmt.executeQuery(); + + if (rs.next()) { + application = this.loadApplication(rs); + } + return application; + } catch (SQLException e) { + throw new DeviceManagementDAOException("Error occurred while retrieving application application '" + + identifier + "' and version '" + version + "'.", e); + } finally { + DeviceManagementDAOUtil.cleanupResources(stmt, rs); + } + } + private Connection getConnection() throws SQLException { return DeviceManagementDAOFactory.getConnection(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java index 0021c0dc96..45a4b881c4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java @@ -102,7 +102,7 @@ public class ApplicationMappingDAOImpl implements ApplicationMappingDAO { Connection conn; PreparedStatement stmt = null; try { - String sql = "DELETE DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID = ? AND " + + String sql = "DELETE FROM DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID = ? AND " + "APPLICATION_ID = ? AND TENANT_ID = ?"; conn = this.getConnection(); @@ -114,7 +114,7 @@ public class ApplicationMappingDAOImpl implements ApplicationMappingDAO { stmt.execute(); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e); + throw new DeviceManagementDAOException("Error occurred while removing device application mapping", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 1998907b9d..2972697b95 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -73,18 +73,16 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { int status = -1; try { conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " + - "DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?" + - " AND ID = ?"; + String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE DEVICE_ID = ?" + + " AND OWNER = ? AND TENANT_ID = ? AND ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, enrolmentInfo.getOwnership().toString()); stmt.setString(2, enrolmentInfo.getStatus().toString()); - stmt.setTimestamp(3, new Timestamp(enrolmentInfo.getDateOfEnrolment())); - stmt.setTimestamp(4, new Timestamp(new Date().getTime())); - stmt.setInt(5, deviceId); - stmt.setString(6, enrolmentInfo.getOwner()); - stmt.setInt(7, tenantId); - stmt.setInt(8, enrolmentInfo.getId()); + stmt.setTimestamp(3, new Timestamp(new Date().getTime())); + stmt.setInt(4, deviceId); + stmt.setString(5, enrolmentInfo.getOwner()); + stmt.setInt(6, tenantId); + stmt.setInt(7, enrolmentInfo.getId()); stmt.executeUpdate(); return status; } catch (SQLException e) { @@ -102,14 +100,12 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { int status = -1; try { conn = this.getConnection(); - String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, " + - "DATE_OF_ENROLMENT = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?"; + String sql = "UPDATE DM_ENROLMENT SET OWNERSHIP = ?, STATUS = ?, DATE_OF_LAST_UPDATE = ? WHERE ID = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, enrolmentInfo.getOwnership().toString()); stmt.setString(2, enrolmentInfo.getStatus().toString()); - stmt.setTimestamp(3, new Timestamp(enrolmentInfo.getDateOfEnrolment())); - stmt.setTimestamp(4, new Timestamp(new Date().getTime())); - stmt.setInt(5, enrolmentInfo.getId()); + stmt.setTimestamp(3, new Timestamp(new Date().getTime())); + stmt.setInt(4, enrolmentInfo.getId()); stmt.executeUpdate(); return status; } catch (SQLException e) { @@ -129,7 +125,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { int status = -1; try { conn = this.getConnection(); - String sql = "DELETE DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql, new String[] {"id"}); stmt.setInt(1, deviceId); stmt.setString(2, currentOwner); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index 7d2f874dd5..ced650ebe1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -93,7 +93,7 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { isStatusProvided = true; } - sql = sql + " ) rs ) WHERE offset >= ? AND ROWNUM <= ?"; + sql = sql + " ) rs ) WHERE OFFSET >= ? AND ROWNUM <= ?"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java index 8ca3ca45cc..7f5f5f5e97 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.internal; +import org.wso2.carbon.apimgt.impl.APIManagerConfiguration; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager; @@ -56,6 +57,16 @@ public class DeviceManagementDataHolder { private EmailSenderService emailSenderService; private PushNotificationProviderRepository pushNotificationProviderRepository; + public APIManagerConfiguration getApiManagerConfiguration() { + return apiManagerConfiguration; + } + + public void setApiManagerConfiguration(APIManagerConfiguration apiManagerConfiguration) { + this.apiManagerConfiguration = apiManagerConfiguration; + } + + private APIManagerConfiguration apiManagerConfiguration; + private DeviceManagementDataHolder() {} public static DeviceManagementDataHolder getInstance() { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java index 0ff2b680fe..03a96ea520 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java @@ -21,6 +21,7 @@ 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.impl.APIManagerConfiguration; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; @@ -30,6 +31,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository; @@ -50,6 +52,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository; +import org.wso2.carbon.device.mgt.core.scope.mgt.ScopeManagementServiceImpl; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory; 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; @@ -59,8 +63,10 @@ import org.wso2.carbon.email.sender.core.service.EmailSenderService; import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.ConfigurationContextService; +import java.io.File; import java.util.ArrayList; import java.util.List; @@ -117,6 +123,9 @@ public class DeviceManagementServiceComponent { private static List deviceManagers = new ArrayList<>(); private static List startupListeners = new ArrayList<>(); private DeviceManagementPluginRepository pluginRepository = new DeviceManagementPluginRepository(); + private static final String APIM_CONFIGURATION_PATH = CarbonUtils.getCarbonHome() + File.separator + "repository" + + File.separator + "conf" + File.separator + "api-manager.xml"; + private static final String DATA_SOURCE_NAME = "DataSourceName"; public static void registerPluginInitializationListener(PluginInitializationListener listener) { synchronized (LOCK) { @@ -149,12 +158,19 @@ public class DeviceManagementServiceComponent { DeviceConfigurationManager.getInstance().getDeviceManagementConfig(); DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig(); + + APIManagerConfiguration apiManagerConfiguration = new APIManagerConfiguration(); + apiManagerConfiguration.load(APIM_CONFIGURATION_PATH); + DeviceManagementDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfiguration); + DeviceManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig); - OperationManagementDAOFactory.init(dsConfig); + String apiManagerDataSource = apiManagerConfiguration.getFirstProperty(DATA_SOURCE_NAME); + ScopeManagementDAOFactory.init(apiManagerDataSource); + /* Initialize Operation Manager */ this.initOperationsManager(); @@ -169,7 +185,7 @@ public class DeviceManagementServiceComponent { /* If -Dsetup option enabled then create device management database schema */ String setupOption = - System.getProperty(DeviceManagementConstants.Common.PROPERTY_SETUP); + System.getProperty(DeviceManagementConstants.Common.SETUP_PROPERTY); if (setupOption != null) { if (log.isDebugEnabled()) { log.debug("-Dsetup is enabled. Device management repository schema initialization is about to " + @@ -227,10 +243,9 @@ public class DeviceManagementServiceComponent { = new NotificationManagementServiceImpl(); bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null); - /* Registering PermissionManager Service */ - PermissionManagerService permissionManagerService - = PermissionManagerServiceImpl.getInstance(); - bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null); + /* Registering Scope Management Service */ + ScopeManagementService scopeManagementService = new ScopeManagementServiceImpl(); + bundleContext.registerService(ScopeManagementService.class.getName(), scopeManagementService, null); /* Registering DeviceAccessAuthorization Service */ DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 59692da94d..88883a4e26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -35,6 +35,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import java.sql.SQLException; import java.util.ArrayList; @@ -177,6 +178,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement public PaginationResult getAllNotifications(PaginationRequest request) throws NotificationManagementException { PaginationResult paginationResult = new PaginationResult(); List notifications = new ArrayList<>(); + request = DeviceManagerUtil.validateNotificationListPageSize(request); int count =0; try { NotificationManagementDAOFactory.openConnection(); @@ -199,6 +201,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement PaginationRequest request) throws NotificationManagementException{ PaginationResult paginationResult = new PaginationResult(); List notifications = new ArrayList<>(); + request = DeviceManagerUtil.validateNotificationListPageSize(request); int count =0; try { NotificationManagementDAOFactory.openConnection(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java index 20e8543cb4..d280dd643e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java @@ -20,11 +20,13 @@ package org.wso2.carbon.device.mgt.core.notification.mgt.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; -import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.NotificationDAOImpl; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.*; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; import javax.sql.DataSource; @@ -39,21 +41,48 @@ import java.util.List; public class NotificationManagementDAOFactory { private static DataSource dataSource; + private static String databaseEngine; private static final Log log = LogFactory.getLog(NotificationManagementDAOFactory.class); private static ThreadLocal currentConnection = new ThreadLocal(); public static NotificationDAO getNotificationDAO() { - return new NotificationDAOImpl(); + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericNotificationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); } public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } public static void init(DataSource dtSource) { dataSource = dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } + public static void beginTransaction() throws TransactionManagementException { Connection conn = currentConnection.get(); if (conn != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java similarity index 74% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java index 608c5a4f2e..96c47cf0d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java @@ -35,7 +35,7 @@ import java.util.List; /** * Implementation of NotificationDAO which includes the methods to do CRUD operations on notification. */ -public class NotificationDAOImpl implements NotificationDAO { +public abstract class AbstractNotificationDAOImpl implements NotificationDAO { @Override public int addNotification(int deviceId, int tenantId, @@ -87,7 +87,7 @@ public class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); while (rs.next()) { - notification = this.getNotification(rs); + notification = NotificationDAOUtil.getNotification(rs); } } catch (SQLException e) { throw new NotificationManagementException( @@ -165,7 +165,7 @@ public class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); notifications = new ArrayList<>(); while (rs.next()) { - notifications.add(this.getNotification(rs)); + notifications.add(NotificationDAOUtil.getNotification(rs)); } } catch (SQLException e) { throw new NotificationManagementException( @@ -176,45 +176,6 @@ public class NotificationDAOImpl implements NotificationDAO { return notifications; } - @Override - public List getAllNotifications(PaginationRequest request, int tenantId) throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = - "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + - " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + - "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; - - sql = sql + " LIMIT ?,?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - int paramIdx = 3; - - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all notifications", e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - } - - @Override public int getNotificationCount(int tenantId) throws NotificationManagementException { int notificationCount = 0; @@ -277,7 +238,7 @@ public class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); notifications = new ArrayList<>(); while (rs.next()) { - notifications.add(this.getNotification(rs)); + notifications.add(NotificationDAOUtil.getNotification(rs)); } } catch (SQLException e) { throw new NotificationManagementException( @@ -322,59 +283,4 @@ public class NotificationDAOImpl implements NotificationDAO { } return notificationCountByStatus; } - - @Override - public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws - NotificationManagementException{ - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + - " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + - "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + - "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + - "AND TENANT_ID = ?"; - - sql = sql + " LIMIT ?,?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); - stmt.setInt(3, tenantId); - - int paramIdx = 4; - - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - - - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all " + - "notifications by status : " + status, e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - - } - - private Notification getNotification(ResultSet rs) throws SQLException { - Notification notification = new Notification(); - notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); - notification.setOperationId(rs.getInt("OPERATION_ID")); - notification.setDescription(rs.getString("DESCRIPTION")); - notification.setStatus(rs.getString("STATUS")); - return notification; - } - } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java new file mode 100644 index 0000000000..0653ec3029 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * 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.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the generic implementation of NotificationDAO which can be used to support ANSI db syntax. + */ +public class GenericNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " LIMIT ?,?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " LIMIT ?,?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java new file mode 100644 index 0000000000..829e586d79 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * 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.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the Oracle implementation of NotificationDAO which can be used to support Oracle db syntax. + */ +public class OracleNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " WHERE OFFSET >= ? AND ROWNUM <= ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " OFFSET >= ? AND ROWNUM <= ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java new file mode 100644 index 0000000000..2039c04cbc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * 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.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of NotificationDAO which can be used to support PostgreSQL db syntax. + */ +public class PostgreSQLNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java new file mode 100644 index 0000000000..e03a220ed1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * 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.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of NotificationDAO which can be used to support SQLServer db syntax. + */ +public class SQLServerNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java index 5c87e1b311..36f7df6be0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.core.notification.mgt.dao.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.user.api.UserStoreException; @@ -123,4 +124,13 @@ public class NotificationDAOUtil { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } } + + public static Notification getNotification(ResultSet rs) throws SQLException { + Notification notification = new Notification(); + notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); + notification.setOperationId(rs.getInt("OPERATION_ID")); + notification.setDescription(rs.getString("DESCRIPTION")); + notification.setStatus(rs.getString("STATUS")); + return notification; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 4c60e4a6b8..1e9c3d68fd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -340,45 +340,52 @@ public class GenericOperationDAOImpl implements OperationDAO { } @Override - public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException { + public List getActivitiesUpdatedAfter(long timestamp, int limit, + int offset) throws OperationManagementDAOException { PreparedStatement stmt = null; ResultSet rs = null; List activities = new ArrayList<>(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" + - "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + - "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + - "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + - "dor.RECEIVED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING AS eom \n" + - "INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID\n" + - "INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID\n" + - "INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID \n" + - "INNER JOIN DM_DEVICE_TYPE AS dt ON dt.ID=d.DEVICE_TYPE_ID\n" + - "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE AS dor ON dor.ENROLMENT_ID=de.id \n" + - "AND dor.OPERATION_ID=eom.OPERATION_ID\n" + - "WHERE eom.UPDATED_TIMESTAMP > ? AND de.TENANT_ID = ? ORDER BY eom.OPERATION_ID"; +// String sql = "SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.ID AS EOM_MAPPING_ID, dor.ID AS OP_RES_ID,\n" + +// "de.DEVICE_ID, d.DEVICE_IDENTIFICATION, \n" + +// "d.DEVICE_TYPE_ID, dt.NAME AS DEVICE_TYPE_NAME, eom.STATUS, eom.CREATED_TIMESTAMP, \n" + +// "eom.UPDATED_TIMESTAMP, op.OPERATION_CODE, op.TYPE AS OPERATION_TYPE, dor.OPERATION_RESPONSE, \n" + +// "dor.RECEIVED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING AS eom \n" + +// "INNER JOIN DM_OPERATION AS op ON op.ID=eom.OPERATION_ID\n" + +// "INNER JOIN DM_ENROLMENT AS de ON de.ID=eom.ENROLMENT_ID\n" + +// "INNER JOIN DM_DEVICE AS d ON d.ID=de.DEVICE_ID \n" + +// "INNER JOIN DM_DEVICE_TYPE AS dt ON dt.ID=d.DEVICE_TYPE_ID\n" + +// "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE AS dor ON dor.ENROLMENT_ID=de.id \n" + +// "AND dor.OPERATION_ID=eom.OPERATION_ID\n" + +// "WHERE eom.UPDATED_TIMESTAMP > ? AND de.TENANT_ID = ? ORDER BY eom.OPERATION_ID"; - if(limit > 0) { - sql = sql + " LIMIT ?"; - } +// if(limit > 0) { +// sql = sql + " LIMIT ?"; +// } +// +// if(offset > 0) { +// sql = sql + " OFFSET ?"; +// } - if(offset > 0) { - sql = sql + " OFFSET ?"; - } + String sql = "SELECT dte.ENROLMENT_ID, oor.OPERATION_ID, oor.OP_RES_ID, oor.OPERATION_TYPE, " + + "oor.OPERATION_CODE, oor.OPERATION_RESPONSE, dte.DEVICE_TYPE, dte.DEVICE_IDENTIFICATION, " + + "oor.RECEIVED_TIMESTAMP, eom.UPDATED_TIMESTAMP, eom.STATUS FROM (SELECT d.DEVICE_IDENTIFICATION, " + + "t.NAME AS DEVICE_TYPE, e.ID AS ENROLMENT_ID FROM DM_DEVICE d INNER JOIN DM_DEVICE_TYPE t " + + "ON d.DEVICE_TYPE_ID = t.ID INNER JOIN DM_ENROLMENT e ON d.ID = e.DEVICE_ID WHERE " + + "e.TENANT_ID = ?) dte INNER JOIN (SELECT o.ID AS OPERATION_ID, o.TYPE AS OPERATION_TYPE, " + + "o.OPERATION_CODE, r.ID AS OP_RES_ID, r.OPERATION_RESPONSE, r.RECEIVED_TIMESTAMP, " + + "r.ENROLMENT_ID FROM DM_OPERATION o INNER JOIN DM_DEVICE_OPERATION_RESPONSE r ON " + + "o.ID = r.OPERATION_ID) oor ON oor.ENROLMENT_ID=dte.ENROLMENT_ID LEFT OUTER JOIN " + + "(SELECT ENROLMENT_ID, OPERATION_ID, STATUS, UPDATED_TIMESTAMP FROM DM_ENROLMENT_OP_MAPPING " + + "WHERE UPDATED_TIMESTAMP > ? LIMIT ? OFFSET ?) eom ON eom.ENROLMENT_ID=oor.ENROLMENT_ID AND " + + "oor.OPERATION_ID=eom.OPERATION_ID ORDER BY oor.OPERATION_ID"; stmt = conn.prepareStatement(sql); - stmt.setLong(1, timestamp); - stmt.setInt(2, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); - - int increment = 2; - - if(limit > 0) { - stmt.setInt(++increment, limit); - } - if(offset > 0) { - stmt.setInt(++increment, offset); - } + stmt.setInt(1, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + stmt.setLong(2, timestamp); + stmt.setInt(3, limit); + stmt.setInt(4, offset); rs = stmt.executeQuery(); int operationId = 0; @@ -434,7 +441,7 @@ public class GenericOperationDAOImpl implements OperationDAO { DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - deviceIdentifier.setType(rs.getString("DEVICE_TYPE_NAME")); + deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); activityStatus.setDeviceIdentifier(deviceIdentifier); activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index 0d107ead1d..c9ddcb3d91 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -46,8 +46,8 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); @@ -72,7 +72,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + - "available for the device'" + enrolmentId + "' with status '", e); + "available for the device'" + enrolmentId, e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -89,7 +89,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE " + "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java index 190b90dbc7..0cdae21617 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java @@ -22,8 +22,9 @@ import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService; -import java.util.List; +import java.util.HashSet; import java.util.Properties; +import java.util.Set; /** * This class will add, update custom permissions defined in permission.xml in webapps and it will @@ -52,16 +53,19 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { } @Override - public boolean addPermission(Permission permission) throws PermissionManagementException { + public void addPermission(Permission permission) throws PermissionManagementException { // adding a permission to the tree permissionTree.addPermission(permission); - return PermissionUtils.putPermission(permission); } @Override public Permission getPermission(Properties properties) throws PermissionManagementException { String url = (String) properties.get(URL_PROPERTY); String httpMethod = (String) properties.get(HTTP_METHOD_PROPERTY); + + if (url == null || url.isEmpty() || httpMethod == null || httpMethod.isEmpty()) { + throw new PermissionManagementException("Resource URI/HTTP method is empty"); + } return permissionTree.getPermission(url, httpMethod); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java index 8294cce8a0..62af312e66 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java @@ -54,9 +54,6 @@ public class PermissionTree { tempRoot = addPermissionNode(tempRoot, tempChild); } tempRoot.addPermission(permission.getMethod(), permission); //setting permission to the vertex - if (log.isDebugEnabled()) { - log.debug("Added permission '" + permission.getName() + "'"); - } } /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java index 27b95e56cc..9f73a36e1c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java @@ -39,84 +39,82 @@ import java.util.StringTokenizer; */ public class PermissionUtils { - public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; - public static final String PERMISSION_PROPERTY_NAME = "name"; + public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin"; + public static final String PERMISSION_PROPERTY_NAME = "name"; - public static Registry getGovernanceRegistry() throws PermissionManagementException { - try { - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - return DeviceManagementDataHolder.getInstance().getRegistryService() - .getGovernanceSystemRegistry( - tenantId); - } catch (RegistryException e) { - throw new PermissionManagementException( - "Error in retrieving governance registry instance: " + - e.getMessage(), e); - } - } + public static Registry getGovernanceRegistry() throws PermissionManagementException { + try { + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + return DeviceManagementDataHolder.getInstance().getRegistryService() + .getGovernanceSystemRegistry( + tenantId); + } catch (RegistryException e) { + throw new PermissionManagementException( + "Error in retrieving governance registry instance: " + + e.getMessage(), e); + } + } - public static String getAbsolutePermissionPath(String permissionPath) { - return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath; - } + public static String getAbsolutePermissionPath(String permissionPath) { + return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath; + } public static String getAbsoluteContextPathOfAPI(String contextPath, String version, String url) { - if((version != null) && !version.isEmpty()) { - return contextPath + "/" + version + url; + if ((version != null) && !version.isEmpty()) { + return contextPath + "/" + version + url; } return contextPath + url; } - public static Permission getPermission(String path) throws PermissionManagementException { - try { - Resource resource = PermissionUtils.getGovernanceRegistry().get(path); - Permission permission = new Permission(); - permission.setName(resource.getProperty(PERMISSION_PROPERTY_NAME)); - permission.setPath(resource.getPath()); - return permission; - } catch (RegistryException e) { - throw new PermissionManagementException("Error in retrieving registry resource : " + - e.getMessage(), e); - } - } - - public static boolean putPermission(Permission permission) - throws PermissionManagementException { - boolean status; - try { - StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/"); - String lastToken = "", currentToken, tempPath; - while(tokenizer.hasMoreTokens()) { - currentToken = tokenizer.nextToken(); - tempPath = lastToken + "/" + currentToken; - if(!checkResourceExists(tempPath)) { + // public static Permission getPermission(String path) throws PermissionManagementException { +// try { +// Resource resource = PermissionUtils.getGovernanceRegistry().get(path); +// Permission permission = new Permission(); +// permission.setName(resource.getProperty(PERMISSION_PROPERTY_NAME)); +// permission.setPath(resource.getPath()); +// return permission; +// } catch (RegistryException e) { +// throw new PermissionManagementException("Error in retrieving registry resource : " + +// e.getMessage(), e); +// } +// } +// + public static boolean putPermission(String permissionPath) + throws PermissionManagementException { + boolean status; + try { + StringTokenizer tokenizer = new StringTokenizer(permissionPath, "/"); + String lastToken = "", currentToken, tempPath; + while (tokenizer.hasMoreTokens()) { + currentToken = tokenizer.nextToken(); + tempPath = lastToken + "/" + currentToken; + if (!checkResourceExists(tempPath)) { createRegistryCollection(tempPath, currentToken); - } - lastToken = tempPath; - } - status = true; - } catch (RegistryException e) { - throw new PermissionManagementException( - "Error occurred while persisting permission : " + - permission.getName(), e); - } - return status; - } + } + lastToken = tempPath; + } + status = true; + } catch (RegistryException e) { + throw new PermissionManagementException("Error occurred while persisting permission", e); + } + return status; + } - public static void createRegistryCollection(String path, String resourceName) - throws PermissionManagementException, - RegistryException { - Resource resource = PermissionUtils.getGovernanceRegistry().newCollection(); - resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName); - PermissionUtils.getGovernanceRegistry().beginTransaction(); - PermissionUtils.getGovernanceRegistry().put(path, resource); - PermissionUtils.getGovernanceRegistry().commitTransaction(); - } + public static void createRegistryCollection(String path, String resourceName) + throws PermissionManagementException, + RegistryException { + Resource resource = PermissionUtils.getGovernanceRegistry().newCollection(); + resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName); + PermissionUtils.getGovernanceRegistry().beginTransaction(); + PermissionUtils.getGovernanceRegistry().put(path, resource); + PermissionUtils.getGovernanceRegistry().commitTransaction(); + } - public static boolean checkResourceExists(String path) - throws PermissionManagementException, - org.wso2.carbon.registry.core.exceptions.RegistryException { - return PermissionUtils.getGovernanceRegistry().resourceExists(path); - } + public static boolean checkResourceExists(String path) + throws PermissionManagementException, + org.wso2.carbon.registry.core.exceptions.RegistryException { + return PermissionUtils.getGovernanceRegistry().resourceExists(path); + } public static Document convertToDocument(File file) throws PermissionManagementException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java deleted file mode 100644 index fb62730082..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public class EvaluationContext { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java deleted file mode 100644 index 569f311aa6..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public class PolicyEvaluationException extends Exception { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java deleted file mode 100644 index bd4557eeb0..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public interface PolicyEvaluationStrategy { - - Profile execute(EvaluationContext ctx) throws PolicyEvaluationException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java deleted file mode 100644 index a36bd28fda..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public class PolicyManagementException extends Exception { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java deleted file mode 100644 index a69068a003..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy; - -import java.util.List; - -public interface PolicyManager { - - public enum Type { - USER_BASED, ROLE_BASED, PLATFORM_BASED - } - - boolean addPolicy(Policy policy) throws PolicyManagementException; - - boolean removePolicy(String policyId) throws PolicyManagementException; - - boolean updatePolicy(Policy policy) throws PolicyManagementException; - - Policy getPolicy(String policyId) throws PolicyManagementException; - - List getPolicies() throws PolicyManagementException; - - List getUserBasedPolicies(String user) throws PolicyManagementException; - - List getRoleBasedPolicies(String role) throws PolicyManagementException; - - List getPlatformBasedPolicies(String platform) throws PolicyManagementException; - - boolean assignRoleBasedPolicy(String policyId, String role) throws PolicyManagementException; - - boolean assignRoleBasedPolicy(String policyId, List roles) throws PolicyManagementException; - - boolean assignUserBasedPolicy(String policyId, String user) throws PolicyManagementException; - - boolean assignUserBasedPolicy(String policyId, List users) throws PolicyManagementException; - - boolean assignPlatformBasedPolicy(String policyId, String platform) throws PolicyManagementException; - - Profile getEffectiveProfile(DeviceIdentifier deviceId) throws PolicyManagementException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java deleted file mode 100644 index 1e16c2a58f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy; - -public interface PolicyRepository { - - public enum Type { - USER_BASED, ROLE_BASED, PLATFORM_BASED - } - - void addPolicy(Policy policy) throws PolicyManagementException; - - void remotePolicy(Policy policy) throws PolicyManagementException; - - void getPolicy(String id) throws PolicyManagementException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java deleted file mode 100644 index 70f1b4269f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public class Profile { -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java deleted file mode 100644 index ad40cff1af..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public class Rule { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java deleted file mode 100644 index 862089c135..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt; - -public interface RuleCombiningStrategy { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java deleted file mode 100644 index db6354b008..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.dao; - -public interface PolicyDAO { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java deleted file mode 100644 index 5e5c570e62..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.dao; - -public class PolicyDAOFactory { - - public static PolicyDAO getPolicyDAO() { - return new PolicyDAOImpl(); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java deleted file mode 100644 index de2de21bd7..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.dao; - -public class PolicyDAOImpl implements PolicyDAO { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java deleted file mode 100644 index 4914a33f26..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.policy; - -public class PlatformBasedPolicy extends Policy { - - private String platform; - - public String getPlatform() { - return platform; - } - - public void setPlatform(String platform) { - this.platform = platform; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java deleted file mode 100644 index a528c09eed..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.policy; - -public class Policy { - - private String id; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java deleted file mode 100644 index c08544f125..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.policy; - -public class RoleBasedPolicy extends Policy { - - private String role; - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java deleted file mode 100644 index 0eb9417826..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, 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.policy.mgt.policy; - -public class UsedBasedPolicy extends Policy { - - private String username; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java new file mode 100644 index 0000000000..59418e760f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java @@ -0,0 +1,97 @@ +/* +* 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.scope.mgt; + +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException; +import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAO; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOException; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory; + +import java.lang.annotation.Inherited; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This is an implementation of a Scope Management Service. + */ +public class ScopeManagementServiceImpl implements ScopeManagementService { + + private ScopeManagementDAO scopeManagementDAO; + + public ScopeManagementServiceImpl() { + this.scopeManagementDAO = ScopeManagementDAOFactory.getScopeManagementDAO(); + } + + @Override + public void updateScopes(List scopes) throws ScopeManagementException { + try{ + ScopeManagementDAOFactory.beginTransaction(); + scopeManagementDAO.updateScopes(scopes); + ScopeManagementDAOFactory.commitTransaction(); + } catch (TransactionManagementException e) { + ScopeManagementDAOFactory.rollbackTransaction(); + throw new ScopeManagementException("Transactional error occurred while adding the scopes.", e); + } catch (ScopeManagementDAOException e) { + ScopeManagementDAOFactory.rollbackTransaction(); + throw new ScopeManagementException("Error occurred while adding the scopes to database.", e); + } finally { + ScopeManagementDAOFactory.closeConnection(); + } + } + + @Override + public List getAllScopes() throws ScopeManagementException { + List scopes = new ArrayList<>(); + try{ + ScopeManagementDAOFactory.openConnection(); + scopes = scopeManagementDAO.getAllScopes(); + } catch (SQLException e) { + throw new ScopeManagementException("SQL error occurred while retrieving scopes from database.", e); + } catch (ScopeManagementDAOException e) { + throw new ScopeManagementException("Error occurred while retrieving scopes from database.", e); + } finally { + ScopeManagementDAOFactory.closeConnection(); + } + return scopes; + } + + @Override + public String getRolesOfScope(String scopeKey) throws ScopeManagementException { + String roles; + if (scopeKey == null || scopeKey.isEmpty()) { + throw new ScopeManagementException("Scope key is null or empty"); + } + try { + ScopeManagementDAOFactory.openConnection(); + roles = scopeManagementDAO.getRolesOfScope(scopeKey); + } catch (SQLException e) { + throw new ScopeManagementException("SQL error occurred while retrieving roles of scope from database.", e); + } catch (ScopeManagementDAOException e) { + throw new ScopeManagementException("Error occurred while retrieving roles of scope from database.", e); + } finally { + ScopeManagementDAOFactory.closeConnection(); + } + return roles; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java new file mode 100644 index 0000000000..38517f6c4e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java @@ -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. +*/ + +package org.wso2.carbon.device.mgt.core.scope.mgt.dao; + +import org.wso2.carbon.apimgt.api.model.Scope; + +import java.util.List; + +/** + * This interface contains the basic database operations related to scope management. + */ +public interface ScopeManagementDAO { + + /** + * This method is used to update the list of scopes. + * + * @param scopes List of scopes to be updated. + * @throws ScopeManagementDAOException + */ + void updateScopes(List scopes) throws ScopeManagementDAOException; + + /** + * This method is used to retrieve all the scopes. + * + * @return List of scopes. + * @throws ScopeManagementDAOException + */ + List getAllScopes() throws ScopeManagementDAOException; + + /** + * This method is to retrieve the roles of the given scope + * @param scopeKey key of the scope + * @return List of roles + * @throws ScopeManagementDAOException + */ + String getRolesOfScope(String scopeKey) throws ScopeManagementDAOException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java new file mode 100644 index 0000000000..61ea7de2e2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java @@ -0,0 +1,57 @@ +/* +* 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.scope.mgt.dao; + +public class ScopeManagementDAOException extends Exception { + + private static final long serialVersionUID = -315127931137771199L; + + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public ScopeManagementDAOException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public ScopeManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public ScopeManagementDAOException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public ScopeManagementDAOException() { + super(); + } + + public ScopeManagementDAOException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java new file mode 100644 index 0000000000..cb53d76f29 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java @@ -0,0 +1,139 @@ +/* + * 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.scope.mgt.dao; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; +import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.impl.ScopeManagementDAOImpl; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class ScopeManagementDAOFactory { + + private static final Log log = LogFactory.getLog(ScopeManagementDAOFactory.class); + private static DataSource dataSource; + private static String databaseEngine; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public static ScopeManagementDAO getScopeManagementDAO() { + return new ScopeManagementDAOImpl(); + } + + public static void init(String dataSourceName) { + dataSource = resolveDataSource(dataSourceName); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } + } + + public static void beginTransaction() throws TransactionManagementException { + try { + Connection conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new TransactionManagementException( + "Error occurred while retrieving config.datasource connection", e); + } + } + + public static void openConnection() throws SQLException { + currentConnection.set(dataSource.getConnection()); + } + + public static Connection getConnection() throws SQLException { + if (currentConnection.get() == null) { + throw new IllegalTransactionStateException("No connection is associated with the current transaction. " + + "This might have ideally caused by not properly initiating the transaction via " + + "'beginTransaction'/'openConnection' methods"); + } + return currentConnection.get(); + } + + public static void closeConnection() { + Connection con = currentConnection.get(); + if (con != null) { + try { + con.close(); + } catch (SQLException e) { + log.error("Error occurred while close the connection"); + } + currentConnection.remove(); + } + } + + public static void commitTransaction() { + try { + Connection conn = currentConnection.get(); + if (conn != null) { + conn.commit(); + } else { + if (log.isDebugEnabled()) { + log.debug("Datasource connection associated with the current thread is null, hence commit " + + "has not been attempted"); + } + } + } catch (SQLException e) { + log.error("Error occurred while committing the transaction", e); + } + } + + public static void rollbackTransaction() { + try { + Connection conn = currentConnection.get(); + if (conn != null) { + conn.rollback(); + } else { + if (log.isDebugEnabled()) { + log.debug("Datasource connection associated with the current thread is null, hence rollback " + + "has not been attempted"); + } + } + } catch (SQLException e) { + log.error("Error occurred while roll-backing the transaction", e); + } + } + + /** + * Resolve data source from the data source name. + * + * @param dataSourceName data source name + * @return data source resolved from the data source definition + */ + private static DataSource resolveDataSource(String dataSourceName) { + DataSource dataSource; + if (dataSourceName == null || dataSourceName.isEmpty()) { + throw new RuntimeException("Scope Management Repository data source configuration is null and " + + "thus, is not initialized"); + } + if (log.isDebugEnabled()) { + log.debug("Initializing Scope Management Repository data source using the JNDI Lookup Definition"); + } + dataSource = DeviceManagementDAOUtil.lookupDataSource(dataSourceName, null); + return dataSource; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java new file mode 100644 index 0000000000..570b4ce07d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java @@ -0,0 +1,57 @@ +/* + * 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.scope.mgt.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +public class ScopeManagementDAOUtil { + + private static final Log log = LogFactory.getLog(ScopeManagementDAOUtil.class); + + public static void cleanupResources(Statement stmt, ResultSet rs) { + if (rs != null) { + try { + rs.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing the result set", e); + } + } + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing the statement", e); + } + } + } + public static void cleanupResources(Statement stmt) { + if (stmt != null) { + try { + stmt.close(); + } catch (SQLException e) { + log.warn("Error occurred while closing the statement", e); + } + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java new file mode 100644 index 0000000000..7e46392446 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java @@ -0,0 +1,121 @@ +/* +* 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.scope.mgt.dao.impl; + +import org.wso2.carbon.apimgt.api.model.Scope; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAO; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOException; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +public class ScopeManagementDAOImpl implements ScopeManagementDAO { + + @Override + public void updateScopes(List scopes) throws ScopeManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + + try { + conn = this.getConnection(); + String sql = "UPDATE IDN_OAUTH2_SCOPE SET ROLES=? WHERE SCOPE_KEY=?"; + stmt = conn.prepareStatement(sql); + + // creating a batch request + for (Scope scope : scopes) { + stmt.setString(1, scope.getRoles()); + stmt.setString(2, scope.getKey()); + stmt.addBatch(); + } + stmt.executeBatch(); + } catch (SQLException e) { + throw new ScopeManagementDAOException("Error occurred while updating the details of the scopes.", e); + } finally { + ScopeManagementDAOUtil.cleanupResources(stmt, rs); + } + + } + + + public List getAllScopes() throws ScopeManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List scopes = new ArrayList<>(); + Scope scope; + + try { + conn = this.getConnection(); + String sql = "SELECT * FROM IDN_OAUTH2_SCOPE"; + stmt = conn.prepareStatement(sql); + rs = stmt.executeQuery(); + + while (rs.next()) { + scope = new Scope(); + scope.setKey(rs.getString("SCOPE_KEY")); + scope.setName(rs.getString("NAME")); + scope.setDescription(rs.getString("DESCRIPTION")); + scope.setRoles(rs.getString("ROLES")); + scopes.add(scope); + } + return scopes; + } catch (SQLException e) { + throw new ScopeManagementDAOException("Error occurred while fetching the details of the scopes.", e); + } finally { + ScopeManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + @Override + public String getRolesOfScope(String scopeKey) throws ScopeManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + String roles = null; + + try { + conn = this.getConnection(); + String sql = "SELECT ROLES FROM IDN_OAUTH2_SCOPE WHERE SCOPE_KEY = ?"; + stmt = conn.prepareStatement(sql); + stmt.setString(1, scopeKey); + rs = stmt.executeQuery(); + + if (rs.next()) { + roles = rs.getString("ROLES"); + } + return roles; + } catch (SQLException e) { + throw new ScopeManagementDAOException("Error occurred while fetching the details of the scopes.", e); + } finally { + ScopeManagementDAOUtil.cleanupResources(stmt, rs); + } + } + + private Connection getConnection() throws SQLException { + return ScopeManagementDAOFactory.getConnection(); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index b86e3c1bcc..3a841f2aa0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -47,8 +47,7 @@ public class QueryBuilderImpl implements QueryBuilder { Condition locCondition = new Condition(); if (conditions.size() == 1) { - - if (conditions.get(0).getKey().equalsIgnoreCase(Constants.LOCATION)) { + if (Constants.LOCATION.equalsIgnoreCase(conditions.get(0).getKey())) { locCondition = conditions.get(0); } else if (Utils.checkDeviceDetailsColumns(conditions.get(0).getKey()) || Utils.checkDeviceLocationColumns(conditions.get(0).getKey())) { @@ -58,7 +57,7 @@ public class QueryBuilderImpl implements QueryBuilder { } } else { for (Condition con : conditions) { - if (con.getKey().equalsIgnoreCase(Constants.LOCATION)) { + if (Constants.LOCATION.equalsIgnoreCase(con.getKey())) { locCondition = con; } else if (Utils.checkDeviceDetailsColumns(con.getKey()) || Utils.checkDeviceLocationColumns(con.getKey())) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 314a26c392..73533f36fd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -508,6 +508,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int count = 0; int tenantId = this.getTenantId(); String deviceType = request.getDeviceType(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevices(request, tenantId); @@ -569,6 +570,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allDevices = new ArrayList<>(); int count = 0; int tenantId = this.getTenantId(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevices(request, tenantId); @@ -1031,6 +1033,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { + request = DeviceManagerUtil.validateOperationListPageSize(request); return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) .getOperations(deviceId, request); } @@ -1091,6 +1094,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException { + limit = DeviceManagerUtil.validateActivityListPageSize(limit); return DeviceManagementDataHolder.getInstance().getOperationManager().getActivitiesUpdatedAfter(timestamp, limit, offset); } @@ -1176,6 +1180,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String username = request.getOwner(); List devices = new ArrayList<>(); List userDevices = new ArrayList<>(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(request, tenantId); @@ -1253,6 +1258,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int deviceCount = 0; int tenantId = this.getTenantId(); String ownerShip = request.getOwnership(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByOwnership(request, tenantId); @@ -1412,6 +1418,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException { List devices = new ArrayList<>(); List allDevices; + limit = DeviceManagerUtil.validateDeviceListPageSize(limit); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit); @@ -1474,6 +1481,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); String deviceName = request.getDeviceName(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByName(request, tenantId); @@ -1636,6 +1644,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allDevices = new ArrayList<>(); int tenantId = this.getTenantId(); String status = request.getStatus(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByStatus(request, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index a9d472d498..f8a31b2457 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -21,10 +21,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; -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.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; @@ -227,7 +228,7 @@ public final class DeviceManagerUtil { */ public static int getTenantId(String tenantDomain) throws DeviceManagementException { try { - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { return MultitenantConstants.SUPER_TENANT_ID; } TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); @@ -241,4 +242,79 @@ public final class DeviceManagerUtil { } } + public static int validateActivityListPageSize(int limit) throws OperationManagementException { + if (limit == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + return deviceManagementConfig.getPaginationConfiguration().getActivityListPageSize(); + } else { + throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return limit; + } + + public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) throws + OperationManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getOperationListPageSize()); + } else { + throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) throws + NotificationManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getNotificationListPageSize()); + } else { + throw new NotificationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest) throws + DeviceManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getDeviceListPageSize()); + } else { + throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static int validateDeviceListPageSize(int limit) throws DeviceManagementException { + if (limit == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + return deviceManagementConfig.getPaginationConfiguration().getDeviceListPageSize(); + } else { + throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return limit; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java index 6d7e4b4bb6..7ba74caa10 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/java/org/wso2/carbon/device/mgt/core/dao/EnrolmentPersistenceTests.java @@ -41,7 +41,7 @@ public class EnrolmentPersistenceTests extends BaseDeviceManagementTest { /* Initializing source enrolment configuration bean to be tested */ EnrolmentInfo source = - new EnrolmentInfo(null, owner, EnrolmentInfo.OwnerShip.BYOD, + new EnrolmentInfo(owner, EnrolmentInfo.OwnerShip.BYOD, EnrolmentInfo.Status.CREATED); /* Adding dummy enrolment configuration to the device management metadata store */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag index e52746e9df..05ca19906a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag @@ -22,8 +22,8 @@ var log = new Log("api/data-tables-invoker-api.jag"); var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; function appendQueryParam (url, queryParam , value) { if (url.indexOf("?") > 0) { @@ -39,18 +39,26 @@ if (uriMatcher.match("/{context}/api/data-tables/invoker")) { for (var key in allParams) { if (allParams.hasOwnProperty(key)) { - if (key == "limit" || key == "offset" || key == "filter") { + if(key == "limit" || key == "offset"){ targetURL = appendQueryParam(targetURL, key, allParams[key]); } + if(key == "filter"){ + if(allParams[key]){ + var searchPayload = JSON.parse(allParams[key]); + for (var key in searchPayload) { + targetURL = appendQueryParam(targetURL, key, searchPayload[key]); + } + } + } } } serviceInvokers.XMLHttp.get( - targetURL, - // response callback - function (backendResponse) { - response["status"] = backendResponse["status"]; - response["content"] = backendResponse["responseText"]; - } + targetURL, + // response callback + function (backendResponse) { + response["status"] = backendResponse["status"]; + response["content"] = backendResponse["responseText"]; + } ); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 1a163d76e4..ecb9806b5d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -22,11 +22,11 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); -var deviceModule = require("/app/modules/device.js").deviceModule; +var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var userModule = require("/app/modules/user.js").userModule; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag index d5f9bb2628..2ba4ebba9e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -23,8 +23,8 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 6fa133523e..3e410ee2c5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -23,8 +23,8 @@ var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var constants = require("/app/modules/constants.js"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; if (uriMatcher.match("/{context}/api/invoker/execute/")) { var restAPIRequestDetails = request.getContent(); @@ -97,8 +97,8 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { break; } } catch (e) { - log.error("Exception occurred while trying to access backend " + - "REST API services from Jaggery API invoker layer", e); + throw new Error("Exception occurred while trying to access " + + "backend REST API services from Jaggery API invoker layer", e); } } %> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index 46b4595b66..c6dca89321 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -22,8 +22,8 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/operation-api.jag"); -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (uriMatcher.match("/{context}/api/operation/paginate")) { var deviceType = request.getParameter("deviceType"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag index d2a2630be7..5ae93fdde7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag @@ -27,7 +27,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/policy-api.jag"); var constants = require("/modules/constants.js"); -var policyModule = require("/modules/policy.js").policyModule; +var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"]; var result; if (uriMatcher.match("/{context}/api/policies/update")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index cab3d3a32f..212a087539 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -23,12 +23,12 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/user-api.jag"); var constants = require("/app/modules/constants.js"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var userModule = require("/app/modules/user.js").userModule; -var deviceModule = require("/app/modules/device.js").deviceModule; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; +var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; -var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; -var util = require("/app/modules/util.js").util; +var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; +var util = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var responseProcessor = require('utils').response; @@ -46,10 +46,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPair("password", { - "username": username, - "password": password - }); + apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password); }, function () { response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()}); }); @@ -68,7 +65,8 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPair("password", {"username": username, "password": password}); + + apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password); var permissions = userModule.getUIPermissions(); if (permissions.VIEW_DASHBOARD) { response.sendRedirect(constants.WEB_APP_CONTEXT); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index 8c732e33cd..cf19f5ec5b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -1,68 +1,125 @@ { - "appContext" : "/devicemgt/", - "webAgentContext" : "/devicemgt-web-agent/", - "apiContext" : "api", - "httpsURL" : "https://localhost:8243", - "httpURL" : "%http.ip%", - "httpsWebURL" : "%https.ip%", - "wssURL" : "%https.ip%", - "wsURL" : "%http.ip%", - "dashboardserverURL" : "%https.ip%", - "enrollmentDir": "/emm-web-agent/enrollment", - "iOSConfigRoot" : "%https.ip%/ios-enrollment/", - "iOSAPIRoot" : "%https.ip%/ios/", - "dynamicClientRegistrationEndPoint" : "https://localhost:8243/dynamic-client-web/register/", - "adminService":"%https.ip%", - "idPServer":"https://localhost:8243", - "callBackUrl":"%https.ip%/devicemgt_admin", - "adminUser":"admin@carbon.super", - "adminRole":"admin", - "usernameLength":30, - "ssoConfiguration" : { - "enabled" : false, - "issuer" : "devicemgt", - "appName" : "devicemgt", - "identityProviderURL" : "%https.ip%/sso/samlsso.jag", - "responseSigningEnabled" : "true", - "keyStorePassword" : "wso2carbon", - "identityAlias" : "wso2carbon", - "keyStoreName" : "/repository/resources/security/wso2carbon.jks" - }, - "userValidationConfig" : { - "usernameJSRegEx" : "^[\\S]{3,30}$", - "usernameRegExViolationErrorMsg" : "Provided username is invalid.", - "usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.", - "firstnameJSRegEx" : "^[\\S]{3,30}$", - "firstnameRegExViolationErrorMsg" : "Provided first name is invalid.", - "lastnameJSRegEx" : "^[\\S]{3,30}$", - "lastnameRegExViolationErrorMsg" : "Provided last name is invalid.", - "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", - "emailRegExViolationErrorMsg" : "Provided email is invalid." - }, - "groupValidationConfig": { - "groupNameJSRegEx": "^[\\S]{3,30}$", - "groupNameRegExViolationErrorMsg": "Provided group name is invalid.", - "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." - }, - "roleValidationConfig" : { - "rolenameJSRegEx" : "^[\\S]{3,30}$", - "rolenameRegExViolationErrorMsg" : "Provided role name is invalid.", - "rolenameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces." - }, - "generalConfig" : { - "host" : "https://localhost:9443", - "companyName" : "WSO2 Carbon Device Manager", - "browserTitle" : "WSO2 Device Manager", - "copyrightPrefix" : "\u00A9 %date-year%, ", - "copyrightOwner" : "WSO2 Inc.", - "copyrightOwnersSite" : "http://www.wso2.org", - "copyrightSuffix" : " All Rights Reserved." - }, - "scopes" : ["license-add", "license-view", "device-view", "device-info", "device-list", "device-view-own", - "device-modify", "device-search", "operation-install", "operation-view", "operation-modify", "operation-uninstall", - "group-add", "group-share", "group-modify", "group-view", "group-remove", "certificate-modify", "certificate-view", - "configuration-view", "configuration-modify", "policy-view", "policy-modify", "device-notification-view", - "device-notification-modify", "feature-view", "arduino_device", "arduino_user", " android_sense_user", - "virtual_firealarm_user", "raspberrypi_user", "roles-view", "roles-modify", "roles-remove", "roles-add", - "user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"] + "appContext": "/emm/", + "webAgentContext" : "/emm-web-agent/", + "apiContext": "api", + "httpsURL" : "%https.ip%", + "httpURL" : "%http.ip%", + "httpsWebURL" : "%https.ip%", + "wssURL" : "%https.ip%", + "wsURL" : "%http.ip%", + "dashboardServerURL" : "%https.ip%", + "enrollmentDir": "/emm-web-agent/enrollment", + "iOSConfigRoot" : "%https.ip%/ios-enrollment/", + "iOSAPIRoot" : "%https.ip%/ios/", + "adminService": "%https.ip%", + "oauthProvider": { + "appRegistration": { + "appType": "webapp", + "clientName": "emm", + "owner": "admin@carbon.super", + "dynamicClientAppRegistrationServiceURL": "%https.ip%/dynamic-client-web/register", + "apiManagerClientAppRegistrationServiceURL": "%https.ip%/api-application-registration/register/tenants", + "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer", + "tokenScope": "admin", + "callbackUrl": "%https.ip%/api/device-mgt/v1.0" + }, + "tokenServiceURL": "%https.ip%/oauth2/token" + }, + "adminUser":"admin@carbon.super", + "adminRole":"admin", + "usernameLength":30, + "pageSize":10, + "ssoConfiguration" : { + "enabled" : false, + "issuer" : "devicemgt", + "appName" : "devicemgt", + "identityProviderURL" : "%https.ip%/sso/samlsso.jag", + "responseSigningEnabled" : "true", + "keyStorePassword" : "wso2carbon", + "identityAlias" : "wso2carbon", + "keyStoreName" : "/repository/resources/security/wso2carbon.jks" + }, + "userValidationConfig" : { + "usernameJSRegEx" : "^[\\S]{3,30}$", + "usernameRegExViolationErrorMsg" : "Provided username is invalid.", + "usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.", + "firstnameJSRegEx" : "^[\\S]{3,30}$", + "firstnameRegExViolationErrorMsg" : "Provided first name is invalid.", + "lastnameJSRegEx" : "^[\\S]{3,30}$", + "lastnameRegExViolationErrorMsg" : "Provided last name is invalid.", + "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", + "emailRegExViolationErrorMsg" : "Provided email is invalid." + }, + "groupValidationConfig": { + "groupNameJSRegEx": "^[\\S]{3,30}$", + "groupNameRegExViolationErrorMsg": "Provided group name is invalid.", + "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." + }, + "roleValidationConfig" : { + "roleNameJSRegEx" : "^[\\S]{3,30}$", + "roleNameRegExViolationErrorMsg" : "Provided role name is invalid.", + "roleNameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces." + }, + "generalConfig" : { + "host" : "https://localhost:9443", + "companyName" : "WSO2 Carbon Device Manager", + "browserTitle" : "WSO2 Device Manager", + "copyrightPrefix" : "\u00A9 %date-year%, ", + "copyrightOwner" : "WSO2 Inc.", + "copyrightOwnersSite" : "http://www.wso2.org", + "copyrightSuffix" : " All Rights Reserved." + }, + "scopes" : [ + "user:manage", + "user:view", + "device-type:admin:view", + "device:view", + "notification:view", + "device:admin:view", + "application:manage", + "activity:view", + "user:admin:reset-password", + "policy:manage", + "policy:view", + "role:manage", + "role:view", + "configuration:view", + "configuration:modify", + "device:android:operation:reboot", + "device:android:operation:camera", + "device:android:operation:vpn", + "device:android:operation:lock", + "device:android:operation:ring", + "device:android:operation:update-app", + "device:android:operation:wipe", + "device:android:operation:encrypt", + "device:android:operation:blacklist-app", + "device:android:operation:applications", + "device:android:operation:enterprise-wipe", + "device:android:operation:info", + "device:android:operation:wifi", + "device:android:operation:uninstall-app", + "device:android:operation:change-lock", + "device:android:operation:notification", + "device:android:operation:upgrade", + "device:android:operation:unlock", + "device:android:operation:mute", + "device:android:operation:location", + "device:android:operation:webclip", + "device:android:operation:clear-password", + "device:android:operation:password-policy", + "device:android:operation:install-app", + "device:android:event:write", + "device:android:event:read", + "device:android:enroll", + "configuration:manage", + "configuration:view", + "device:android:enroll", + "certificate:view", + "certificate:manage" + ], + "isOAuthEnabled" : true, + "backendRestEndpoints" : { + "deviceMgt" : "/api/device-mgt/v1.0" + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js deleted file mode 100644 index 02df5fb3a1..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (c) 2015, 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. - */ - -/** - * ---------------------------------------------------------------------------- - * Following module includes invokers - * at Jaggery Layer for calling Backend Services, protected by OAuth Tokens. - * These Services include both REST and SOAP Services. - * ---------------------------------------------------------------------------- - */ -var handlers = function () { - var log = new Log("/app/modules/token-handlers.js"); - - var tokenUtil = require("/app/modules/util.js")["util"]; - var constants = require("/app/modules/constants.js"); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - - var privateMethods = {}; - var publicMethods = {}; - - privateMethods.setUpEncodedTenantBasedClientCredentials = function (username) { - if (!username) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + - "client credentials to session context. No username is found as " + - "input - setUpEncodedTenantBasedClientCredentials(x)"); - } else { - var dynamicClientCredentials = tokenUtil.getDynamicClientCredentials(); - if (!dynamicClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + - "client credentials to session context as the server is unable to obtain " + - "dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)"); - } else { - var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); - if (!jwtToken) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + - "client credentials to session context as the server is unable to obtain " + - "a jwt token - setUpEncodedTenantBasedClientCredentials(x)"); - } else { - var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken); - if (!tenantBasedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " + - "based client credentials to session context as the server is unable " + - "to obtain such credentials - setUpEncodedTenantBasedClientCredentials(x)"); - } else { - var encodedTenantBasedClientCredentials = - tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" + - tenantBasedClientCredentials["clientSecret"]); - // setting up encoded tenant based client credentials to session context. - session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials); - } - } - } - } - }; - - publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) { - if (!username || !password) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + - "password grant type. Either username, password or both are missing as " + - "input - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - privateMethods.setUpEncodedTenantBasedClientCredentials(username); - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + - "password grant type. Encoded client credentials are " + - "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - var accessTokenPair; - // accessTokenPair will include current access token as well as current refresh token - var arrayOfScopes = devicemgtProps["scopes"]; - var stringOfScopes = ""; - arrayOfScopes.forEach(function (entry) { - stringOfScopes += entry + " "; - }); - accessTokenPair = tokenUtil. - getTokenWithPasswordGrantType(username, - encodeURIComponent(password), encodedClientCredentials, stringOfScopes); - if (!accessTokenPair) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access " + - "token pair by password grant type. Error in token " + - "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - // setting up access token pair into session context as a string - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); - } - } - } - }; - - publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) { - if (!username || !samlToken) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + - "saml grant type. Either username, samlToken or both are missing as " + - "input - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - privateMethods.setUpEncodedTenantBasedClientCredentials(username); - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair " + - "by saml grant type. Encoded client credentials are " + - "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - var accessTokenPair; - // accessTokenPair will include current access token as well as current refresh token - accessTokenPair = tokenUtil. - getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); - if (!accessTokenPair) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token " + - "pair by password grant type. Error in token " + - "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - // setting up access token pair into session context as a string - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); - } - } - } - }; - - publicMethods.refreshToken = function () { - var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); - // accessTokenPair includes current access token as well as current refresh token - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!accessTokenPair || !encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Error in refreshing tokens. Either the access " + - "token pair, encoded client credentials or both input are not found under " + - "session context - refreshToken()"); - } else { - var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); - if (!newAccessTokenPair) { - log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " + - "session context with new access token pair - refreshToken()"); - } else { - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newAccessTokenPair)); - } - } - }; - - return publicMethods; -}(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js new file mode 100644 index 0000000000..21360452c1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -0,0 +1,369 @@ +/* + * 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. + */ + +var deviceModule; +deviceModule = function () { + var log = new Log("/app/modules/business-controllers/device.js"); + + var utility = require('/app/modules/utility.js').utility; + var constants = require('/app/modules/constants.js'); + var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; + +// var ArrayList = Packages.java.util.ArrayList; +// var Properties = Packages.java.util.Properties; +// var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier; +// var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +// var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation; +// var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; +// var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; + + var deviceManagementService = utility.getDeviceManagementService(); + + var publicMethods = {}; + var privateMethods = {}; + +// var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; + +/** + * Only GET method is implemented for now since there are no other type of methods used this method. + * @param url - URL to call the backend without the host + * @param method - HTTP Method (GET, POST) + * @returns An object with 'status': 'success'|'error', 'content': {} + */ + privateMethods.callBackend = function (url, method) { + if (constants["HTTP_GET"] == method) { + return serviceInvokers.XMLHttp.get(url, + function (backendResponse) { + var response = {}; + response.content = backendResponse.responseText; + if (backendResponse.status == 200) { + response.status = "success"; + } else if (backendResponse.status == 400 || backendResponse.status == 401 || + backendResponse.status == 404 || backendResponse.status == 500) { + response.status = "error"; + } + return response; + } + ); + } else { + log.error("Runtime error : This method only support HTTP GET requests."); + } + }; + + privateMethods.validateAndReturn = function (value) { + return (value == undefined || value == null) ? constants.UNSPECIFIED : value; + }; + + /* + @Deprecated + */ +// publicMethods.listDevices = function () { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var devices = deviceManagementService.getAllDevices(); +// var deviceList = []; +// var i, device, propertiesList, deviceObject; +// for (i = 0; i < devices.size(); i++) { +// device = devices.get(i); +// propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); +// +// deviceObject = {}; +// deviceObject[constants.DEVICE_IDENTIFIER] = +// privateMethods.validateAndReturn(device.getDeviceIdentifier()); +// deviceObject[constants.DEVICE_NAME] = +// privateMethods.validateAndReturn(device.getName()); +// deviceObject[constants.DEVICE_OWNERSHIP] = +// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); +// deviceObject[constants.DEVICE_OWNER] = +// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); +// deviceObject[constants.DEVICE_TYPE] = +// privateMethods.validateAndReturn(device.getType()); +// deviceObject[constants.DEVICE_PROPERTIES] = {}; +// if (device.getType() == constants.PLATFORM_IOS) { +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; +// } else { +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); +// } +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); +// +// deviceList.push(deviceObject); +// } +// return deviceList; +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; + + /* + @Deprecated + */ + /* + Get the supported features by the device type + */ +// publicMethods.getFeatures = function (deviceType) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var features = deviceManagementService.getFeatureManager(deviceType).getFeatures(); +// var featuresConverted = {}; +// if (features) { +// var i, feature, featureObject; +// for (i = 0; i < features.size(); i++) { +// feature = features.get(i); +// featureObject = {}; +// featureObject[constants.FEATURE_NAME] = feature.getName(); +// featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription(); +// featuresConverted[feature.getName()] = featureObject; +// } +// } +// return featuresConverted; +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; + + /* + @Deprecated + */ +// publicMethods.performOperation = function (devices, operation) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var operationInstance; +// if (operation.type == "COMMAND") { +// operationInstance = new CommandOperation(); +// } else if (operation.type == "CONFIG") { +// operationInstance = new ConfigOperation(); +// } else { +// operationInstance = new SimpleOperation(); +// } +// operationInstance.setCode(operation.featureName); +// var props = new Properties(); +// var i, object; +// for (i = 0; i < operation.properties.length; i++) { +// object = properties[i]; +// props.setProperty(object.key, object.value); +// } +// operationInstance.setProperties(props); +// var deviceList = new ArrayList(); +// var j, device, deviceIdentifier; +// for (j = 0; j < devices.length; i++) { +// device = devices[j]; +// deviceIdentifier = new DeviceIdentifier(); +// deviceIdentifier.setId(device.id); +// deviceIdentifier.setType(device.type); +// deviceList.add(deviceIdentifier); +// } +// deviceManagementService.addOperation(operationInstance, deviceList); +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; + + /* + @Deprecated + */ +// privateMethods.getDevice = function (type, deviceId) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var deviceIdentifier = new DeviceIdentifier(); +// deviceIdentifier.setType(type); +// deviceIdentifier.setId(deviceId); +// return deviceManagementService.getDevice(deviceIdentifier); +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; + + /* + @Updated + */ + publicMethods.viewDevice = function (deviceType, deviceId) { + var carbonUser = session.get(constants["USER_SESSION_KEY"]); + if (!carbonUser) { + log.error("User object was not found in the session"); + throw constants["ERRORS"]["USER_NOT_FOUND"]; + } + var utility = require('/app/modules/utility.js')["utility"]; + try { + utility.startTenantFlow(carbonUser); + //var url = mdmProps["httpsURL"] + "/mdm-admin/devices/view?type=" + deviceType + "&id=" + deviceId; + var url = mdmProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId; + return serviceInvokers.XMLHttp.get( + url, + function (backendResponse) { + var response = {}; + if (backendResponse.status == 200 && backendResponse.responseText) { + response["status"] = "success"; + var device = parse(backendResponse.responseText); + var propertiesList = device["properties"]; + var properties = {}; + for (var i = 0; i < propertiesList.length; i++) { + properties[propertiesList[i]["name"]] = + propertiesList[i]["value"]; + } + var deviceObject = {}; + deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; + deviceObject[constants["DEVICE_NAME"]] = device["name"]; + deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; + deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; + deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; + deviceObject[constants["DEVICE_TYPE"]] = device["type"]; + if (device["type"] == constants["PLATFORM_IOS"]) { + properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; + delete properties[constants["DEVICE_PRODUCT"]]; + properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; + } + deviceObject[constants["DEVICE_PROPERTIES"]] = properties; + response["content"] = deviceObject; + return response; + } else { + response["status"] = "error"; + return response; + } + } + ); + } catch (e) { + throw e; + } finally { + utility.endTenantFlow(); + } + }; + + // Refactored methods + publicMethods.getDevicesCount = function () { + var carbonUser = session.get(constants.USER_SESSION_KEY); + if (carbonUser) { + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var uiPermissions = userModule.getUIPermissions(); + var url; + if (uiPermissions.LIST_DEVICES) { + url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count"; + } else if (uiPermissions.LIST_OWN_DEVICES) { + url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username + + "/count"; + } else { + log.error("Access denied for user: " + carbonUser.username); + return -1; + } + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } + ); + } else { + log.error("User object was not found in the session"); + throw constants["ERRORS"]["USER_NOT_FOUND"]; + } + }; + + publicMethods.getDeviceTypes = function () { + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types"; + var response = privateMethods.callBackend(url, constants["HTTP_GET"]); + if (response.status == "success") { + response.content = parse(response.content); + } + return response; + }; + + //Old methods + //TODO: make sure these methods are updated + /* + @Updated + */ + // publicMethods.getLicense = function (deviceType) { + // var url; + // var license; + // if (deviceType == "windows") { + // url = mdmProps["httpURL"] + "/mdm-windows-agent/services/device/license"; + // } else if (deviceType == "ios") { + // url = mdmProps["httpsURL"] + "/ios-enrollment/license/"; + // } + + // if (url != null && url != undefined) { + // serviceInvokers.XMLHttp.get(url, function (responsePayload) { + // license = responsePayload.text; + // }, function (responsePayload) { + // return null; + // }); + // } + // return license; + // }; + + publicMethods.getDevices = function (userName) { + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName; + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + for (var i = 0; i < responsePayload.length; i++) { + responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type); + } + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } + ); + }; + return publicMethods; +}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js similarity index 89% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js index 61bfe9f4b7..02b2198b48 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js @@ -18,13 +18,13 @@ var groupModule = {}; (function (groupModule) { - var log = new Log("/app/modules/group.js"); + var log = new Log("/app/modules/business-controllers/group.js"); - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var utility = require("/app/modules/utility.js").utility; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js similarity index 95% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js index 981a58f5ce..e96ffcdec1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js @@ -17,11 +17,11 @@ */ var operationModule = function () { - var log = new Log("/app/modules/operation.js"); + var log = new Log("/app/modules/business-controllers/operation.js"); var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js new file mode 100644 index 0000000000..2d22a6f9cb --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2015, 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. + */ + +var policyModule; +policyModule = function () { + var log = new Log("/app/modules/business-controllers/policy.js"); + + var constants = require('/app/modules/constants.js'); + var utility = require("/app/modules/utility.js")["utility"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; + + var publicMethods = {}; + var privateMethods = {}; + + privateMethods.handleGetAllPoliciesResponse = function (backendResponse) { + var response = {}; + if (backendResponse.status == 200 && backendResponse.responseText) { + var isUpdated = false; + var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"]; + + var policyListToView = []; + var i, policyObjectFromRestEndpoint, policyObjectToView; + for (i = 0; i < policyListFromRestEndpoint.length; i++) { + // get list object + policyObjectFromRestEndpoint = policyListFromRestEndpoint[i]; + // populate list object values to view-object + policyObjectToView = {}; + policyObjectToView["id"] = policyObjectFromRestEndpoint["id"]; + policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; + policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; + policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]; + policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); + policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; + + var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length; + var assignedUserCount = policyObjectFromRestEndpoint["users"].length; + + if (assignedRoleCount == 0) { + policyObjectToView["roles"] = "None"; + } else if (assignedRoleCount == 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0]; + } else if (assignedRoleCount > 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0] + ", ..."; + } + + if (assignedUserCount == 0) { + policyObjectToView["users"] = "None"; + } else if (assignedUserCount == 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0]; + } else if (assignedUserCount > 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0] + ", ..."; + } + + policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"]; + + if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Active/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Active"; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Inactive/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Inactive"; + } + // push view-objects to list + policyListToView.push(policyObjectToView); + } + // generate response + response.updated = isUpdated; + response.status = "success"; + response.content = policyListToView; + + return response; + } else { + response.status = "error"; + /* backendResponse.responseText == "Scope validation failed" + Here the response.context("Scope validation failed") is used other then response.status(401). + Reason for this is IDP return 401 as the status in 4 different situations such as, + 1. UnAuthorized. + 2. Scope Validation Failed. + 3. Permission Denied. + 4. Access Token Expired. + 5. Access Token Invalid. + In these cases in order to identify the correct situation we have to compare the unique value from status and + context which is context. + */ + if (backendResponse.responseText == "Scope validation failed") { + response.content = "Permission Denied"; + } else { + response.content = backendResponse.responseText; + } + return response; + } + }; + + /* + @Updated + */ + publicMethods.getAllPolicies = function () { + var carbonUser = session.get(constants["USER_SESSION_KEY"]); + if (!carbonUser) { + log.error("User object was not found in the session"); + throw constants["ERRORS"]["USER_NOT_FOUND"]; + } + try { + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/policies?offset=0&limit=100"; + return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse); + } catch (e) { + throw e; + } + }; + + /* + @Updated - used by getAllPolicies + */ + privateMethods.getElementsInAString = function (elementList) { + var i, elementsInAString = ""; + for (i = 0; i < elementList.length; i++) { + if (i == elementList.length - 1) { + elementsInAString += elementList[i]; + } else { + elementsInAString += elementList[i] + ", "; + } + } + return elementsInAString; + }; + + return publicMethods; +}(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js similarity index 97% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index e02e286d91..70bd48770c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -20,12 +20,12 @@ * This module contains user and roles related functionality. */ var userModule = function () { - var log = new Log("/app/modules/user.js"); + var log = new Log("/app/modules/business-controllers/user.js"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js")["utility"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; /* Initializing user manager */ var carbon = require("carbon"); @@ -218,7 +218,8 @@ var userModule = function () { } try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles"; + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/roles?offset=0&limit=100"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); if (response.status == "success") { response.content = parse(response.content).roles; @@ -238,8 +239,7 @@ var userModule = function () { * Get User Roles from user store (Internal roles not included). * @returns {object} a response object with status and content on success. */ - publicMethods.getRolesByUserStore = function () { - var ROLE_LIMIT = devicemgtProps["pageSize"]; + publicMethods.getRolesByUserStore = function (userStore) { var carbonUser = session.get(constants["USER_SESSION_KEY"]); var utility = require("/app/modules/utility.js")["utility"]; if (!carbonUser) { @@ -248,7 +248,8 @@ var userModule = function () { } try { utility.startTenantFlow(carbonUser); - var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles?limit=" + ROLE_LIMIT; + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/roles?user-store=" + userStore + "&limit=100"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); if (response.status == "success") { response.content = parse(response.content).roles; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js similarity index 85% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js index ec5b6642f2..f81849fe3b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js @@ -17,16 +17,18 @@ */ var conf = function () { - var conf = application.get("UI_CONF"); + var conf = application.get("CONF"); if (!conf) { conf = require("/app/conf/config.json"); - var pinch = require("/app/conf/reader/pinch.min.js")["pinch"]; + var pinch = require("/app/modules/conf-reader/pinch.min.js")["pinch"]; var server = require("carbon")["server"]; pinch(conf, /^/, function (path, key, value) { if ((typeof value === "string") && value.indexOf("%https.ip%") > -1) { + //noinspection JSUnresolvedFunction return value.replace("%https.ip%", server.address("https")); } else if ((typeof value === "string") && value.indexOf("%http.ip%") > -1) { + //noinspection JSUnresolvedFunction return value.replace("%http.ip%", server.address("http")); } else if ((typeof value === "string") && value.indexOf("%date-year%") > -1) { var year = new Date().getFullYear(); @@ -35,7 +37,7 @@ var conf = function () { return value; } ); - application.put("UI_CONF", conf); + application.put("CONF", conf); } return conf; }(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/pinch.min.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/pinch.min.js similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/pinch.min.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/pinch.min.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index 3aa7af9975..79aa46e5de 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -59,8 +59,8 @@ var USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT = var SOAP_VERSION = 1.2; var WEB_SERVICE_ADDRESSING_VERSION = 1.0; -var ACCESS_TOKEN_PAIR_IDENTIFIER = "accessTokenPair"; -var ENCODED_CLIENT_KEYS_IDENTIFIER = "encodedClientKey"; +var TOKEN_PAIR = "tokenPair"; +var ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS = "encodedTenantBasedClientAppCredentials"; var CONTENT_TYPE_IDENTIFIER = "Content-Type"; var CONTENT_DISPOSITION_IDENTIFIER = "Content-Disposition"; var APPLICATION_JSON = "application/json"; @@ -83,3 +83,4 @@ var HTTP_CONFLICT = 409; var HTTP_CREATED = 201; var CACHED_CREDENTIALS = "tenantBasedCredentials"; +var ALLOWED_SCOPES = "scopes"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js deleted file mode 100644 index 8dfdd26f5e..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -var deviceModule; -deviceModule = function () { - var log = new Log("/app/modules/device.js"); - - var utility = require('/app/modules/utility.js').utility; - var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; - - var ArrayList = Packages.java.util.ArrayList; - var Properties = Packages.java.util.Properties; - var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier; - var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; - var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation; - var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; - var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; - - var publicMethods = {}; - var privateMethods = {}; - - var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; - - /** - * Only GET method is implemented for now since there are no other type of methods used this method. - * @param url - URL to call the backend without the host - * @param method - HTTP Method (GET, POST) - * @returns An object with 'status': 'success'|'error', 'content': {} - */ - privateMethods.callBackend = function (url, method) { - if (constants["HTTP_GET"] == method) { - return serviceInvokers.XMLHttp.get(url, - function (backendResponse) { - var response = {}; - response.content = backendResponse.responseText; - if (backendResponse.status == 200) { - response.status = "success"; - } else if (backendResponse.status == 400 || backendResponse.status == 401 || - backendResponse.status == 404 || backendResponse.status == 500) { - response.status = "error"; - } - return response; - } - ); - } else { - log.error("Runtime error : This method only support HTTP GET requests."); - } - }; - - privateMethods.validateAndReturn = function (value) { - return (value == undefined || value == null) ? constants.UNSPECIFIED : value; - }; - - /* - @Deprecated - */ - publicMethods.listDevices = function () { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var devices = deviceManagementService.getAllDevices(); - var deviceList = []; - var i, device, propertiesList, deviceObject; - for (i = 0; i < devices.size(); i++) { - device = devices.get(i); - propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); - - deviceObject = {}; - deviceObject[constants.DEVICE_IDENTIFIER] = - privateMethods.validateAndReturn(device.getDeviceIdentifier()); - deviceObject[constants.DEVICE_NAME] = - privateMethods.validateAndReturn(device.getName()); - deviceObject[constants.DEVICE_OWNERSHIP] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); - deviceObject[constants.DEVICE_OWNER] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); - deviceObject[constants.DEVICE_TYPE] = - privateMethods.validateAndReturn(device.getType()); - deviceObject[constants.DEVICE_PROPERTIES] = {}; - if (device.getType() == constants.PLATFORM_IOS) { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; - } else { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); - } - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); - - deviceList.push(deviceObject); - } - return deviceList; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Deprecated - */ - /* - Get the supported features by the device type - */ - publicMethods.getFeatures = function (deviceType) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var features = deviceManagementService.getFeatureManager(deviceType).getFeatures(); - var featuresConverted = {}; - if (features) { - var i, feature, featureObject; - for (i = 0; i < features.size(); i++) { - feature = features.get(i); - featureObject = {}; - featureObject[constants.FEATURE_NAME] = feature.getName(); - featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription(); - featuresConverted[feature.getName()] = featureObject; - } - } - return featuresConverted; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Deprecated - */ - publicMethods.performOperation = function (devices, operation) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var operationInstance; - if (operation.type == "COMMAND") { - operationInstance = new CommandOperation(); - } else if (operation.type == "CONFIG") { - operationInstance = new ConfigOperation(); - } else { - operationInstance = new SimpleOperation(); - } - operationInstance.setCode(operation.featureName); - var props = new Properties(); - var i, object; - for (i = 0; i < operation.properties.length; i++) { - object = properties[i]; - props.setProperty(object.key, object.value); - } - operationInstance.setProperties(props); - var deviceList = new ArrayList(); - var j, device, deviceIdentifier; - for (j = 0; j < devices.length; i++) { - device = devices[j]; - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(device.id); - deviceIdentifier.setType(device.type); - deviceList.add(deviceIdentifier); - } - deviceManagementService.addOperation(operationInstance, deviceList); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Deprecated - */ - privateMethods.getDevice = function (type, deviceId) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(type); - deviceIdentifier.setId(deviceId); - return deviceManagementService.getDevice(deviceIdentifier); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Updated - */ - publicMethods.viewDevice = function (deviceType, deviceId) { - var carbonUser = session.get(constants["USER_SESSION_KEY"]); - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; - } - var utility = require('/app/modules/utility.js')["utility"]; - try { - utility.startTenantFlow(carbonUser); - - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId; - return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - var device = responsePayload.responseContent; - if (device) { - var propertiesList = device["properties"]; - var properties = {}; - if (propertiesList){ - for (var i = 0; i < propertiesList.length; i++) { - properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; - } - } - var deviceObject = {}; - deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; - deviceObject[constants["DEVICE_NAME"]] = device["name"]; - deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; - deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; - deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; - deviceObject[constants["DEVICE_TYPE"]] = device["type"]; - if (device["type"] == constants["PLATFORM_IOS"]) { - properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; - delete properties[constants["DEVICE_PRODUCT"]]; - properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; - } - deviceObject[constants["DEVICE_PROPERTIES"]] = properties; - return deviceObject; - } - }, - function (responsePayload) { - var response = {}; - response["status"] = "error"; - return response; - } - ); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - // Refactored methods - publicMethods.getDevicesCount = function () { - var carbonUser = session.get(constants.USER_SESSION_KEY); - if (carbonUser) { - var userModule = require("/app/modules/user.js").userModule; - var uiPermissions = userModule.getUIPermissions(); - var url; - if (uiPermissions.LIST_DEVICES) { - url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count"; - } else if (uiPermissions.LIST_OWN_DEVICES) { - url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username - + "/count"; - } else { - log.error("Access denied for user: " + carbonUser.username); - return -1; - } - return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - return responsePayload; - }, - function (responsePayload) { - log.error(responsePayload); - return -1; - } - ); - } else { - log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; - } - }; - - publicMethods.getDeviceTypes = function () { - var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types"; - var response = privateMethods.callBackend(url, constants["HTTP_GET"]); - if (response.status == "success") { - response.content = parse(response.content); - } - return response; - }; - - //Old methods - //TODO: make sure these methods are updated - /* - @Updated - */ - publicMethods.getLicense = function (deviceType) { - var url; - var license; - if (deviceType == "windows") { - url = devicemgtProps["httpURL"] + "/mdm-windows-agent/services/device/license"; - } else if (deviceType == "ios") { - url = devicemgtProps["httpsURL"] + "/ios-enrollment/license/"; - } - - if (url != null && url != undefined) { - serviceInvokers.XMLHttp.get(url, function (responsePayload) { - license = responsePayload.text; - }, function (responsePayload) { - return null; - }); - } - return license; - }; - - publicMethods.getDevices = function (userName) { - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName; - return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - for (var i = 0; i < responsePayload.length; i++) { - responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type); - } - return responsePayload; - }, - function (responsePayload) { - log.error(responsePayload); - return -1; - } - ); - }; - return publicMethods; -}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index 35c902dbab..d9f442cdd4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -17,14 +17,14 @@ */ var carbonModule = require("carbon"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var carbonServer = new carbonModule.server.Server({ tenanted: true, url: devicemgtProps["httpsURL"] + "/admin" }); application.put("carbonServer", carbonServer); -var userModule = require("/app/modules/user.js")["userModule"]; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var utility = require("/app/modules/utility.js")["utility"]; var permissions = { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js deleted file mode 100644 index d191b1868d..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2015, 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. - */ - -/* - @Deprecated - new - */ - -/** - * This invokerRequestWrapper contains the wrappers for invoker util requests. - */ -//var invokerRequestWrapper = function () { -// -// var constants = require("/modules/constants.js"); -// var serviceInvokers = require("/modules/backend-service-invoker.js").backendServiceInvoker; -// -// var publicWrappers = []; -// -// publicWrappers.initiate = function (method, url, payload) { -// switch (method) { -// case constants.HTTP_GET: -// var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_POST: -// var response = serviceInvokers.XMLHttp.post(url, payload, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_PUT: -// var response = serviceInvokers.XMLHttp.put(url, payload, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_DELETE: -// var response = serviceInvokers.XMLHttp.delete(url, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// } -// } -// -//}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 429a6b9c1c..87f840d3ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -24,13 +24,13 @@ var onFail; var constants = require("/app/modules/constants.js"); onSuccess = function (context) { var utility = require("/app/modules/utility.js").utility; - var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; + var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; if (context.input.samlToken) { - apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); + apiWrapperUtil.setupTokenPairBySamlGrantType(context.input.username, context.input.samlToken); } else { - apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(context.input.username, context.input.password); + apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password); } - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var carbonServer = require("carbon").server; (new carbonServer.Server({url: devicemgtProps["adminService"]})) .login(context.input.username, context.input.password); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js new file mode 100644 index 0000000000..ba7827173b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2015, 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. + */ + +var utils = function () { + var log = new Log("/app/modules/oauth/token-handler-utils.js"); + + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var constants = require("/app/modules/constants.js"); + var carbon = require("carbon"); + + //noinspection JSUnresolvedVariable + var Base64 = Packages.org.apache.commons.codec.binary.Base64; + //noinspection JSUnresolvedVariable + var String = Packages.java.lang.String; + + var publicMethods = {}; + var privateMethods = {}; + + publicMethods["encode"] = function (payload) { + //noinspection JSUnresolvedFunction + return String(Base64.encodeBase64(String(payload).getBytes())); + }; + + publicMethods["decode"] = function (payload) { + //noinspection JSUnresolvedFunction + return String(Base64.decodeBase64(String(payload).getBytes())); + }; + + publicMethods["getDynamicClientAppCredentials"] = function () { + // setting up dynamic client application properties + var dcAppProperties = { + "applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"], + "clientName": deviceMgtProps["oauthProvider"]["appRegistration"]["clientName"], + "owner": deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], + "tokenScope": deviceMgtProps["oauthProvider"]["appRegistration"]["tokenScope"], + "grantType": deviceMgtProps["oauthProvider"]["appRegistration"]["grantType"], + "callbackUrl": deviceMgtProps["oauthProvider"]["appRegistration"]["callbackUrl"], + "saasApp" : true + }; + // calling dynamic client app registration service endpoint + var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] + ["dynamicClientAppRegistrationServiceURL"]; + var requestPayload = dcAppProperties; + + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.send(stringify(requestPayload)); + + var dynamicClientAppCredentials = {}; + if (xhr["status"] == 201 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + dynamicClientAppCredentials["clientId"] = responsePayload["client_id"]; + dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; + } else if (xhr["status"] == 400) { + log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + + "Bad request. Invalid data provided as dynamic client application properties."); + dynamicClientAppCredentials = null; + } else { + log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + + "Error in retrieving dynamic client credentials."); + dynamicClientAppCredentials = null; + } + // returning dynamic client credentials + return dynamicClientAppCredentials; + }; + + publicMethods["getTenantBasedClientAppCredentials"] = function (username, jwtToken) { + if (!username || !jwtToken) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client app credentials. No username or jwt token is found " + + "as input - getTenantBasedClientAppCredentials(x, y)"); + return null; + } else { + //noinspection JSUnresolvedFunction, JSUnresolvedVariable + var tenantDomain = carbon.server.tenantDomain({username: username}); + if (!tenantDomain) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials. Unable to obtain a valid tenant domain for provided " + + "username - getTenantBasedClientAppCredentials(x, y)"); + return null; + } else { + var cachedTenantBasedClientAppCredentials = privateMethods. + getCachedTenantBasedClientAppCredentials(tenantDomain); + if (cachedTenantBasedClientAppCredentials) { + return cachedTenantBasedClientAppCredentials; + } else { + // register a tenant based client app at API Manager + var applicationName = "webapp_" + tenantDomain; + var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] + ["apiManagerClientAppRegistrationServiceURL"] + + "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; + + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("Authorization", "Bearer " + jwtToken); + xhr.send(); + + if (xhr["status"] == 201 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var tenantBasedClientAppCredentials = {}; + tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"]; + tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; + privateMethods. + setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); + return tenantBasedClientAppCredentials; + } else { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials from API " + + "Manager - getTenantBasedClientAppCredentials(x, y)"); + return null; + } + } + } + } + }; + + privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); + if (!cachedTenantBasedClientAppCredentialsMap) { + cachedTenantBasedClientAppCredentialsMap = {}; + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap); + } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + } + }; + + privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); + if (!cachedTenantBasedClientAppCredentialsMap || + !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + return null; + } else { + return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; + } + }; + + publicMethods["getTokenPairByPasswordGrantType"] = function (username, password, encodedClientAppCredentials, scopes) { + if (!username || !password || !encodedClientAppCredentials || !scopes) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + + "grant type. No username, password, encoded client app credentials or scopes are " + + "found - getTokenPairByPasswordGrantType(a, b, c, d)"); + return null; + } else { + // calling oauth provider token service endpoint + var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"]; + var requestPayload = "grant_type=password&username=" + + username + "&password=" + password + "&scope=" + scopes; + + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); + xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); + xhr.send(requestPayload); + + if (xhr["status"] == 200 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var tokenData = {}; + tokenData["accessToken"] = responsePayload["access_token"]; + tokenData["refreshToken"] = responsePayload["refresh_token"]; + tokenData["scopes"] = responsePayload["scope"]; + return tokenData; + } else { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " + + "by password grant type - getTokenPairByPasswordGrantType(a, b, c, d)"); + return null; + } + } + }; + + publicMethods["getTokenPairBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) { + if (!assertion || !encodedClientAppCredentials || !scopes) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + + "grant type. No assertion, encoded client app credentials or scopes are " + + "found - getTokenPairBySAMLGrantType(x, y, z)"); + return null; + } else { + var assertionXML = publicMethods.decode(assertion); + /* + TODO: make assertion extraction with proper parsing. + Since Jaggery XML parser seem to add formatting which causes signature verification to fail. + */ + var assertionStartMarker = " @@ -24,6 +25,7 @@
  • + Policies @@ -36,5 +38,6 @@ {{/zone}} {{#zone "content"}} + {{unit "cdmf.unit.device.operation-mod"}} {{unit "cdmf.unit.policy.create"}} {{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs index c6519777db..9d7f4445bd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs @@ -2,20 +2,21 @@ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at + 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 + 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 + "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. }} -{{unit "cdmf.unit.ui.title" pageTitle="Policy Management"}} + +{{unit "cdmf.unit.ui.title" pageTitle="Policy Management | Edit Policy"}} {{#zone "breadcrumbs"}}
  • @@ -24,6 +25,7 @@
  • + Policies @@ -36,5 +38,6 @@ {{/zone}} {{#zone "content"}} - {{unit deviceTypePolicyEdit}} + {{unit "cdmf.unit.device.operation-mod"}} + {{unit "cdmf.unit.policy.edit"}} {{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js index e39d8b9316..fa2282141b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js @@ -20,4 +20,4 @@ function onRequest(context) { var utility = require("/app/modules/utility.js").utility; var deviceType = request.getParameter("type"); return {"deviceTypePolicyEdit": utility.getTenantedDeviceUnitName(deviceType, "policy-edit")}; -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json index fcddd12965..f2122eb998 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json @@ -1,5 +1,5 @@ { "version": "1.0.0", - "uri": "/policy/edit", + "uri": "/policy/edit", "layout": "cdmf.layout.default" } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.hbs index 6295e4b87d..7b1a0775fe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.hbs @@ -15,7 +15,7 @@ specific language governing permissions and limitations under the License. }} -{{unit "cdmf.unit.ui.title" pageTitle="Policy Management"}} +{{unit "cdmf.unit.ui.title" pageTitle="Policy Management | Policy Priorities"}} {{#zone "breadcrumbs"}}
  • @@ -24,10 +24,17 @@
  • + Policies
  • +
  • + + + Priorities + +
  • {{/zone}} {{#zone "content"}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.json index 96ec4c8d85..b8be6d8bbb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.priority/priority.json @@ -1,5 +1,5 @@ { "version": "1.0.0", - "uri": "/policy/priority", + "uri": "/policy/priority", "layout": "cdmf.layout.default" } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs index f3113d2069..ad8f81f82a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs @@ -2,20 +2,21 @@ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at + 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 + 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 + "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. }} -{{unit "cdmf.unit.ui.title" pageTitle="Policy Management"}} + +{{unit "cdmf.unit.ui.title" pageTitle="Policy Management | View Policy"}} {{#zone "breadcrumbs"}}
  • @@ -24,6 +25,7 @@
  • + Policies @@ -36,5 +38,6 @@ {{/zone}} {{#zone "content"}} - {{unit deviceTypePolicyView}} + {{unit "cdmf.unit.device.operation-mod"}} + {{unit "cdmf.unit.policy.view"}} {{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js index 58829242be..07e42077e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js @@ -17,7 +17,7 @@ */ function onRequest(context) { - var utility = require("/app/modules/utility.js").utility; + var utility = require("/app/modules/utility.js")["utility"]; var deviceType = request.getParameter("type"); return {"deviceTypePolicyView": utility.getTenantedDeviceUnitName(deviceType, "policy-view")}; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json index 77ddf10eaa..a4d19525f6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json @@ -1,5 +1,5 @@ { "version": "1.0.0", - "uri": "/policy/view", + "uri": "/policy/view", "layout": "cdmf.layout.default" } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.hbs index d9f24cd04f..9fc20f8049 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.hbs @@ -67,25 +67,19 @@
    - + - +
    - +
    - +
    @@ -121,6 +115,8 @@

    User was added successfully.


    An invitation mail will be sent to this user to initiate device enrollment. + Below QR code can also be used to enroll a device. +
    diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js index 70e9089a5f..a93b1a48cc 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js @@ -18,18 +18,16 @@ /** * Returns the dynamic state to be populated by add-user page. - * - * @param context Object that gets updated with the dynamic state of this page to be presented * @returns {*} A context object that returns the dynamic state of this page to be presented */ -function onRequest(context) { +function onRequest() { //var log = new Log("/app/pages/cdmf.page.user.create server-side js"); - var userModule = require("/app/modules/user.js")["userModule"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var page = {}; - var response = userModule.getRolesByUserStore(); + var response = userModule.getRolesByUserStore("PRIMARY"); if (response["status"] == "success") { page["roles"] = response["content"]; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/public/js/bottomJs.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/public/js/bottomJs.js index 7280042d59..c254b82cc9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/public/js/bottomJs.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/public/js/bottomJs.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, 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 @@ -72,8 +72,8 @@ var disableInlineError = function (inputField, errorMsg, errorSign) { * Validate if provided username is valid against RegEx configures. */ validateInline["user-name"] = function () { - var usernameinput = $("input#username"); - if (inputIsValid(usernameinput.data("regex"), usernameinput.val())) { + var usernameInput = $("input#username"); + if (inputIsValid(usernameInput.data("regex"), usernameInput.val())) { disableInlineError("usernameInputField", "usernameEmpty", "usernameError"); } else { enableInlineError("usernameInputField", "usernameEmpty", "usernameError"); @@ -84,9 +84,9 @@ validateInline["user-name"] = function () { * Validate if provided first name is valid against RegEx configures. */ validateInline["first-name"] = function () { - var firstnameinput = $("input#firstname"); - if (firstnameinput.val()) { - disableInlineError("firstNameField", "fnError"); + var firstnameInput = $("input#firstname"); + if (firstnameInput.val()) { + disableInlineError("firstNameField", "fnError"); } else { enableInlineError("firstNameField", "fnError"); } @@ -96,8 +96,8 @@ validateInline["first-name"] = function () { * Validate if provided last name is valid against RegEx configures. */ validateInline["last-name"] = function () { - var lastnameinput = $("input#lastname"); - if (lastnameinput.val()) { + var lastnameInput = $("input#lastname"); + if (lastnameInput.val()) { disableInlineError("lastNameField", "lnError"); } else { enableInlineError("lastNameField", "lnError"); @@ -165,9 +165,9 @@ $("#userStore").change( function () { var str = ""; $("select option:selected").each(function () { - str += $(this).text() + " "; + str += $(this).text() + ""; }); - var getRolesAPI = deviceMgtAPIsBasePath + "/roles/"+ str; + var getRolesAPI = deviceMgtAPIsBasePath + "/roles?user-store=" + str + "&limit=100"; invokerUtil.get( getRolesAPI, @@ -188,8 +188,7 @@ $("#userStore").change( } ); - } -).change(); + }).change(); $(document).ready(function () { $("#emailValidationText").hide(); @@ -207,7 +206,7 @@ $(document).ready(function () { var usernameInput = $("input#username"); var firstnameInput = $("input#firstname"); var lastnameInput = $("input#lastname"); - //var charLimit = parseInt($("input#username").attr("limit")); + var charLimit = parseInt($("input#username").attr("limit")); var domain = $("#userStore").val(); var username = usernameInput.val().trim(); var firstname = firstnameInput.val(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js index 8f94c2902b..a8eab03731 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js @@ -17,10 +17,10 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var userName = request.getParameter("username"); var user = userModule.getUser(userName)["content"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (user) { var title; if (user.firstname || user.lastname) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js index 8b41bc8a36..4528f4cba4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js @@ -17,10 +17,9 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var username = request.getParameter("username"); var user = userModule.getUser(username)["content"]; - var userModule = require("/app/modules/user.js")["userModule"]; var userName = request.getParameter("username"); @@ -38,7 +37,7 @@ function onRequest(context) { if (response["status"] == "success") { userRoles = response["content"]; } - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; devices = deviceModule.getDevices(userName); } return {"user": user, "userRoles": userRoles, "devices": devices}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js index b2db97ca66..abd9c2da6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js @@ -1,54 +1,37 @@ /* - * Copyright (c) 2015, 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the + * "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. */ -var deviceMgtAPIsBasePath = "/api/device-mgt/v1.0"; - -/** - * Checks if provided input is valid against RegEx input. - * - * @param regExp Regular expression - * @param inputString Input string to check - * @returns {boolean} Returns true if input matches RegEx - */ -function inputIsValid(regExp, inputString) { - regExp = new RegExp(regExp); - return regExp.test(inputString); -} - -/** - * Sorting function of users - * listed on User Management page in WSO2 Devicemgt Console. - */ $(function () { var sortableElem = '.wr-sortable'; $(sortableElem).sortable({ beforeStop: function () { - $(this).sortable('toArray'); + var sortedIDs = $(this).sortable('toArray'); } }); $(sortableElem).disableSelection(); }); +var apiBasePath = "/api/device-mgt/v1.0"; var modalPopup = ".wr-modalpopup"; var modalPopupContainer = modalPopup + " .modalpopup-container"; var modalPopupContent = modalPopup + " .modalpopup-content"; var body = "body"; -//var isInit = true; +var isInit = true; $(".icon .text").res_text(0.2); /* @@ -90,11 +73,11 @@ function getSelectedUsernames() { /** * Following click function would execute * when a user clicks on "Invite" link - * on User Management page in WSO2 Devicemgt Console. + * on User Management page in WSO2 MDM Console. */ $("a.invite-user-link").click(function () { var usernameList = getSelectedUsernames(); - var inviteUserAPI = deviceMgtAPIsBasePath + "/users/send-invitation"; + var inviteUserAPI = apiBasePath + "/users/send-invitation"; if (usernameList.length == 0) { $(modalPopupContent).html($("#errorUsers").html()); @@ -108,18 +91,13 @@ $("a.invite-user-link").click(function () { invokerUtil.post( inviteUserAPI, usernameList, - // success callback - function (data, textStatus, jqXHR) { - if (jqXHR.status == 200) { - $(modalPopupContent).html($('#invite-user-success-content').html()); - $("a#invite-user-success-link").click(function () { - hidePopup(); - }); - } + function () { + $(modalPopupContent).html($('#invite-user-success-content').html()); + $("a#invite-user-success-link").click(function () { + hidePopup(); + }); }, - // error callback - function (jqXHR) { - console.log("error in invite-user API, status code: " + jqXHR.status); + function () { $(modalPopupContent).html($('#invite-user-error-content').html()); $("a#invite-user-error-link").click(function () { hidePopup(); @@ -136,30 +114,31 @@ $("a.invite-user-link").click(function () { /** * Following click function would execute * when a user clicks on "Remove" link - * on User Listing page in WSO2 Devicemgt Console. + * on User Listing page in WSO2 MDM Console. */ -function removeUser(username) { - var removeUserAPI = deviceMgtAPIsBasePath + "/users/" + username; +function removeUser(uname, uid) { + var username = uname; + var userid = uid; + var removeUserAPI = apiBasePath + "/users/" + username; $(modalPopupContent).html($('#remove-user-modal-content').html()); showPopup(); $("a#remove-user-yes-link").click(function () { invokerUtil.delete( removeUserAPI, - // success callback - function (data, textStatus, jqXHR) { - if (jqXHR.status == 200) { - // update modal-content with success message - $(modalPopupContent).html($('#remove-user-success-content').html()); - $("a#remove-user-success-link").click(function () { - hidePopup(); - location.reload(); - }); - } + function () { + $("#" + userid).remove(); + // get new user-list-count + var newUserListCount = $(".user-list > span").length; + // update user-listing-status-msg with new user-count + $("#user-listing-status-msg").text("Total number of Users found : " + newUserListCount); + // update modal-content with success message + $(modalPopupContent).html($('#remove-user-success-content').html()); + $("a#remove-user-success-link").click(function () { + hidePopup(); + }); }, - // error callback - function (jqXHR) { - console.log("error in remove-user API, status code: " + jqXHR.status); + function () { $(modalPopupContent).html($('#remove-user-error-content').html()); $("a#remove-user-error-link").click(function () { hidePopup(); @@ -207,23 +186,19 @@ function resetPassword(uname) { //resetPasswordFormData.username = user; resetPasswordFormData.newPassword = unescape(confirmedPassword); - var resetPasswordServiceURL = deviceMgtAPIsBasePath + "/admin/users/"+ user +"/credentials"; + var resetPasswordServiceURL = apiBasePath + "/admin/users/"+ user +"/credentials"; invokerUtil.post( resetPasswordServiceURL, resetPasswordFormData, - // success callback - function (data, textStatus, jqXHR) { + function (data, textStatus, jqXHR) { // The success callback if (jqXHR.status == 200) { $(modalPopupContent).html($('#reset-password-success-content').html()); $("a#reset-password-success-link").click(function () { hidePopup(); }); } - }, - // error callback - function (jqXHR) { - console.log("error in reset-password API, status code: " + jqXHR.status); + }, function (jqXHR) { // The error callback var payload = JSON.parse(jqXHR.responseText); $(errorMsg).text(payload.message); $(errorMsgWrapper).removeClass("hidden"); @@ -253,7 +228,7 @@ $("#search-btn").click(function () { * when a user clicks on the list item * initial mode and with out select mode. */ -function initiateViewOption() { +function InitiateViewOption() { if ($("#can-view").val()) { $(location).attr('href', $(this).data("url")); } else { @@ -262,137 +237,172 @@ function initiateViewOption() { } } -function loadUsers() { - var loadingContentIcon = "#loading-content"; - $(loadingContentIcon).show(); +function loadUsers(searchParam) { - var dataFilter = function (data) { + + $("#loading-content").show(); + + + var dataFilter = function(data){ data = JSON.parse(data); var objects = []; - $(data.users).each( - function (index) { - objects.push( - { - username: data.users[index].username, - firstname: data.users[index].firstname ? data.users[index].firstname: '' , - lastname: data.users[index].lastname ? data.users[index].lastname : '', - emailAddress : data.users[index].emailAddress ? data.users[index].emailAddress: '', - DT_RowId : "user-" + data.users[index].username - } - ) - } - ); + $(data.users).each(function( index ) { + objects.push({ + filter: data.users[index].username, + firstname: data.users[index].firstname ? data.users[index].firstname: '' , + lastname: data.users[index].lastname ? data.users[index].lastname : '', + emailAddress : data.users[index].emailAddress ? data.users[index].emailAddress: '', + DT_RowId : "role-" + data.users[index].username}) + }); - var json = { + json = { "recordsTotal": data.count, "recordsFiltered": data.count, "data": objects }; - return JSON.stringify(json); - }; + return JSON.stringify( json ); + } - var fnCreatedRow = function(nRow, aData, iDataIndex) { - console.log(JSON.stringify(aData)); + var fnCreatedRow = function( nRow, aData, iDataIndex ) { $(nRow).attr('data-type', 'selectable'); $(nRow).attr('data-username', aData["username"]); - }; + } var columns = [ { class: "remove-padding icon-only content-fill", data: null, - defaultContent: - '
    ' + - '' + - '
    ' + defaultContent: '
    ' }, { class: "fade-edge", data: null, - render: function (data, type, row, meta) { + render: function ( data, type, row, meta ) { return '

    ' + data.firstname + ' ' + data.lastname + '

    '; } }, { class: "fade-edge remove-padding-top", - data: null, - render: function (data, type, row, meta) { - return ' ' + data.username; + data: 'filter', + render: function ( filter, type, row, meta ) { + return ' ' + filter; } }, { class: "fade-edge remove-padding-top", data: null, - render: function (data, type, row, meta) { - return ' ' + - data.emailAddress + ' '; + render: function ( data, type, row, meta ) { + return ' ' + data.emailAddress + ' '; } }, { class: "text-right content-fill text-left-on-grid-view no-wrap", data: null, - render: function (data, type, row, meta) { - return '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - ' ' + - '' + - ' ' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - '' + - ' ' + - '' + render: function ( data, type, row, meta ) { + return ' ' + + ' ' + + ' ' + + + '' + + ' ' + + ' ' + + + ' ' + + ' <' + + '/i> ' + + ' ' } } ]; - $("#user-grid").datatables_extended_serverside_paging( - null, '/api/device-mgt/v1.0/users', dataFilter, columns, fnCreatedRow, null - ); + + var options = { + "placeholder": "Search By Username", + "searchKey" : "filter" + }; + + + $('#user-grid').datatables_extended_serverside_paging(null, '/api/device-mgt/v1.0/users', dataFilter, columns, fnCreatedRow, null, options); $("#loading-content").hide(); + + + + // $("#loading-content").show(); + // var userListing = $("#user-listing"); + // var userListingSrc = userListing.attr("src"); + // $.template("user-listing", userListingSrc, function (template) { + // var serviceURL = apiBasePath + "/users"; + // if (searchParam) { + // serviceURL = serviceURL + "?filter=" + searchParam; + // } + // var successCallback = function (data) { + // if (!data) { + // $('#ast-container').addClass('hidden'); + // $('#user-listing-status-msg').text('No users are available to be displayed.'); + // return; + // } + // var canRemove = $("#can-remove").val(); + // var canEdit = $("#can-edit").val(); + // var canResetPassword = $("#can-reset-password").val(); + // data = JSON.parse(data); + // var viewModel = {}; + // viewModel.users = data.users; + // for (var i = 0; i < viewModel.users.length; i++) { + // viewModel.users[i].userid = viewModel.users[i].username.replace(/[^\w\s]/gi, ''); + // if (canRemove) { + // viewModel.users[i].canRemove = true; + // } + // if (canEdit) { + // viewModel.users[i].canEdit = true; + // } + // if (canResetPassword) { + // viewModel.users[i].canResetPassword = true; + // } + // viewModel.users[i].adminUser = $("#user-table").data("user"); + // } + // if (data.count > 0) { + // $('#ast-container').removeClass('hidden'); + // $('#user-listing-status-msg').text(""); + // var content = template(viewModel); + // $("#ast-container").html(content); + // } else { + // $('#ast-container').addClass('hidden'); + // $('#user-listing-status-msg').text('No users are available to be displayed.'); + // } + // $("#loading-content").hide(); + // if (isInit) { + // $('#user-grid').datatables_extended(); + // isInit = false; + // } + // $(".icon .text").res_text(0.2); + // }; + // invokerUtil.get(serviceURL, + // successCallback, + // function (message) { + // $('#ast-container').addClass('hidden'); + // $('#user-listing-status-msg'). + // text('Invalid search query. Try again with a valid search query'); + // } + // ); + // }); } $(document).ready(function () { loadUsers(); $(".viewEnabledIcon").click(function () { - initiateViewOption(); + InitiateViewOption(); }); - if (!$("#can-invite").val()) { $("#invite-user-button").remove(); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.hbs index 560f597bbe..ae90987ece 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.hbs @@ -81,31 +81,58 @@
    - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    - - - - - - - - - + -
    +
    By Username
    - - - - -
    • @@ -124,7 +151,7 @@
    diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js index 98ddb20716..dab14ec3a4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js @@ -28,8 +28,8 @@ function onRequest(context) { }); var page = {}; - var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; page["adminUser"] = deviceMgtProps["adminUser"]; page["permissions"] = userModule.getUIPermissions(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js index 1ac4db312d..8b6c1e3b71 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js @@ -29,33 +29,41 @@ * For ex: $(this) means jQuery(this) and S.fn.x means jQuery.fn.x */ - $.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter, - columns, fnCreatedRow, fnDrawCallback) { +$.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter, + columns, fnCreatedRow, fnDrawCallback, options) { var elem = $(this); // EMM related function - if (initiateViewOption) { - $(".viewEnabledIcon").bind("click", initiateViewOption); + if (InitiateViewOption) { + $(".viewEnabledIcon").bind("click", InitiateViewOption); } //--- End of EMM related codes $(elem).DataTable( $.extend({},{ serverSide: true, + processing: false, + searching: true, + ordering: false, + filter: false, bSortCellsTop: true, ajax : { url: "/emm/api/data-tables/invoker", data : function (params) { - var filter = ""; var i; + var searchParams = {}; for (i = 0; i < params.columns.length; i++) { - // console.log(i); - filter += "&" + params.columns[i].data + "=" + params.columns[i].search.value; + searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value); } - // console.log(filter); + if(options) { + searchParams[options.searchKey] = encodeURIComponent(params.search.value); + } + params.filter = JSON.stringify(searchParams); params.offset = params.start; params.limit = params.length; - params.filter = filter; + // if(params.search.value){ + // params.filter = params.search.value; + // } params.url = url; }, dataFilter: dataFilter @@ -64,15 +72,15 @@ responsive: false, autoWidth: false, dom:'<"dataTablesTop"' + - 'f' + - '<"dataTables_toolbar">' + - '>' + - 'rt' + - '<"dataTablesBottom"' + - 'lip' + - '>', + 'f' + + '<"dataTables_toolbar">' + + '>' + + 'rt' + + '<"dataTablesBottom"' + + 'lip' + + '>', language: { - searchPlaceholder: 'Search by Role name', + searchPlaceholder: options.placeholder, search: '' }, fnCreatedRow: fnCreatedRow, @@ -216,7 +224,7 @@ $(button).addClass("active").html('Select'); $(button).parent().next().children().addClass("disabled"); // EMM related function - $(".viewEnabledIcon").bind("click", initiateViewOption); + $(".viewEnabledIcon").bind("click", InitiateViewOption); //--- End of EMM related codes } }); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.operation-mod/public/js/operation-mod.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.operation-mod/public/js/operation-mod.js index 8c115f0a97..3f1219765d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.operation-mod/public/js/operation-mod.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.operation-mod/public/js/operation-mod.js @@ -1,17 +1,17 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, 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 + * 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 + * "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. */ @@ -37,12 +37,50 @@ var operationModule = function () { // Constants to define Android Operation Constants var androidOperationConstants = { "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "VPN_OPERATION_CODE": "VPN", "CAMERA_OPERATION_CODE": "CAMERA", "ENCRYPT_STORAGE_OPERATION_CODE": "ENCRYPT_STORAGE", "WIFI_OPERATION_CODE": "WIFI", "WIPE_OPERATION_CODE": "WIPE_DATA", "NOTIFICATION_OPERATION_CODE": "NOTIFICATION", - "CHANGE_LOCK_CODE_OPERATION_CODE": "CHANGE_LOCK_CODE" + "WORK_PROFILE_CODE": "WORK_PROFILE", + "CHANGE_LOCK_CODE_OPERATION_CODE": "CHANGE_LOCK_CODE", + "LOCK_OPERATION_CODE": "DEVICE_LOCK", + "UPGRADE_FIRMWARE": "UPGRADE_FIRMWARE", + "DISALLOW_ADJUST_VOLUME": "DISALLOW_ADJUST_VOLUME", + "DISALLOW_CONFIG_BLUETOOTH" : "DISALLOW_CONFIG_BLUETOOTH", + "DISALLOW_CONFIG_CELL_BROADCASTS" : "DISALLOW_CONFIG_CELL_BROADCASTS", + "DISALLOW_CONFIG_CREDENTIALS" : "DISALLOW_CONFIG_CREDENTIALS", + "DISALLOW_CONFIG_MOBILE_NETWORKS" : "DISALLOW_CONFIG_MOBILE_NETWORKS", + "DISALLOW_CONFIG_TETHERING" : "DISALLOW_CONFIG_TETHERING", + "DISALLOW_CONFIG_VPN" : "DISALLOW_CONFIG_VPN", + "DISALLOW_CONFIG_WIFI" : "DISALLOW_CONFIG_WIFI", + "DISALLOW_APPS_CONTROL" : "DISALLOW_APPS_CONTROL", + "DISALLOW_CREATE_WINDOWS" : "DISALLOW_CREATE_WINDOWS", + "DISALLOW_CROSS_PROFILE_COPY_PASTE" : "DISALLOW_CROSS_PROFILE_COPY_PASTE", + "DISALLOW_DEBUGGING_FEATURES" : "DISALLOW_DEBUGGING_FEATURES", + "DISALLOW_FACTORY_RESET" : "DISALLOW_FACTORY_RESET", + "DISALLOW_ADD_USER" : "DISALLOW_ADD_USER", + "DISALLOW_INSTALL_APPS" : "DISALLOW_INSTALL_APPS", + "DISALLOW_INSTALL_UNKNOWN_SOURCES" : "DISALLOW_INSTALL_UNKNOWN_SOURCES", + "DISALLOW_MODIFY_ACCOUNTS" : "DISALLOW_MODIFY_ACCOUNTS", + "DISALLOW_MOUNT_PHYSICAL_MEDIA" : "DISALLOW_MOUNT_PHYSICAL_MEDIA", + "DISALLOW_NETWORK_RESET" : "DISALLOW_NETWORK_RESET", + "DISALLOW_OUTGOING_BEAM" : "DISALLOW_OUTGOING_BEAM", + "DISALLOW_OUTGOING_CALLS" : "DISALLOW_OUTGOING_CALLS", + "DISALLOW_REMOVE_USER" : "DISALLOW_REMOVE_USER", + "DISALLOW_SAFE_BOOT" : "DISALLOW_SAFE_BOOT", + "DISALLOW_SHARE_LOCATION" : "DISALLOW_SHARE_LOCATION", + "DISALLOW_SMS" : "DISALLOW_SMS", + "DISALLOW_UNINSTALL_APPS" : "DISALLOW_UNINSTALL_APPS", + "DISALLOW_UNMUTE_MICROPHONE" : "DISALLOW_UNMUTE_MICROPHONE", + "DISALLOW_USB_FILE_TRANSFER" : "DISALLOW_USB_FILE_TRANSFER", + "ALLOW_PARENT_PROFILE_APP_LINKING" : "ALLOW_PARENT_PROFILE_APP_LINKING", + "ENSURE_VERIFY_APPS" : "ENSURE_VERIFY_APPS", + "AUTO_TIME" : "AUTO_TIME", + "SET_SCREEN_CAPTURE_DISABLED" : "SET_SCREEN_CAPTURE_DISABLED", + "SET_STATUS_BAR_DISABLED" : "SET_STATUS_BAR_DISABLED", + "APPLICATION_OPERATION_CODE":"APP-RESTRICTION" }; // Constants to define Windows Operation Constants @@ -58,6 +96,7 @@ var operationModule = function () { var iosOperationConstants = { "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", "RESTRICTIONS_OPERATION_CODE": "RESTRICTION", + "VPN_OPERATION_CODE": "VPN", "WIFI_OPERATION_CODE": "WIFI", "EMAIL_OPERATION_CODE": "EMAIL", "AIRPLAY_OPERATION_CODE": "AIR_PLAY", @@ -66,12 +105,18 @@ var operationModule = function () { "NOTIFICATION_OPERATION_CODE": "NOTIFICATION", "CALENDAR_SUBSCRIPTION_OPERATION_CODE": "CALENDAR_SUBSCRIPTION", "APN_OPERATION_CODE": "APN", - "CELLULAR_OPERATION_CODE": "CELLULAR" + "DOMAIN_CODE": "DOMAIN", + "CELLULAR_OPERATION_CODE": "CELLULAR", + "PER_APP_VPN_OPERATION_CODE": "PER_APP_VPN", + "APP_TO_PER_APP_VPN_MAPPING_OPERATION_CODE": "APP_TO_PER_APP_VPN_MAPPING" }; publicMethods.getIOSServiceEndpoint = function (operationCode) { var featureMap = { "DEVICE_LOCK": "lock", + "VPN": "vpn", + "PER_APP_VPN": "perappvpn", + "APP_TO_PER_APP_VPN_MAPPING": "apptoperappvpnmapping", "RING": "ring", "LOCATION": "location", "NOTIFICATION": "notification", @@ -182,6 +227,76 @@ var operationModule = function () { "restrictionsAutonomousSingleAppModePermittedAppIDs": operationPayload["autonomousSingleAppModePermittedAppIDs"] }; break; + case iosOperationConstants["VPN_OPERATION_CODE"]: + var pptp = false; + var l2tp = false; + if (operationPayload["vpnType"] == "PPTP") { + pptp = true; + } else if (operationPayload["vpnType"] == "L2TP") { + l2tp = true; + } + + payload = { + "userDefinedName": operationPayload["userDefinedName"], + "overridePrimary": operationPayload["overridePrimary"], + "onDemandEnabled": operationPayload["onDemandEnabled"], + "onDemandMatchDomainsAlways": operationPayload["onDemandMatchDomainsAlways"], + "onDemandMatchDomainsNever": operationPayload["onDemandMatchDomainsNever"], + "onDemandMatchDomainsOnRetry": operationPayload["onDemandMatchDomainsOnRetry"], + "onDemandRules": operationPayload["onDemandRules"], + "vendorConfigs": operationPayload["vendorConfigs"], + "vpnType": operationPayload["vpnType"], + "pptpAuthName": pptp ? operationPayload.ppp["authName"] : "", + "pptpTokenCard": pptp ? operationPayload.ppp["tokenCard"] : "", + "pptpAuthPassword": pptp ? operationPayload.ppp["authPassword"] : "", + "pptpCommRemoteAddress": pptp ? operationPayload.ppp["commRemoteAddress"] : "", + "pptpRSASecureID": pptp ? operationPayload.ppp["RSASecureID"] : "", + "pptpCCPEnabled": pptp ? operationPayload.ppp["CCPEnabled"] : "", + "pptpCCPMPPE40Enabled": pptp ? operationPayload.ppp["CCPMPPE40Enabled"] : "", + "pptpCCPMPPE128Enabled": pptp ? operationPayload.ppp["CCPMPPE128Enabled"] : "", + "l2tpAuthName": l2tp ? operationPayload.ppp["authName"] : "", + "l2tpTokenCard": l2tp ? operationPayload.ppp["tokenCard"] : "", + "l2tpAuthPassword": l2tp ? operationPayload.ppp["authPassword"] : "", + "l2tpCommRemoteAddress": l2tp ? operationPayload.ppp["commRemoteAddress"] : "", + "l2tpRSASecureID": l2tp ? operationPayload.ppp["RSASecureID"] : "", + "ipsecRemoteAddress": operationPayload.ipSec["remoteAddress"], + "ipsecAuthenticationMethod": operationPayload.ipSec["authenticationMethod"], + "ipsecLocalIdentifier": operationPayload.ipSec["localIdentifier"], + "ipsecSharedSecret": operationPayload.ipSec["sharedSecret"], + "ipsecPayloadCertificateUUID": operationPayload.ipSec["payloadCertificateUUID"], + "ipsecXAuthEnabled": operationPayload.ipSec["XAuthEnabled"], + "ipsecXAuthName": operationPayload.ipSec["XAuthName"], + "ipsecPromptForVPNPIN": operationPayload.ipSec["promptForVPNPIN"], + "ikev2RemoteAddress": operationPayload.ikEv2["remoteAddress"], + "ikev2LocalIdentifier": operationPayload.ikEv2["localIdentifier"], + "ikev2RemoteIdentifier": operationPayload.ikEv2["remoteIdentifier"], + "ikev2AuthenticationMethod": operationPayload.ikEv2["authenticationMethod"], + "ikev2SharedSecret": operationPayload.ikEv2["sharedSecret"], + "ikev2PayloadCertificateUUID": operationPayload.ikEv2["payloadCertificateUUID"], + "ikev2ExtendedAuthEnabled": operationPayload.ikEv2["extendedAuthEnabled"], + "ikev2AuthName": operationPayload.ikEv2["authName"], + "ikev2AuthPassword": operationPayload.ikEv2["authPassword"], + "ikev2DeadPeerDetectionInterval": operationPayload.ikEv2["deadPeerDetectionInterval"], + "ikev2ServerCertificateIssuerCommonName": operationPayload.ikEv2["serverCertificateIssuerCommonName"], + "ikev2ServerCertificateCommonName": operationPayload.ikEv2["serverCertificateCommonName"] + }; + break; + case iosOperationConstants["PER_APP_VPN_OPERATION_CODE"]: + payload = { + "operation": { + "VPNUUID": operationPayload["PER-APP-VPNUUID"], + "safariDomains": operationPayload["safariDomains"], + "onDemandMatchAppEnabled": operationPayload["onDemandMatchAppEnabled"] + } + }; + break; + case iosOperationConstants["APP_TO_PER_APP_VPN_MAPPING_OPERATION_CODE"]: + payload = { + "operation": { + "appLayerVPNMappings": operationPayload["appLayerVPNMappings"] + } + }; + break; case iosOperationConstants["WIFI_OPERATION_CODE"]: payload = { "wifiHiddenNetwork": operationPayload["hiddenNetwork"], @@ -367,6 +482,112 @@ var operationModule = function () { } }; break; + case iosOperationConstants["VPN_OPERATION_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + var ppp = {}; + var ipSec = {}; + var ikev2 = {}; + if (operationData["vpnType"] == "PPTP") { + ppp = { + "authName": operationData["pptpAuthName"], + "tokenCard": operationData["pptpTokenCard"], + "authPassword": operationData["pptpAuthPassword"], + "commRemoteAddress": operationData["pptpCommRemoteAddress"], + "RSASecureID": operationData["pptpRSASecureID"], + "CCPEnabled": operationData["pptpCCPEnabled"], + "CCPMPPE40Enabled": operationData["pptpCCPMPPE40Enabled"], + "CCPMPPE128Enabled": operationData["pptpCCPMPPE128Enabled"] + }; + } else if (operationData["vpnType"] == "L2TP") { + ppp = { + "authName": operationData["l2tpAuthName"], + "tokenCard": operationData["l2tpTokenCard"], + "authPassword": operationData["l2tpAuthPassword"], + "commRemoteAddress": operationData["l2tpCommRemoteAddress"], + "RSASecureID": operationData["l2tpRSASecureID"] + }; + } else if (operationData["vpnType"] == "IPSec") { + ipSec = { + "remoteAddress" : operationData["ipsecRemoteAddress"], + "authenticationMethod" : operationData["ipsecAuthenticationMethod"], + "localIdentifier" : operationData["ipsecLocalIdentifier"], + "sharedSecret" : operationData["ipsecSharedSecret"], + "payloadCertificateUUID" : operationData["ipsecPayloadCertificateUUID"], + "XAuthEnabled" : operationData["ipsecXAuthEnabled"], + "XAuthName" : operationData["ipsecXAuthName"], + "promptForVPNPIN" : operationData["ipsecPromptForVPNPIN"] + }; + } else if (operationData["vpnType"] == "IKEv2") { + ikev2 = { + "remoteAddress" : operationData["ikev2RemoteAddress"], + "localIdentifier" : operationData["ikev2LocalIdentifier"], + "remoteIdentifier" : operationData["ikev2RemoteIdentifier"], + "authenticationMethod" : operationData["ikev2AuthenticationMethod"], + "sharedSecret" : operationData["ikev2SharedSecret"], + "payloadCertificateUUID" : operationData["ikev2PayloadCertificateUUID"], + "extendedAuthEnabled" : operationData["ikev2ExtendedAuthEnabled"], + "authName" : operationData["ikev2AuthName"], + "authPassword" : operationData["ikev2AuthPassword"], + "deadPeerDetectionInterval" : operationData["ikev2DeadPeerDetectionInterval"], + "serverCertificateIssuerCommonName" : operationData["ikev2ServerCertificateIssuerCommonName"], + "serverCertificateCommonName" : operationData["ikev2ServerCertificateCommonName"] + }; + } + + var domainsAlways = new Array(); + for (var i = 0; i < operationData["onDemandMatchDomainsAlways"].length; i++) { + domainsAlways.push(operationData["onDemandMatchDomainsAlways"][i].domain); + } + + var domainsNever = new Array(); + for (var i = 0; i < operationData["onDemandMatchDomainsNever"].length; i++) { + domainsNever.push(operationData["onDemandMatchDomainsNever"][i].domain); + } + + var domainsRetry = new Array(); + for (var i = 0; i < operationData["onDemandMatchDomainsOnRetry"].length; i++) { + domainsRetry.push(operationData["onDemandMatchDomainsOnRetry"][i].domain); + } + + payload = { + "operation": { + "userDefinedName": operationData["userDefinedName"], + "overridePrimary": operationData["overridePrimary"], + "onDemandEnabled": operationData["onDemandEnabled"], + "onDemandMatchDomainsAlways": domainsAlways, + "onDemandMatchDomainsNever": domainsNever, + "onDemandMatchDomainsOnRetry": domainsRetry, + "onDemandRules" : operationData["onDemandRules"], + "vendorConfigs" : operationData["vendorConfigs"], + "vpnType" : operationData["vpnType"], + "ppp": ppp, + "ipSec": ipSec, + "ikEv2": ikev2 + } + }; + break; + case iosOperationConstants["PER_APP_VPN_OPERATION_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + var domains = new Array(); + for (var i = 0; i < operationData["safariDomains"].length; i++) { + domains.push(operationData["safariDomains"][i].domain); + } + payload = { + "operation": { + "VPNUUID": operationData["VPNUUID"], + "safariDomains": domains, + "onDemandMatchAppEnabled": operationData["onDemandMatchAppEnabled"] + } + }; + break; + case iosOperationConstants["APP_TO_PER_APP_VPN_MAPPING_OPERATION_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "appLayerVPNMappings": operationData["appLayerVPNMappings"] + } + }; + break; case iosOperationConstants["RESTRICTIONS_OPERATION_CODE"]: operationType = operationTypeConstants["PROFILE"]; payload = { @@ -528,6 +749,15 @@ var operationModule = function () { } }; break; + case iosOperationConstants["DOMAIN_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "emailDomains": operationData["emailDomains"], + "webDomains": operationData["webDomains"] + } + }; + break; case iosOperationConstants["CELLULAR_OPERATION_CODE"]: operationType = operationTypeConstants["PROFILE"]; payload = { @@ -584,9 +814,7 @@ var operationModule = function () { }; break; case androidOperationConstants["CAMERA_OPERATION_CODE"]: - payload = { - "cameraEnabled": operationPayload["enabled"] - }; + payload = operationPayload; break; case androidOperationConstants["ENCRYPT_STORAGE_OPERATION_CODE"]: payload = { @@ -596,7 +824,29 @@ var operationModule = function () { case androidOperationConstants["WIFI_OPERATION_CODE"]: payload = { "wifiSSID": operationPayload["ssid"], - "wifiPassword": operationPayload["password"] + "wifiPassword": operationPayload["password"], + "wifiType": operationPayload["type"], + "wifiEAP": operationPayload["eap"], + "wifiPhase2": operationPayload["phase2"], + "wifiProvisioning": operationPayload["provisioning"], + "wifiIdentity": operationPayload["identity"], + "wifiAnoIdentity": operationPayload["anonymousIdentity"], + "wifiCaCert" : operationPayload["cacert"], + "wifiCaCertName" : operationPayload["cacertName"] + }; + break; + case androidOperationConstants["VPN_OPERATION_CODE"]: + payload = { + "serverAddress": operationPayload["serverAddress"], + "serverPort": operationPayload["serverPort"], + "sharedSecret": operationPayload["sharedSecret"], + "dnsServer": operationPayload["dnsServer"] + }; + break; + case androidOperationConstants["APPLICATION_OPERATION_CODE"]: + payload = { + "restrictionType": operationPayload["restriction-type"], + "restrictedApplications": operationPayload["restricted-applications"] }; break; } @@ -611,7 +861,40 @@ var operationModule = function () { operationType = operationTypeConstants["PROFILE"]; payload = { "operation": { - "enabled" : operationData["cameraEnabled"] + "CAMERA" : operationData["cameraEnabled"], + "DISALLOW_ADJUST_VOLUME" : operationData["disallowAdjustVolumeEnabled"], + "DISALLOW_CONFIG_BLUETOOTH" : operationData["disallowConfigBluetooth"], + "DISALLOW_CONFIG_CELL_BROADCASTS" : operationData["disallowConfigCellBroadcasts"], + "DISALLOW_CONFIG_CREDENTIALS" : operationData["disallowConfigCredentials"], + "DISALLOW_CONFIG_MOBILE_NETWORKS" : operationData["disallowConfigMobileNetworks"], + "DISALLOW_CONFIG_TETHERING" : operationData["disallowConfigTethering"], + "DISALLOW_CONFIG_VPN" : operationData["disallowConfigVpn"], + "DISALLOW_CONFIG_WIFI" : operationData["disallowConfigWifi"], + "DISALLOW_APPS_CONTROL" : operationData["disallowAppControl"], + "DISALLOW_CREATE_WINDOWS" : operationData["disallowCreateWindows"], + "DISALLOW_CROSS_PROFILE_COPY_PASTE" : operationData["disallowCrossProfileCopyPaste"], + "DISALLOW_DEBUGGING_FEATURES" : operationData["disallowDebugging"], + "DISALLOW_FACTORY_RESET" : operationData["disallowFactoryReset"], + "DISALLOW_ADD_USER" : operationData["disallowAddUser"], + "DISALLOW_INSTALL_APPS" : operationData["disallowInstallApps"], + "DISALLOW_INSTALL_UNKNOWN_SOURCES" : operationData["disallowInstallUnknownSources"], + "DISALLOW_MODIFY_ACCOUNTS" : operationData["disallowModifyAccounts"], + "DISALLOW_MOUNT_PHYSICAL_MEDIA" : operationData["disallowMountPhysicalMedia"], + "DISALLOW_NETWORK_RESET" : operationData["disallowNetworkReset"], + "DISALLOW_OUTGOING_BEAM" : operationData["disallowOutgoingBeam"], + "DISALLOW_OUTGOING_CALLS" : operationData["disallowOutgoingCalls"], + "DISALLOW_REMOVE_USER" : operationData["disallowRemoveUser"], + "DISALLOW_SAFE_BOOT" : operationData["disallowSafeBoot"], + "DISALLOW_SHARE_LOCATION" : operationData["disallowLocationSharing"], + "DISALLOW_SMS" : operationData["disallowSMS"], + "DISALLOW_UNINSTALL_APPS" : operationData["disallowUninstallApps"], + "DISALLOW_UNMUTE_MICROPHONE" : operationData["disallowUnmuteMicrophone"], + "DISALLOW_USB_FILE_TRANSFER" : operationData["disallowUSBFileTransfer"], + "ALLOW_PARENT_PROFILE_APP_LINKING" : operationData["disallowParentProfileAppLinking"], + "ENSURE_VERIFY_APPS" : operationData["ensureVerifyApps"], + "AUTO_TIME" : operationData["enableAutoTime"], + "SET_SCREEN_CAPTURE_DISABLED" : operationData["diableScreenCapture"], + "SET_STATUS_BAR_DISABLED" : operationData["disableStatusBar"] } }; break; @@ -635,7 +918,18 @@ var operationModule = function () { operationType = operationTypeConstants["PROFILE"]; payload = { "operation": { - "message" : operationData["message"] + //"message" : operationData["message"] + "messageText": operationData["messageText"], + "messageTitle": operationData["messageTitle"] + } + }; + break; + case androidOperationConstants["UPGRADE_FIRMWARE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "schedule" : operationData["schedule"], + "server" : operationData["server"] } }; break; @@ -652,7 +946,47 @@ var operationModule = function () { payload = { "operation": { "ssid": operationData["wifiSSID"], - "password": operationData["wifiPassword"] + "type": operationData["wifiType"], + "password" : operationData["wifiPassword"], + "eap" : operationData["wifiEAP"], + "phase2" : operationData["wifiPhase2"], + "provisioning" : operationData["wifiProvisioning"], + "identity" : operationData["wifiIdentity"], + "anonymousIdentity" : operationData["wifiAnoIdentity"], + "cacert" : operationData["wifiCaCert"], + "cacertName" : operationData["wifiCaCertName"] + } + }; + break; + case androidOperationConstants["VPN_OPERATION_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "serverAddress": operationData["serverAddress"], + "serverPort": operationData["serverPort"], + "sharedSecret": operationData["sharedSecret"], + "dnsServer": operationData["dnsServer"] + } + }; + break; + case androidOperationConstants["LOCK_OPERATION_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "message" : operationData["lock-message"], + "isHardLockEnabled" : operationData["hard-lock"] + } + }; + break; + case androidOperationConstants["WORK_PROFILE_CODE"]: + operationType = operationTypeConstants["PROFILE"]; + payload = { + "operation": { + "profileName": operationData["workProfilePolicyProfileName"], + "enableSystemApps": operationData["workProfilePolicyEnableSystemApps"], + "hideSystemApps": operationData["workProfilePolicyHideSystemApps"], + "unhideSystemApps": operationData["workProfilePolicyUnhideSystemApps"], + "enablePlaystoreApps": operationData["workProfilePolicyEnablePlaystoreApps"] } }; break; @@ -670,6 +1004,14 @@ var operationModule = function () { } }; break; + case androidOperationConstants["APPLICATION_OPERATION_CODE"]: + payload = { + "operation": { + "restriction-type": operationData["restrictionType"], + "restricted-applications": operationData["restrictedApplications"] + } + }; + break; default: // If the operation is neither of above, it is a command operation operationType = operationTypeConstants["COMMAND"]; @@ -686,28 +1028,31 @@ var operationModule = function () { publicMethods.getAndroidServiceEndpoint = function (operationCode) { var featureMap = { - "WIFI": "wifi", - "CAMERA": "camera", - "DEVICE_LOCK": "lock", + "WIFI": "configure-wifi", + "CAMERA": "control-camera", + "VPN": "configure-vpn", + "DEVICE_LOCK": "lock-devices", + "DEVICE_UNLOCK": "unlock-devices", "DEVICE_LOCATION": "location", "CLEAR_PASSWORD": "clear-password", "APPLICATION_LIST": "get-application-list", - "DEVICE_RING": "ring-device", - "DEVICE_REBOOT": "reboot-device", + "DEVICE_RING": "ring", + "DEVICE_REBOOT": "reboot", "UPGRADE_FIRMWARE": "upgrade-firmware", "DEVICE_MUTE": "mute", - "NOTIFICATION": "notification", - "ENCRYPT_STORAGE": "encrypt", + "NOTIFICATION": "send-notification", + "ENCRYPT_STORAGE": "encrypt-storage", "CHANGE_LOCK_CODE": "change-lock-code", - "WEBCLIP": "webclip", + "WEBCLIP": "set-webclip", "INSTALL_APPLICATION": "install-application", "UNINSTALL_APPLICATION": "uninstall-application", "BLACKLIST_APPLICATIONS": "blacklist-applications", - "PASSCODE_POLICY": "password-policy", + "PASSCODE_POLICY": "set-password-policy", "ENTERPRISE_WIPE": "enterprise-wipe", - "WIPE_DATA": "wipe-data" + "WIPE_DATA": "wipe" }; - return "/mdm-android-agent/operation/" + featureMap[operationCode]; + //return "/mdm-android-agent/operation/" + featureMap[operationCode]; + return "/api/device-mgt/android/v1.0/admin/devices/" + featureMap[operationCode]; }; /** @@ -852,9 +1197,10 @@ var operationModule = function () { "DEVICE_RING": "fw-dial-up", "DEVICE_REBOOT": "fw-refresh", "UPGRADE_FIRMWARE": "fw-up-arrow", - "DEVICE_MUTE": "fw-incoming-call", + "DEVICE_MUTE": "fw-mute", "NOTIFICATION": "fw-message", - "CHANGE_LOCK_CODE": "fw-security" + "CHANGE_LOCK_CODE": "fw-security", + "DEVICE_UNLOCK": "fw-lock" }; return featureMap[operationCode]; }; @@ -926,7 +1272,7 @@ var operationModule = function () { var key = operationDataObj.data("key"); var value; if (operationDataObj.is(":text") || operationDataObj.is("textarea") || - operationDataObj.is(":password")) { + operationDataObj.is(":password") || operationDataObj.is(":hidden")) { value = operationDataObj.val(); } else if (operationDataObj.is(":checkbox")) { value = operationDataObj.is(":checked"); @@ -939,7 +1285,8 @@ var operationModule = function () { if (operationDataObj.hasClass("one-column-input-array")) { $(".child-input", this).each(function () { childInput = $(this); - if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password")) { + if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password") + || childInput.is(":hidden")) { childInputValue = childInput.val(); } else if (childInput.is(":checkbox")) { childInputValue = childInput.is(":checked"); @@ -965,7 +1312,8 @@ var operationModule = function () { var joinedInput; $(".child-input", this).each(function () { childInput = $(this); - if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password")) { + if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password") + || childInput.is(":hidden")) { childInputValue = childInput.val(); } else if (childInput.is(":checkbox")) { childInputValue = childInput.is(":checked"); @@ -996,7 +1344,8 @@ var operationModule = function () { $(".child-input", this).each(function () { childInput = $(this); childInputKey = childInput.data("child-key"); - if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password")) { + if (childInput.is(":text") || childInput.is("textarea") || childInput.is(":password") + || childInput.is(":hidden")) { childInputValue = childInput.val(); } else if (childInput.is(":checkbox")) { childInputValue = childInput.is(":checked"); @@ -1024,6 +1373,7 @@ var operationModule = function () { operationData[key] = value; } ); + switch (platformType) { case platformTypeConstants["ANDROID"]: payload = privateMethods.generateAndroidOperationPayload(operationCode, operationData, deviceList); @@ -1087,58 +1437,17 @@ var operationModule = function () { // var childInputValue; if (operationDataObj.hasClass("one-column-input-array")) { // generating input fields to populate complex value - for (i = 0; i < value.length; ++i) { - operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); - } - // traversing through each child input - $(".child-input", this).each(function () { - childInput = $(this); - var childInputValue = value[childInputIndex]; - // populating extracted value in the UI according to the input type - if (childInput.is(":text") || - childInput.is("textarea") || - childInput.is(":password") || - childInput.is("select")) { - childInput.val(childInputValue); - } else if (childInput.is(":checkbox")) { - operationDataObj.prop("checked", childInputValue); + if (value) { + for (i = 0; i < value.length; ++i) { + operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); } - // incrementing childInputIndex - childInputIndex++; - }); - } else if (operationDataObj.hasClass("valued-check-box-array")) { - // traversing through each child input - $(".child-input", this).each(function () { - childInput = $(this); - // check if corresponding value of current checkbox exists in the array of values - if (value.indexOf(childInput.data("value")) != -1) { - // if YES, set checkbox as checked - childInput.prop("checked", true); - } - }); - } else if (operationDataObj.hasClass("multi-column-joined-input-array")) { - // generating input fields to populate complex value - for (i = 0; i < value.length; ++i) { - operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); - } - var columnCount = operationDataObj.data("column-count"); - var multiColumnJoinedInputArrayIndex = 0; - // handling scenarios specifically - if (operationDataObj.attr("id") == "wifi-mcc-and-mncs") { // traversing through each child input $(".child-input", this).each(function () { childInput = $(this); - var multiColumnJoinedInput = value[multiColumnJoinedInputArrayIndex]; - var childInputValue; - if ((childInputIndex % columnCount) == 0) { - childInputValue = multiColumnJoinedInput.substring(3, 0) - } else { - childInputValue = multiColumnJoinedInput.substring(3); - // incrementing childInputIndex - multiColumnJoinedInputArrayIndex++; - } + var childInputValue = value[childInputIndex]; // populating extracted value in the UI according to the input type if (childInput.is(":text") || + childInput.is(":hidden") || childInput.is("textarea") || childInput.is(":password") || childInput.is("select")) { @@ -1150,35 +1459,87 @@ var operationModule = function () { childInputIndex++; }); } - } else if (operationDataObj.hasClass("multi-column-key-value-pair-array")) { - // generating input fields to populate complex value - for (i = 0; i < value.length; ++i) { - operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); - } - columnCount = operationDataObj.data("column-count"); - var multiColumnKeyValuePairArrayIndex = 0; + } else if (operationDataObj.hasClass("valued-check-box-array")) { // traversing through each child input $(".child-input", this).each(function () { childInput = $(this); - var multiColumnKeyValuePair = value[multiColumnKeyValuePairArrayIndex]; - var childInputKey = childInput.data("child-key"); - var childInputValue = multiColumnKeyValuePair[childInputKey]; - // populating extracted value in the UI according to the input type - if (childInput.is(":text") || - childInput.is("textarea") || - childInput.is(":password") || - childInput.is("select")) { - childInput.val(childInputValue); - } else if (childInput.is(":checkbox")) { - operationDataObj.prop("checked", childInputValue); + // check if corresponding value of current checkbox exists in the array of values + if (value) { + if (value.indexOf(childInput.data("value")) != -1) { + // if YES, set checkbox as checked + childInput.prop("checked", true); + } } - // incrementing multiColumnKeyValuePairArrayIndex for the next row of inputs - if ((childInputIndex % columnCount) == (columnCount - 1)) { - multiColumnKeyValuePairArrayIndex++; - } - // incrementing childInputIndex - childInputIndex++; }); + } else if (operationDataObj.hasClass("multi-column-joined-input-array")) { + // generating input fields to populate complex value + if (value) { + for (i = 0; i < value.length; ++i) { + operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); + } + var columnCount = operationDataObj.data("column-count"); + var multiColumnJoinedInputArrayIndex = 0; + // handling scenarios specifically + if (operationDataObj.attr("id") == "wifi-mcc-and-mncs") { + // traversing through each child input + $(".child-input", this).each(function () { + childInput = $(this); + var multiColumnJoinedInput = value[multiColumnJoinedInputArrayIndex]; + var childInputValue; + if ((childInputIndex % columnCount) == 0) { + childInputValue = multiColumnJoinedInput.substring(3, 0) + } else { + childInputValue = multiColumnJoinedInput.substring(3); + // incrementing childInputIndex + multiColumnJoinedInputArrayIndex++; + } + // populating extracted value in the UI according to the input type + if (childInput.is(":text") || + childInput.is(":hidden") || + childInput.is("textarea") || + childInput.is(":password") || + childInput.is("select")) { + childInput.val(childInputValue); + } else if (childInput.is(":checkbox")) { + operationDataObj.prop("checked", childInputValue); + } + // incrementing childInputIndex + childInputIndex++; + }); + } + } + } else if (operationDataObj.hasClass("multi-column-key-value-pair-array")) { + // generating input fields to populate complex value + if (value) { + for (i = 0; i < value.length; ++i) { + operationDataObj.parent().find("a").filterByData("click-event", "add-form").click(); + } + columnCount = operationDataObj.data("column-count"); + var multiColumnKeyValuePairArrayIndex = 0; + // traversing through each child input + $(".child-input", this).each(function () { + childInput = $(this); + var multiColumnKeyValuePair = value[multiColumnKeyValuePairArrayIndex]; + var childInputKey = childInput.data("child-key"); + var childInputValue = multiColumnKeyValuePair[childInputKey]; + // populating extracted value in the UI according to the input type + if (childInput.is(":text") || + childInput.is(":hidden") || + childInput.is("textarea") || + childInput.is(":password") || + childInput.is("select")) { + childInput.val(childInputValue); + } else if (childInput.is(":checkbox")) { + operationDataObj.prop("checked", childInputValue); + } + // incrementing multiColumnKeyValuePairArrayIndex for the next row of inputs + if ((childInputIndex % columnCount) == (columnCount - 1)) { + multiColumnKeyValuePairArrayIndex++; + } + // incrementing childInputIndex + childInputIndex++; + }); + } } } } @@ -1197,8 +1558,29 @@ var operationModule = function () { for (var i = 0; i < operationCodes.length; ++i) { var operationCode = operationCodes[i]; var payload = publicMethods.generatePayload(platformType, operationCode, null); - generatedProfile[operationCode] = payload["operation"]; + + if(platformType == platformTypeConstants["ANDROID"] && + operationCodes[i] == androidOperationConstants["CAMERA_OPERATION_CODE"]){ + var operations = payload["operation"]; + for (var key in operations){ + operationCode = key; + var restriction = false; + if(operations[key]){ + restriction = true; + } + var payloadResult = { + "operation": { + "enabled" : restriction + } + }; + generatedProfile[operationCode] = payloadResult["operation"]; + } + + } else { + generatedProfile[operationCode] = payload["operation"]; + } } + console.log(generatedProfile); return generatedProfile; }; @@ -1211,14 +1593,125 @@ var operationModule = function () { */ publicMethods.populateProfile = function (platformType, payload) { var i, configuredOperations = []; + var restrictions = {}; for (i = 0; i < payload.length; ++i) { var configuredFeature = payload[i]; var featureCode = configuredFeature["featureCode"]; var operationPayload = configuredFeature["content"]; + if(platformType == platformTypeConstants["ANDROID"]){ + var restriction = JSON.parse(operationPayload); + if(featureCode == androidOperationConstants["CAMERA_OPERATION_CODE"]){ + restrictions["cameraEnabled"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_ADJUST_VOLUME"]){ + restrictions["disallowAdjustVolumeEnabled"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_BLUETOOTH"]){ + restrictions["disallowConfigBluetooth"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_CELL_BROADCASTS"]){ + restrictions["disallowConfigCellBroadcasts"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_CREDENTIALS"]){ + restrictions["disallowConfigCredentials"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_MOBILE_NETWORKS"]){ + restrictions["disallowConfigMobileNetworks"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_TETHERING"]){ + restrictions["disallowConfigTethering"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_VPN"]){ + restrictions["disallowConfigVpn"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CONFIG_WIFI"]){ + restrictions["disallowConfigWifi"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_APPS_CONTROL"]){ + restrictions["disallowAppControl"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CREATE_WINDOWS"]){ + restrictions["disallowCreateWindows"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_CROSS_PROFILE_COPY_PASTE"]){ + restrictions["disallowCrossProfileCopyPaste"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_DEBUGGING_FEATURES"]){ + restrictions["disallowDebugging"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_FACTORY_RESET"]){ + restrictions["disallowFactoryReset"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_ADD_USER"]){ + restrictions["disallowAddUser"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_INSTALL_APPS"]){ + restrictions["disallowInstallApps"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_INSTALL_UNKNOWN_SOURCES"]){ + restrictions["disallowInstallUnknownSources"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_MODIFY_ACCOUNTS"]){ + restrictions["disallowModifyAccounts"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_MOUNT_PHYSICAL_MEDIA"]){ + restrictions["disallowMountPhysicalMedia"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_NETWORK_RESET"]){ + restrictions["disallowNetworkReset"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_OUTGOING_BEAM"]){ + restrictions["disallowOutgoingBeam"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_OUTGOING_CALLS"]){ + restrictions["disallowOutgoingCalls"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_REMOVE_USER"]){ + restrictions["disallowRemoveUser"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_SAFE_BOOT"]){ + restrictions["disallowSafeBoot"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_SHARE_LOCATION"]){ + restrictions["disallowLocationSharing"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_SMS"]){ + restrictions["disallowSMS"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_UNINSTALL_APPS"]){ + restrictions["disallowUninstallApps"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_UNMUTE_MICROPHONE"]){ + restrictions["disallowUnmuteMicrophone"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["DISALLOW_USB_FILE_TRANSFER"]){ + restrictions["disallowUSBFileTransfer"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["ALLOW_PARENT_PROFILE_APP_LINKING"]){ + restrictions["disallowParentProfileAppLinking"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["ENSURE_VERIFY_APPS"]){ + restrictions["ensureVerifyApps"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["AUTO_TIME"]){ + restrictions["enableAutoTime"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["SET_SCREEN_CAPTURE_DISABLED"]){ + restrictions["diableScreenCapture"] = restriction["enabled"]; + continue; + } else if (featureCode == androidOperationConstants["SET_STATUS_BAR_DISABLED"]){ + restrictions["disableStatusBar"] = restriction["enabled"]; + continue; + } + } //push the feature-code to the configuration array configuredOperations.push(featureCode); publicMethods.populateUI(platformType, featureCode, operationPayload); } + if (typeof restrictions.cameraEnabled !== 'undefined') { + configuredOperations.push(androidOperationConstants["CAMERA_OPERATION_CODE"]); + publicMethods.populateUI(platformType, androidOperationConstants["CAMERA_OPERATION_CODE"], JSON.stringify(restrictions)); + } return configuredOperations; }; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js index 9cf038f561..fa599c37a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js @@ -27,10 +27,10 @@ function onRequest (context) { } //For QR Code - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require("/app/modules/constants.js"); var permissions = userModule.getUIPermissions(); - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; context.permissions = permissions; context["enrollmentURL"] = deviceMgtProps.enrollmentURL; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js index eb4c87aeaf..e9c68c6452 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js @@ -23,7 +23,7 @@ function onRequest(context) { var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label"; var viewModel = {}; - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; var typesListResponse = deviceModule.getDeviceTypes(); if (typesListResponse["status"] == "success") { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js index d544e09b58..a3a0037dcb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js @@ -22,7 +22,7 @@ function onRequest(context) { var deviceId = request.getParameter("id"); if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var device = deviceModule.viewDevice(deviceType, deviceId); if (device) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js index a63dcbd5b0..9410669d5a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/public/js/invoker-lib.js @@ -27,8 +27,10 @@ var invokerUtil = function () { restAPIRequestDetails["requestURL"] = requestURL; restAPIRequestDetails["requestPayload"] = JSON.stringify(requestPayload); + var appContext = $("#app-context").data("app-context"); + var request = { - url: context + "/api/invoker/execute/", + url: appContext + "/api/invoker/execute/", type: "POST", contentType: "application/json", data: JSON.stringify(restAPIRequestDetails), diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/service-invoker-utility.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/service-invoker-utility.hbs index af0fa53631..cd12d80319 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/service-invoker-utility.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.lib.service-invoker-utility/service-invoker-utility.hbs @@ -31,11 +31,16 @@
    + {{/zone}} -{{#zone "bottomJs"}} + +{{#zone "topJs"}} +{{/zone}} + +{{#zone "bottomJs"}} {{js "js/js.cookie.js"}} {{js "js/invoker-lib.js"}} {{/zone}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js index 50306cbfb3..0086ba8e3e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js @@ -17,7 +17,7 @@ */ function onRequest(context){ - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require("/app/modules/constants.js"); var permissions = []; if(userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/notifications/list")){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js index ba6f47c614..52fd96af33 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js @@ -46,7 +46,7 @@ $(document).ready(function () { $("#ast-container").on("click", ".new-notification", function(e){ var notificationId = $(this).data("id"); var redirectUrl = $(this).data("url"); - var getNotificationsAPI = "/devicemgt_admin/notifications/"+notificationId+"/CHECKED"; + var getNotificationsAPI = "/api/device-mgt/v1.0/notifications/"+notificationId+"/CHECKED"; var errorMsgWrapper = "#error-msg"; var errorMsg = "#error-msg span"; invokerUtil.put( @@ -87,7 +87,7 @@ function loadNotifications(){ var deviceListingSrc = deviceListing.attr("src"); var currentUser = deviceListing.data("currentUser"); $.template("notification-listing", deviceListingSrc, function (template) { - var serviceURL = "/devicemgt_admin/notifications"; + var serviceURL = "/api/device-mgt/v1.0/notifications"; var successCallback = function (data) { var viewModel = {}; data = JSON.parse(data); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js index bdf84142ac..ce96d0d1a0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js @@ -17,8 +17,8 @@ */ function onRequest(context) { - var utility = require("/app/modules/device.js").utility; - var deviceModule = require("/app/modules/device.js").deviceModule; + var utility = require("/app/modules/utility.js").utility; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; //get all device types var deviceTypesArray = []; var typesListResponse = deviceModule.getDeviceTypes(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs index 5ea81961f6..adfadb50ab 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs @@ -15,69 +15,71 @@ specific language governing permissions and limitations under the License. }} -
    -
    -
    -
    -

    ADD POLICY

    -
    -
    -
    -
    -
    1
    - +{{#zone "content"}} +
    +
    +
    +
    +

    ADD POLICY

    +
    +
    +
    +
    +
    1
    + +
    +
    -
    -
    -
    -
    -
    2
    - +
    +
    +
    2
    + +
    +
    -
    -
    -
    -
    -
    3
    - +
    +
    +
    3
    + +
    +
    -
    -
    -
    -
    -
    4
    - +
    +
    +
    4
    + +
    +
    -
    -
    -
    -
    -
    -

    Step 1: Select a platform

    -
    +
    +
    +
    +

    Step 1: Select a platform

    +
    -
    -
    - +
    +
    + +
    +
    -
    -
    \ No newline at end of file +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js index e5c8045b4d..79d41eab85 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js @@ -21,14 +21,16 @@ function onRequest(context) { var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label"; var utility = require("/app/modules/utility.js").utility; - var deviceModule = require("/app/modules/device.js").deviceModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var types = {}; types["types"] = []; var typesListResponse = deviceModule.getDeviceTypes(); if (typesListResponse["status"] == "success") { for (var type in typesListResponse["content"]) { - var deviceType = typesListResponse["content"][type]["name"]; + var content = {}; + var deviceType = typesListResponse["content"]["deviceTypes"][type]; + content["name"] = deviceType; var configs = utility.getDeviceTypeConfig(deviceType); var deviceTypeLabel = deviceType; if (configs && configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) { @@ -36,9 +38,9 @@ function onRequest(context) { } var policyWizard = new File("/app/units/" + utility.getTenantedDeviceUnitName(deviceType, "policy-wizard")); if(policyWizard.isExists()){ - typesListResponse["content"][type]["icon"] = utility.getDeviceThumb(deviceType); - typesListResponse["content"][type]["label"] = deviceTypeLabel; - types["types"].push(typesListResponse["content"][type]); + content["icon"] = utility.getDeviceThumb(deviceType); + content["label"] = deviceTypeLabel; + types["types"].push(content); } } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs new file mode 100644 index 0000000000..fbeb8f8eb3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs @@ -0,0 +1,233 @@ +{{#zone "content"}} +
    +
    + + + + + + + + + +
    +
    +

    EDIT POLICY

    +
    +
    +
    +
    +
    +

    Step 1: Edit current profile

    +
    + +
    +
    +
    +    + +  Loading platform features . . . +
    +
    +
    +
    + +
    +
    +
    +
    + + + +
    +
    +{{/zone}} +{{#zone "bottomJs"}} + + + + + + + {{js "js/edit.js"}} +{{/zone}} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.js new file mode 100644 index 0000000000..dfb1cbe953 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.js @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2015, 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. + */ + +function onRequest(context) { + var log = new Log("policy-view-edit-unit backend js"); + log.debug("calling policy-view-edit-unit"); + + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + + var rolesResult = userModule.getRoles(); + if (rolesResult.status == "success") { + context.roles = rolesResult.content; + } + + var usersResult = userModule.getUsers(); + if (usersResult.status == "success") { + context.users = usersResult.content; + } + + return context; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.json new file mode 100644 index 0000000000..f706ffceea --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.json @@ -0,0 +1,3 @@ +{ + "version" : "1.0.0" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.hbs index 5a7fea7f8a..f4c6ff7754 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.hbs @@ -15,20 +15,19 @@ specific language governing permissions and limitations under the License. }} +
     Policy List by priority order
    -
    -
    -
    - {{policyListingStatusMsg}} - -
    - {{#each policyListToView}} - +
    +
    + {{policyListingStatusMsg}} +
    + {{#each policyListToView}} +
    @@ -40,15 +39,7 @@ - {{#equal platform "android"}} - - {{/equal}} - {{#equal platform "windows"}} - - {{/equal}} - {{#equal platform "ios"}} - - {{/equal}} +

    {{name}}

    @@ -62,19 +53,20 @@ Ownership Type : {{ownershipType}}
    - {{#if roles}} -
    -
    - Assigned Role(s) : {{roles}} -
    -
    - {{else}} + {{#equal roles "None"}}
    Assigned User(s) : {{users}}
    - {{/if}} + {{/equal}} + {{#equal users "None"}} +
    +
    + Assigned Role(s) : {{roles}} +
    +
    + {{/equal}}
    Compliance Type : {{compliance}} @@ -84,120 +76,112 @@
    - {{/each}} -
    - {{#equal noPolicy false}} -
    - - + {{/each}}
    - {{/equal}} + {{#equal noPolicy false}} +
    + + +
    + {{/equal}} +
    -
    -
    -
    -
    -
    -

    Do you really want to apply changes to all policies?

    +
    +
    +
    +
    +

    Do you really want to apply changes to all policies?

    -
    -
    -
    -
    -
    -
    -

    Done. Changes applied successfully.

    +
    +
    +
    +
    +

    Done. Changes applied successfully.

    -
    -
    -
    -
    -
    -
    -

    An unexpected error occurred. Please try again later.

    +
    +
    +
    +
    +

    An unexpected error occurred. Please try again later.

    -
    -
    -
    -
    -
    -
    -

    An unexpected error occurred. Please try again later.

    +
    +
    +
    +
    +

    An unexpected error occurred. Please try again later.

    -
    -
    -
    -
    -
    -
    -

    Done. New Policy priorities were successfully updated.

    +
    +
    +
    +
    +

    Done. New Policy priorities were successfully updated.

    -
    -
    -
    -
    -
    -
    -

    An unexpected error occurred. Please try again later.

    -

    - -
    - - Ok - +
    +
    +
    +
    +

    An unexpected error occurred. Please try again later.

    +
    diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js index 7630df258b..a6afb10f6b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js @@ -1,17 +1,17 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, 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 + * 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 + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ @@ -27,8 +27,9 @@ function onRequest(context) { return options.fn(this); } }); - var policyModule = require("/app/modules/policy.js")["policyModule"]; + var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"]; var response = policyModule.getAllPolicies(); + if (response["status"] == "success") { var policyListToView = response["content"]; context["policyListToView"] = policyListToView; @@ -38,7 +39,7 @@ function onRequest(context) { context["saveNewPrioritiesButtonEnabled"] = false; context["noPolicy"] = true; } else if (policyCount == 1) { - context["policyListingStatusMsg"] = "Add more policies to set up a priority order."; + context["policyListingStatusMsg"] = "Two or more policies should be available to set up a priority order."; context["saveNewPrioritiesButtonEnabled"] = false; context["noPolicy"] = false; } else { @@ -47,9 +48,11 @@ function onRequest(context) { context["noPolicy"] = false; } } else { + // here, response["status"] == "error" context["policyListToView"] = []; - context["policyListingStatusMsg"] = response["content"]; + context["policyListingStatusMsg"] = "Error in retrieving policies. Please try reloading the page."; context["saveNewPrioritiesButtonEnabled"] = false; } + return context; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/policy-priority.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/policy-priority.js index f2ccc3b9d1..f6b5514d7e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/policy-priority.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/policy-priority.js @@ -1,17 +1,17 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, 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 + * 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 + * "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. */ @@ -78,58 +78,66 @@ $(document).ready(function () { newPolicyPriorityList.push(policy); } - var updatePolicyAPI = "/devicemgt_admin/policies/priorities"; + var updatePolicyAPI = "/api/device-mgt/v1.0/policies/priorities"; invokerUtil.put( updatePolicyAPI, newPolicyPriorityList, - function () { - $(modalPopupContent).html($('#save-policy-priorities-success-content').html()); - showPopup(); - $("a#save-policy-priorities-success-link").click(function () { - hidePopup(); - }); + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $(modalPopupContent).html($('#save-policy-priorities-success-content').html()); + showPopup(); + $("a#save-policy-priorities-success-link").click(function () { + hidePopup(); + }); + } }, - function () { - $("#save-policy-priorities-error-content").find(".message-from-server").html( - "Message From Server : " + data["statusText"]); - $(modalPopupContent).html($('#save-policy-priorities-error-content').html()); - showPopup(); - $("a#save-policy-priorities-error-link").click(function () { - hidePopup(); - }); + // on error + function (jqXHR) { + if (jqXHR.status == 400 || jqXHR.status == 500) { + $(modalPopupContent).html($("#save-policy-priorities-error-content").html()); + showPopup(); + $("a#save-policy-priorities-error-link").click(function () { + hidePopup(); + }); + } } ); }); $(applyChangesBtn).click(function () { - var applyPolicyChangesAPI = "/devicemgt_admin/policies/apply-changes"; - $(modalPopupContent).html($('#change-policy-modal-content').html()); + var applyPolicyChangesAPI = "/api/device-mgt/v1.0/policies/apply-changes"; + $(modalPopupContent).html($("#apply-changes-modal-content").html()); showPopup(); - $("a#change-policy-yes-link").click(function () { + $("a#apply-changes-yes-link").click(function () { invokerUtil.put( applyPolicyChangesAPI, null, // on success - function () { - $(modalPopupContent).html($('#change-policy-success-content').html()); - showPopup(); - $("a#change-policy-success-link").click(function () { - hidePopup(); - }); + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $(modalPopupContent).html($("#apply-changes-success-content").html()); + showPopup(); + $("a#apply-changes-success-link").click(function () { + hidePopup(); + }); + } }, // on error - function () { - $(modalPopupContent).html($('#change-policy-error-content').html()); - showPopup(); - $("a#change-policy-error-link").click(function () { - hidePopup(); - }); + function (jqXHR) { + if (jqXHR.status == 500) { + $(modalPopupContent).html($("#apply-changes-error-content").html()); + showPopup(); + $("a#apply-changes-error-link").click(function () { + hidePopup(); + }); + } } ); }); - $("a#change-policy-cancel-link").click(function () { + $("a#apply-changes-cancel-link").click(function () { hidePopup(); }); }); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/sortable-list.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/sortable-list.js index c4f78b1bc1..c436e2ac56 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/sortable-list.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/public/js/sortable-list.js @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, 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 @@ -47,7 +47,7 @@ var sortableListFunction = (function () { } /** - * on input text field focus autocomplete bind function + * on input text field focus auto-complete bind function */ $(sortableElem).on('focus', '.wr-sort-index input.index', function () { currentElemId = $(this).val(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.hbs new file mode 100644 index 0000000000..b7f2adf56d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.hbs @@ -0,0 +1,88 @@ +{{#zone "content"}} + {{#defineZone "policy-profile-top"}} +
    +
    + +
    +
    + {{/defineZone}} + + +
    +
    +
    +
    +
    + Policy Overview +
    + {{#defineZone "policy-detail-properties"}} + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Platform
    Ownership
    Action upon non-compliance
    Status
    Assigned Users
    Assigned Roles
    + {{/defineZone}} +
    Description
    +
    +
    +
    +
    +
    + Profile Information +
    +
    + +
    +
    +
    + + Loading platform features . . . +
    +
    +
    +
    +
    +
    +
    +
    +
    +{{/zone}} +{{#zone "bottomJs"}} + + + + + + + {{js "js/view.js"}} +{{/zone}} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js similarity index 73% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js index 45210346bb..2d2a438263 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js @@ -1,4 +1,3 @@ -<% /* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * @@ -17,11 +16,10 @@ * under the License. */ -/* - @Deprecated - new - */ +function onRequest(context) { +// var log = new Log("policy-view-edit-unit backend js"); -// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; -// var tokenCookie = apiWrapperUtil.refreshToken(); -// print(tokenCookie); -%> \ No newline at end of file +// var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; +// context.roles = userModule.getRoles(); + return context; +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.json new file mode 100644 index 0000000000..f706ffceea --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.json @@ -0,0 +1,3 @@ +{ + "version" : "1.0.0" +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js index db293c3bf6..a65fa31e25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js @@ -23,8 +23,8 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var response = userModule.getRoles(); if (response["status"] == "success") { context["roles"] = response["content"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js index a16f9a38bb..6829dc21e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js @@ -23,7 +23,7 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var isMatched = uriMatcher.match("/{context}/roles/edit-role-permission/{rolename}"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js index 5e24261bd2..cf54af034e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js @@ -23,8 +23,8 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var isMatched = uriMatcher.match("/{context}/role/edit/{rolename}"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.hbs index fc648ff450..acf56f7963 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.hbs @@ -47,19 +47,6 @@ By Role Name - - - - - - - - - diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js index 681883aae3..d908da5d2d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js @@ -17,7 +17,7 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var response = userModule.getUsers(); var users = {}; context["permissions"] = userModule.getUIPermissions(); @@ -30,7 +30,7 @@ function onRequest(context) { if (userModule.isAuthorized("/permission/admin/device-mgt/roles/remove")) { context["removePermitted"] = true; } - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; context["appContext"] = deviceMgtProps.appContext; context["adminRole"] = deviceMgtProps.adminRole; return context; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/public/js/role-listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/public/js/role-listing.js index bee418fd1c..1b0991cb0a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/public/js/role-listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/public/js/role-listing.js @@ -16,10 +16,12 @@ * under the License. */ var loadRoleBasedActionURL = function (action, rolename) { - var href = $("#ast-container").data("app-context") + "role/" + action + "/" + rolename; + var href = $("#ast-container").data("app-context") + "roles/" + action + "?rolename=" + rolename; $(location).attr('href', href); }; +var apiBasePath = "/api/device-mgt/v1.0"; + /** * Following function would execute * when a user clicks on the list item @@ -38,34 +40,34 @@ var loadPaginatedObjects = function (objectGridId, objectGridContainer, objectGr var templateSrc = $(objectGridTemplateSrc).attr("src"); $.template(objectGridId, templateSrc, function (template) { invokerUtil.get(serviceURL, - function (data) { - data = callback(data); - if (data.length > 0 && data != null) { - $('#ast-container').removeClass('hidden'); - $('#role-listing-status').hide(); - for (var i = 0; i < data.viewModel.roles.length; i++) { - data.viewModel.roles[i].adminRole = $("#role-table").data("role"); - } - var content = template(data.viewModel); - $(objectGridContainer).html(content); - if (isInit) { - $('#role-grid').datatables_extended(); - isInit = false; - } - $("#dt-select-all").addClass("hidden"); - $(".icon .text").res_text(0.2); - } else { - $('#ast-container').addClass('hidden'); - $('#role-listing-status-msg').text('No roles are available to be displayed.'); - $('#role-listing-status').show(); - } + function (data) { + data = callback(data); + if (data.length > 0 && data != null) { + $('#ast-container').removeClass('hidden'); + $('#role-listing-status').hide(); + for (var i = 0; i < data.viewModel.roles.length; i++) { + data.viewModel.roles[i].adminRole = $("#role-table").data("role"); + } + var content = template(data.viewModel); + $(objectGridContainer).html(content); + if (isInit) { + $('#role-grid').datatables_extended_serverside_paging(); + isInit = false; + } + $("#dt-select-all").addClass("hidden"); + $(".icon .text").res_text(0.2); + } else { + $('#ast-container').addClass('hidden'); + $('#role-listing-status-msg').text('No roles are available to be displayed.'); + $('#role-listing-status').show(); + } - //$(objectGridId).datatables_extended(); - }, function (message) { - $('#ast-container').addClass('hidden'); - $('#role-listing-status-msg').text('Invalid search query. Try again with a valid search ' + - 'query'); - $('#role-listing-status').show(); + //$(objectGridId).datatables_extended(); + }, function (message) { + $('#ast-container').addClass('hidden'); + $('#role-listing-status-msg').text('Invalid search query. Try again with a valid search ' + + 'query'); + $('#role-listing-status').show(); }); }); }; @@ -73,46 +75,72 @@ var loadPaginatedObjects = function (objectGridId, objectGridContainer, objectGr function loadRoles(searchQuery) { var loadingContent = $("#loading-content"); loadingContent.show(); - var serviceURL = "/devicemgt_admin/roles"; - if (searchQuery) { - serviceURL = serviceURL + "/search?filter=" + searchQuery; + + var dataFilter = function(data){ + data = JSON.parse(data); + + var objects = []; + + $(data.roles).each(function( index ) { + objects.push({name: data.roles[index], DT_RowId : "role-" + data.roles[index]}) + }); + + json = { + "recordsTotal": data.count, + "recordsFiltered": data.count, + "data": objects + }; + + return JSON.stringify( json ); } - var callback = function (data) { - if (data != null || data == "null") { - data = JSON.parse(data); - var canRemove = $("#can-remove").val(); - var canEdit = $("#can-edit").val(); - var roles = []; - for(var i=0; i
    ' + }, + { + class: "fade-edge remove-padding-top", + data: "name", + defaultContent: '' + }, + { + class: "text-right content-fill text-left-on-grid-view no-wrap", + data: null, + render: function ( data, type, row, meta ) { + return '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' } } - return data; + ]; + + var options = { + "placeholder": "Search By Role Name", + "searchKey" : "filter" }; - loadPaginatedObjects("#role-grid", "#ast-container", "#role-listing", serviceURL, callback); + $('#role-grid').datatables_extended_serverside_paging(null, '/api/device-mgt/v1.0/roles', dataFilter, columns, fnCreatedRow, null, options); + loadingContent.hide(); - var sortableElem = '.wr-sortable'; - $(sortableElem).sortable({ - beforeStop: function () { - var sortedIDs = $(this).sortable('toArray'); - } - }); - $(sortableElem).disableSelection(); + } var modalPopup = ".wr-modalpopup"; @@ -153,7 +181,7 @@ function hidePopup() { */ $("#role-grid").on("click", ".remove-role-link", function () { var role = $(this).data("role"); - var removeRoleAPI = "/devicemgt_admin/roles?rolename=" + role; + var removeRoleAPI = apiBasePath + "/roles/" + role; $(modalPopupContent).html($('#remove-role-modal-content').html()); showPopup(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js index 89213cf587..363d9688e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js @@ -27,8 +27,8 @@ function onRequest(context) { return options.fn(this); } }); - var userModule = require("/app/modules/user.js")["userModule"]; - var mdmProps = require('/app/conf/reader/main.js')["conf"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var uiPermissions = userModule.getUIPermissions(); context["permissions"] = uiPermissions; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs index 1d82a81154..5fbe77d385 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs @@ -2,17 +2,20 @@ 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 + 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 + 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 + "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. }} -{{#zone "title"}}{{@unit.params.pageTitle}} | {{@app.conf.appName}}{{/zone}} \ No newline at end of file + +{{#zone "title"}} + {{@unit.params.pageTitle}} | {{@app.conf.appName}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs index af6cd3218f..fca8b278a2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs @@ -2,21 +2,24 @@ 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 + 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 + 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 + "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. }} + {{#zone "navbarHeader"}} -
    -