From 49623a4693dcbd35f6b5305c3e29d31254fcb4ce Mon Sep 17 00:00:00 2001 From: mharindu Date: Sun, 3 Jul 2016 15:03:47 +0530 Subject: [PATCH 01/21] Implemented scope based authorization --- .../apimgt/annotations/api/Permission.java | 2 +- .../config/PermissionConfiguration.java | 10 +- .../lifecycle/util/AnnotationProcessor.java | 58 +-- .../mgt/jaxrs/api/CertificateMgtService.java | 2 +- .../CertificateManagementAdminService.java | 8 +- .../org.wso2.carbon.device.mgt.api/pom.xml | 4 +- .../api/ActivityInfoProviderService.java | 6 +- .../api/ConfigurationManagementService.java | 8 +- .../service/api/DeviceManagementService.java | 45 +-- .../api/NotificationManagementService.java | 9 +- .../service/api/PolicyManagementService.java | 41 +-- .../service/api/RoleManagementService.java | 20 +- .../service/api/UserManagementService.java | 18 +- .../ApplicationManagementAdminService.java | 5 +- .../admin/DeviceManagementAdminService.java | 4 +- .../api/admin/UserManagementAdminService.java | 5 +- .../mgt/common/permission/mgt/Permission.java | 43 +-- .../mgt/PermissionManagerService.java | 3 +- .../org.wso2.carbon.device.mgt.core/pom.xml | 28 +- .../DeviceAccessAuthorizationServiceImpl.java | 4 +- .../permission/AnnotationProcessor.java | 332 ++++++++++++++++++ .../permission/PermissionConfiguration.java | 22 +- .../WebAppDeploymentLifecycleListener.java | 48 ++- .../mgt/PermissionManagerServiceImpl.java | 6 +- .../core/permission/mgt/PermissionTree.java | 3 - .../core/permission/mgt/PermissionUtils.java | 154 ++++---- .../PermissionBasedScopeValidator.java | 4 +- .../authenticator/framework/Utils/Utils.java | 23 ++ .../authenticator/OAuthAuthenticator.java | 17 +- .../authorizer/PermissionAuthorizer.java | 51 +-- .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- 32 files changed, 636 insertions(+), 351 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java 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/Permission.java index 65ade5cc3a..bc771b72c7 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/Permission.java @@ -40,6 +40,6 @@ public @interface Permission { * Represents the associated permissions. * @return Returns list of permissions. */ - String[] permissions(); + String[] roles(); } 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/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java index 7d16d198b9..81a722e5ff 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/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java @@ -24,7 +24,7 @@ package org.wso2.carbon.apimgt.webapp.publisher.config; public class PermissionConfiguration { private String scopeName; - private String[] permissions; + private String[] roles; public String getScopeName() { return scopeName; @@ -34,12 +34,12 @@ public class PermissionConfiguration { this.scopeName = scope; } - public String[] getPermissions() { - return permissions; + public String[] getRoles() { + return roles; } - public void setPermissions(String[] permissions) { - this.permissions = permissions; + public void setRoles(String[] roles) { + this.roles = roles; } } 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 a88fe00e9f..7de4b6569b 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,12 +19,10 @@ 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; @@ -36,11 +34,14 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementExcept 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; @@ -58,13 +59,9 @@ 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"; - private StandardContext context; private Method[] pathClazzMethods; private Class pathClazz; Class apiClazz; @@ -73,7 +70,6 @@ public class AnnotationProcessor { public AnnotationProcessor(final StandardContext context) { - this.context = context; servletContext = context.getServletContext(); classLoader = servletContext.getClassLoader(); } @@ -90,11 +86,8 @@ public class AnnotationProcessor { db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); - URL[] libPath = WarUrlFinder.findWebInfLibClasspaths(servletContext); - URL classPath = WarUrlFinder.findWebInfClassesPath(servletContext); - URL[] urls = (URL[]) ArrayUtils.add(libPath, libPath.length, classPath); - - db.scanArchives(urls); + URL classPath = findWebInfClassesPath(servletContext); + db.scanArchives(classPath); //Returns a list of classes with given Annotation return db.getAnnotationIndex().get(className); @@ -142,7 +135,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 +144,6 @@ public class AnnotationProcessor { } else { rootContext = rootContext + "/" + subContext; } - } else { - subContext = ""; } if (log.isDebugEnabled()) { log.debug("API Root Context = " + rootContext); @@ -167,7 +158,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; } @@ -259,7 +250,7 @@ public class AnnotationProcessor { scope.setKey(permissionConf.getScopeName()); scope.setDescription(permissionConf.getScopeName()); scope.setName(permissionConf.getScopeName()); - String roles = StringUtils.join(permissionConf.getPermissions(), ","); + String roles = StringUtils.join(permissionConf.getRoles(), ","); scope.setRoles(roles); resource.setScope(scope); } @@ -369,10 +360,10 @@ public class AnnotationProcessor { case "scope": permissionConf.setScopeName(invokeMethod(method, permissionAnnotation, STRING)); break; - case "permissions": - String permissions[] = invokeMethod(method, permissionAnnotation); - this.addPermission(permissions); - permissionConf.setPermissions(permissions); + case "roles": + String roles[] = invokeMethod(method, permissionAnnotation); + this.addPermission(roles); + permissionConf.setRoles(roles); break; } } @@ -387,4 +378,29 @@ public class AnnotationProcessor { } } + + /** + * 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); + } + } + } 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..d4b1d3e6da 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 @@ -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"}) + @Permission(scope = "sign-csr", roles = {"emm-admin"}) Response getSignedCertFromCSR( @ApiParam( name = "If-Modified-Since", 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..d69b3987c5 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 @@ -72,7 +72,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"}) + @Permission(scope = "certificate-modify", roles = {"admin"}) Response addCertificate( @ApiParam( name = "enrollmentCertificates", @@ -130,7 +130,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"}) + @Permission(scope = "certificate-view", roles = {"emm-admin"}) Response getCertificate( @ApiParam(name = "serialNumber", value = "Provide the serial number of the certificate that you wish to get the details of", @@ -202,7 +202,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"}) + @Permission(scope = "certificate-view", roles = {"emm-admin"}) Response getAllCertificates( @ApiParam( name = "offset", @@ -245,7 +245,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"}) + @Permission(scope = "certificate-modify", roles = {"emm-admin"}) Response removeCertificate( @ApiParam( name = "serialNumber", 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 e4be5c03ff..36deba6c9b 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 @@ -46,7 +46,7 @@ maven-war-plugin WEB-INF/lib/*cxf*.jar - api#device-mgt#v1.0 + api-device-mgt-v1.0 @@ -72,7 +72,7 @@ - + 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 3cdc31ed07..d2ad14d1f1 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 @@ -32,7 +32,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,7 +91,7 @@ public interface ActivityInfoProviderService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) + @Permission(scope = "activity-view", roles = {"emm-user", "emm-admin"}) Response getActivity( @ApiParam( name = "id", @@ -147,7 +147,7 @@ public interface ActivityInfoProviderService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", permissions = {"/permission/admin/device-mgt/admin/activities/view"}) + @Permission(scope = "activity-view", roles = {"emm-admin"}) 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 ab067e0e19..168eda4740 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 @@ -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 " + @@ -78,8 +78,7 @@ public interface ConfigurationManagementService { "platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration-view", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/view"}) + @Permission(scope = "configuration-view", roles = {"emm-admin"}) Response getConfiguration( @ApiParam( name = "If-Modified-Since", @@ -126,8 +125,7 @@ public interface ConfigurationManagementService { "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration-modify", - permissions = {"/permission/admin/device-mgt/admin/platform-configs/modify"}) + @Permission(scope = "configuration-modify", roles = {"emm-admin"}) 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 a3958d4dac..474677f076 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 @@ -37,7 +37,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 " + @@ -90,10 +90,7 @@ public interface DeviceManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission( - scope = "device-list", - permissions = {"/permission/admin/device-mgt/admin/devices/list"} - ) + @Permission(scope = "device-list", roles = {"emm-admin"}) Response getDevices( @ApiParam( name = "type", @@ -197,13 +194,7 @@ 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" - } - ) + @Permission(scope = "device-view", roles = {"emm-admin"}) Response getDevice( @ApiParam( name = "type", @@ -283,12 +274,7 @@ 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" - } - ) + @Permission(scope = "device-search", roles = {"emm-admin"}) Response getFeaturesOfDevice( @ApiParam( name = "type", @@ -362,10 +348,7 @@ 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" } - ) + @Permission(scope = "device-search", roles = {"emm-admin" }) Response searchDevices( @ApiParam( name = "offset", @@ -445,13 +428,7 @@ public interface DeviceManagementService { + "the device.", response = ErrorResponse.class) }) - @Permission( - scope = "operation-view", - permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Permission(scope = "operation-view", roles = {"emm-admin"}) Response getInstalledApplications( @ApiParam( name = "type", @@ -546,13 +523,7 @@ public interface DeviceManagementService { + "device.", response = ErrorResponse.class) }) - @Permission( - scope = "operation-view", - permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" - } - ) + @Permission(scope = "operation-view", roles = {"emm-admin"}) Response getDeviceOperations( @ApiParam( name = "type", @@ -649,6 +620,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) + @Permission(scope = "operation-view", roles = {"emm-admin"}) Response getEffectivePolicyOfDevice( @ApiParam( name = "type", @@ -689,5 +661,6 @@ public interface DeviceManagementService { message = "Error occurred while fetching the list of device types.") } ) + @Permission(scope = "operation-view", roles = {"emm-admin"}) Response getDeviceTypes(); } 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 de119c553e..d547ddbcd3 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 @@ -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,12 +89,7 @@ public interface NotificationManagementService { message = "Internal Server ErrorResponse. \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" - }) + @Permission(scope = "device-notification-view", roles = {"emm-admin"}) Response getNotifications( @ApiParam( name = "status", 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 9b63bd0e47..e6965402f6 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,6 +19,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.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; @@ -34,6 +35,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,9 +98,7 @@ public interface PolicyManagementService { "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/add"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response addPolicy( @ApiParam( name = "policy", @@ -149,9 +151,7 @@ public interface PolicyManagementService { "policies."), response = ErrorResponse.class) }) - @Permission( - scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"}) + @Permission(scope = "policy-view", roles = {"emm-admin"}) Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -217,9 +217,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Permission( - scope = "policy-view", - permissions = {"/permission/admin/device-mgt/admin/policies/list"}) + @Permission(scope = "policy-view", roles = {"emm-admin"}) Response getPolicy( @ApiParam( name = "id", @@ -281,9 +279,7 @@ public interface PolicyManagementService { "Server error occurred while updating the policy.", response = ErrorResponse.class) }) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/update"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response updatePolicy( @ApiParam( name = "id", @@ -328,9 +324,7 @@ public interface PolicyManagementService { "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) - @Permission( - scope = "policy-modify", - permissions = {"/permission/admin/device-mgt/admin/policies/remove"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response removePolicies( @ApiParam( name = "policyIds", @@ -366,10 +360,7 @@ public interface PolicyManagementService { 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"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response activatePolicies( @ApiParam( name = "policyIds", @@ -405,11 +396,7 @@ public interface PolicyManagementService { 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"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -442,7 +429,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", permissions = {"/permission/admin/device-mgt/admin/policies/update"}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) Response applyChanges(); @@ -471,9 +458,7 @@ public interface PolicyManagementService { message = "Exception in updating policy priorities.", response = ErrorResponse.class) }) - @Permission( - scope = "", - permissions = {}) + @Permission(scope = "policy-modify", roles = {"emm-admin"}) 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 06f52e1dda..f4533bb754 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 @@ -32,7 +32,7 @@ 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.") @@ -82,11 +82,7 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \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"}) + @Permission(scope = "roles-view", roles = {"emm-admin"}) Response getRoles( @ApiParam( name = "filter", @@ -167,7 +163,7 @@ 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"}) + @Permission(scope = "roles-view", roles = {"emm-admin"}) Response getPermissionsOfRole( @ApiParam( name = "roleName", @@ -229,7 +225,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-view", permissions = {"/permission/admin/device-mgt/admin/roles/list"}) + @Permission(scope = "roles-view", roles = {"emm-admin"}) Response getRole( @ApiParam( name = "roleName", @@ -289,7 +285,7 @@ public interface RoleManagementService { "Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/add"}) + @Permission(scope = "roles-modify", roles = {"emm-admin"}) Response addRole( @ApiParam( name = "role", @@ -341,7 +337,7 @@ public interface RoleManagementService { "Server error occurred while updating the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/update"}) + @Permission(scope = "roles-modify", roles = {"emm-admin"}) Response updateRole( @ApiParam( name = "roleName", @@ -378,7 +374,7 @@ public interface RoleManagementService { "Server error occurred while removing the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", permissions = {"/permission/admin/device-mgt/admin/roles/remove"}) + @Permission(scope = "roles-modify", roles = {"emm-admin"}) Response deleteRole( @ApiParam( name = "roleName", @@ -436,7 +432,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"}) + @Permission(scope = "roles-modify", roles = {"emm-admin"}) 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 fbbeb51736..29dff53c4f 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 @@ -28,7 +28,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@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.") @@ -87,7 +87,7 @@ public interface UserManagementService { "Server error occurred while adding a new user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/add"}) + @Permission(scope = "user-modify", roles = {"emm-admin"}) Response addUser( @ApiParam( name = "user", @@ -138,7 +138,7 @@ public interface UserManagementService { " fetching the requested user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + @Permission(scope = "user-view", roles = {"emm-admin"}) Response getUser( @ApiParam( name = "username", @@ -196,7 +196,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"}) + @Permission(scope = "user-modify", roles = {"emm-admin"}) Response updateUser( @ApiParam( name = "username", @@ -231,7 +231,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/device-mgt/admin/user/remove"}) + @Permission(scope = "user-modify", roles = {"emm-admin"}) Response removeUser( @ApiParam(name = "username", value = "Username of the user to be deleted.", required = true) @PathParam("username") String username); @@ -279,7 +279,7 @@ public interface UserManagementService { " assigned to the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/view"}) + @Permission(scope = "user-view", roles = {"emm-admin"}) Response getRolesOfUser( @ApiParam(name = "username", value = "Username of the user.", required = true) @PathParam("username") String username); @@ -321,7 +321,7 @@ public interface UserManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", permissions = {"/permission/admin/device-mgt/admin/user/list"}) + @Permission(scope = "user-view", roles = {"emm-admin"}) Response getUsers( @ApiParam( name = "filter", @@ -387,7 +387,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"}) + @Permission(scope = "user-view", roles = {"emm-admin"}) Response getUserNames( @ApiParam( name = "filter", @@ -439,7 +439,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) + @Permission(scope = "user-modify", roles = {"emm-admin"}) Response resetPassword( @ApiParam( name = "username", 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 23b6cba5ab..a1abf62db1 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.Permission; 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) }) + @Permission(scope = "application-modify", roles = {"emm-admin"}) Response installApplication( @ApiParam( name = "applicationWrapper", @@ -111,6 +113,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) + @Permission(scope = "application-modify", roles = {"emm-admin"}) 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 2396de53f1..fde865b4af 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,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.Permission; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -27,7 +28,7 @@ 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,6 +84,7 @@ public interface DeviceManagementAdminService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) + @Permission(scope = "device-view", roles = {"emm-admin"}) Response getDevicesByName( @ApiParam( name = "name", 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 fb8610ce43..4468044223 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,6 +19,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.Permission; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; @@ -27,6 +28,8 @@ 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,7 +67,7 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", permissions = {"/permission/admin/login"}) + @Permission(scope = "user-modify", roles = {"emm-admin"}) Response resetUserPassword( @ApiParam( name = "username", 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.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml index 9f3b0bee45..be896513a2 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/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 4c2e57d8bd..dc10c5c776 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 @@ -248,9 +248,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/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..6e7fa12c71 --- /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 { + AnnotationDB db = new AnnotationDB(); + 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/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/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..9dd03555a2 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,10 +53,9 @@ 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 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 d70247f683..8ab98b9fd8 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,95 +39,93 @@ 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(); - factory.setNamespaceAware(true); - try { - DocumentBuilder docBuilder = factory.newDocumentBuilder(); - return docBuilder.parse(file); - } catch (Exception e) { - throw new PermissionManagementException("Error occurred while parsing file, while converting " + - "to a org.w3c.dom.Document", e); - } - } + public static Document convertToDocument(File file) throws PermissionManagementException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new PermissionManagementException("Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document", e); + } + } } diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java index 04fc9996cd..b4a5521e0b 100644 --- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java +++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/src/main/java/org/wso2/carbon/device/mgt/oauth/extensions/validators/PermissionBasedScopeValidator.java @@ -87,11 +87,11 @@ public class PermissionBasedScopeValidator extends OAuth2ScopeValidator { if (userRealm != null && userRealm.getAuthorizationManager() != null) { if (userStore != null) { status = userRealm.getAuthorizationManager() - .isUserAuthorized(userStore + "/" + username, permission.getPath(), + .isUserAuthorized(userStore + "/" + username, permission.getUrl(), PermissionMethod.UI_EXECUTE); } else { status = userRealm.getAuthorizationManager() - .isUserAuthorized(username, permission.getPath(), PermissionMethod.UI_EXECUTE); + .isUserAuthorized(username, permission.getUrl(), PermissionMethod.UI_EXECUTE); } } } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java index 9632649277..163e8287fe 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/Utils/Utils.java @@ -23,6 +23,10 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; +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.permission.mgt.PermissionManagerServiceImpl; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.user.api.TenantManager; import org.wso2.carbon.user.api.UserStoreException; @@ -30,9 +34,17 @@ import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; +import java.util.Properties; + public class Utils { private static final Log log = LogFactory.getLog(Utils.class); + private static PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance(); + private static Properties properties; + private static Permission permission; + + public static final String URL_PROPERTY = "URL"; + public static final String HTTP_METHOD_PROPERTY = "HTTP_METHOD"; public static int getTenantIdOFUser(String username) throws AuthenticationException { int tenantId = 0; @@ -74,4 +86,15 @@ public class Utils { } } + public static String getResourceUri(String url, String httpMethod) throws PermissionManagementException { + properties = new Properties(); + properties.put(URL_PROPERTY, url); + properties.put(HTTP_METHOD_PROPERTY, httpMethod); + permission = permissionManagerService.getPermission(properties); + if (permission != null) { + return permission.getContext() + "/1.0.0/1.0.0" + permission.getUrlTemplate() + ":" + permission.getMethod(); + } + return null; + } + } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java index bbeab152a3..abb0178cc6 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OAuthAuthenticator.java @@ -23,6 +23,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; +import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationFrameworkUtil; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; @@ -105,7 +106,7 @@ public class OAuthAuthenticator implements WebappAuthenticator { StringTokenizer tokenizer = new StringTokenizer(requestUri, "/"); String context = tokenizer.nextToken(); - if ((context == null) || ("".equals(context))) { + if ((context == null) || (context.isEmpty())) { authenticationInfo.setStatus(WebappAuthenticator.Status.CONTINUE); } String apiVersion = tokenizer.nextToken(); @@ -120,7 +121,17 @@ public class OAuthAuthenticator implements WebappAuthenticator { } else { String bearerToken = getBearerToken(request); - String resource = requestUri + ":" + requestMethod; + int urlParamIndex = requestUri.indexOf('?'); + if(urlParamIndex > 0) { + requestUri = requestUri.substring(0, urlParamIndex); + } + String resource = Utils.getResourceUri(requestUri, requestMethod); + + if (resource == null || resource.isEmpty()) { + authenticationInfo.setStatus(Status.FAILURE); + authenticationInfo.setMessage("Requested resource does not exist"); + return authenticationInfo; + } OAuthValidationResponse oAuthValidationResponse = this.tokenValidator.validateToken(bearerToken, resource); @@ -142,6 +153,8 @@ public class OAuthAuthenticator implements WebappAuthenticator { log.error("Failed to authenticate the incoming request", e); } catch (OAuthTokenValidationException e) { log.error("Failed to authenticate the incoming request due to oauth token validation error.", e); + } catch (PermissionManagementException e) { + log.error("Failed to authenticate the incoming request due to error in permission initialization", e); } return authenticationInfo; } diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java index 6d5138d3a2..c17d6fcc6a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authorizer/PermissionAuthorizer.java @@ -42,56 +42,7 @@ public class PermissionAuthorizer { public WebappAuthenticator.Status authorize(Request request, Response response) { - String requestUri = request.getRequestURI(); - String requestMethod = request.getMethod(); - - if (requestUri == null || requestUri.isEmpty() || requestMethod == null || requestMethod.isEmpty()) { - return WebappAuthenticator.Status.CONTINUE; - } - - PermissionManagerServiceImpl registryBasedPermissionManager = PermissionManagerServiceImpl.getInstance(); - Properties properties = new Properties(); - properties.put("",requestUri); - properties.put("",requestMethod); - Permission requestPermission = null; - try { - requestPermission = registryBasedPermissionManager.getPermission(properties); - } catch (PermissionManagementException e) { - log.error( - "Error occurred while fetching the permission for URI : " + Encode.forJava(requestUri) + " ," + - " METHOD : " + requestMethod + ", msg = " + e.getMessage()); - } - - if (requestPermission == null) { - if (log.isDebugEnabled()) { - log.debug("Permission to request '" + Encode.forJava(requestUri) + "' is not defined in the configuration"); - } - return WebappAuthenticator.Status.FAILURE; - } - - String permissionString = requestPermission.getPath(); - - // This is added temporarily until authentication works. - // TODO remove below line. - String username = "admin"; - // TODO uncomment this once the authentication works. - //String username = CarbonContext.getThreadLocalCarbonContext().getUsername(); - - boolean isUserAuthorized; - try { - isUserAuthorized = CarbonContext.getThreadLocalCarbonContext().getUserRealm(). - getAuthorizationManager().isUserAuthorized(username, permissionString, - Constants.PermissionMethod.READ); - } catch (UserStoreException e) { - log.error("Error occurred while retrieving user store. " + e.getMessage()); - return WebappAuthenticator.Status.FAILURE; - } - - if (isUserAuthorized) { - return WebappAuthenticator.Status.SUCCESS; - } else { - return WebappAuthenticator.Status.FAILURE; - } + return WebappAuthenticator.Status.SUCCESS; } } diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index d3fcbc2c5d..2ed84f0600 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -57,7 +57,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - api#device-mgt#v1.0.war + api-device-mgt-v1.0.war diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf index e0423d3cc3..032e7e18c8 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf @@ -1,3 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/api#device-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#device-mgt#v1.0.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/api-device-mgt-v1.0.war,target:${installFolder}/../../deployment/server/webapps/api-device-mgt-v1.0.war,overwrite:true);\ \ No newline at end of file From fe28bc25f1d27cf8925584f7de7eebc7d9c6e424 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 4 Jul 2016 14:06:30 +0530 Subject: [PATCH 02/21] Refactored scopes --- .../api/ActivityInfoProviderService.java | 4 +-- .../api/ConfigurationManagementService.java | 4 +-- .../service/api/DeviceManagementService.java | 35 ++++--------------- .../api/NotificationManagementService.java | 2 +- .../service/api/PolicyManagementService.java | 18 +++++----- .../service/api/RoleManagementService.java | 14 ++++---- .../ApplicationManagementAdminService.java | 4 +-- .../admin/DeviceManagementAdminService.java | 2 +- .../api/admin/UserManagementAdminService.java | 2 +- 9 files changed, 32 insertions(+), 53 deletions(-) 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 5b457b1b15..bb1320938a 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 @@ -91,7 +91,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", roles = {"emm-user", "emm-admin"}) + @Permission(scope = "activity:view", roles = {"admin"}) Response getActivity( @ApiParam( name = "id", @@ -150,7 +150,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity-view", roles = {"emm-admin"}) + @Permission(scope = "activity:view", roles = {"admin"}) 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 bbeaf3cf0d..32fa08fd96 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 @@ -81,7 +81,7 @@ public interface ConfigurationManagementService { "platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration-view", roles = {"emm-admin"}) + @Permission(scope = "configuration:view", roles = {"admin"}) Response getConfiguration( @ApiParam( name = "If-Modified-Since", @@ -127,7 +127,7 @@ public interface ConfigurationManagementService { "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration-modify", roles = {"emm-admin"}) + @Permission(scope = "configuration:modify", roles = {"admin"}) 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 11d1672b89..d2ef6fc701 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 @@ -90,7 +90,7 @@ public interface DeviceManagementService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission(scope = "device-list", roles = {"emm-admin"}) + @Permission(scope = "device:list", roles = {"admin"}) Response getDevices( @ApiParam( name = "type", @@ -194,7 +194,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - @Permission(scope = "device-view", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getDevice( @ApiParam( name = "type", @@ -274,7 +274,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) - @Permission(scope = "device-search", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getFeaturesOfDevice( @ApiParam( name = "type", @@ -348,7 +348,7 @@ public interface DeviceManagementService { "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) - @Permission(scope = "device-search", roles = {"emm-admin" }) + @Permission(scope = "device:search", roles = {"admin" }) Response searchDevices( @ApiParam( name = "offset", @@ -427,7 +427,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) - @Permission(scope = "operation-view", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getInstalledApplications( @ApiParam( name = "type", @@ -521,7 +521,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) - @Permission(scope = "operation-view", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getDeviceOperations( @ApiParam( name = "type", @@ -617,7 +617,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Permission(scope = "operation-view", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getEffectivePolicyOfDevice( @ApiParam( name = "type", @@ -639,25 +639,4 @@ public interface DeviceManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince); - @GET - @Path("/types") - @ApiOperation( - produces = MediaType.APPLICATION_JSON, - httpMethod = "GET", - value = "Get the device type.", - notes = "You are able to register Android, iOS and Windows devices with WSO2 EMM. In order to" - + "retrieve the device type details that are registered this end-point van be used.", - tags = "Device Management") - @ApiResponses( - value = { - @ApiResponse( - code = 200, - message = "OK. \n Registered device types have successfully retrieved"), - @ApiResponse( - code = 500, - message = "Error occurred while fetching the list of device types.") - } - ) - @Permission(scope = "operation-view", roles = {"emm-admin"}) - Response getDeviceTypes(); } 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 5656bbf3b2..da4b7c3628 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 @@ -90,7 +90,7 @@ public interface NotificationManagementService { "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) }) - @Permission(scope = "device-notification-view", roles = {"emm-admin"}) + @Permission(scope = "notification:view", roles = {"admin"}) Response getNotifications( @ApiParam( name = "status", 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 17ec195fbc..edd6ea4c8f 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 @@ -99,7 +99,7 @@ public interface PolicyManagementService { "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:add", roles = {"admin"}) Response addPolicy( @ApiParam( name = "policy", @@ -153,7 +153,7 @@ public interface PolicyManagementService { "policies."), response = ErrorResponse.class) }) - @Permission(scope = "policy-view", roles = {"emm-admin"}) + @Permission(scope = "policy:list", roles = {"admin"}) Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -219,7 +219,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy-view", roles = {"emm-admin"}) + @Permission(scope = "policy:view", roles = {"admin"}) Response getPolicy( @ApiParam( name = "id", @@ -283,7 +283,7 @@ public interface PolicyManagementService { "Server error occurred while updating the policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:modify", roles = {"admin"}) Response updatePolicy( @ApiParam( name = "id", @@ -329,7 +329,7 @@ public interface PolicyManagementService { "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:modify", roles = {"admin"}) Response removePolicies( @ApiParam( name = "policyIds", @@ -365,7 +365,7 @@ public interface PolicyManagementService { message = "ErrorResponse in activating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:add", roles = {"admin"}) Response activatePolicies( @ApiParam( name = "policyIds", @@ -401,7 +401,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:add", roles = {"admin"}) Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -434,7 +434,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:add", roles = {"admin"}) Response applyChanges(); @@ -463,7 +463,7 @@ public interface PolicyManagementService { message = "Exception in updating policy priorities.", response = ErrorResponse.class) }) - @Permission(scope = "policy-modify", roles = {"emm-admin"}) + @Permission(scope = "policy:add", roles = {"admin"}) 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 3c08c1b1fb..cef486e935 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 @@ -77,7 +77,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", roles = {"emm-admin"}) + @Permission(scope = "roles:list", roles = {"admin"}) Response getRoles( @ApiParam( name = "filter", @@ -159,7 +159,7 @@ 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", roles = {"emm-admin"}) + @Permission(scope = "roles:view", roles = {"admin"}) Response getPermissionsOfRole( @ApiParam( name = "roleName", @@ -222,7 +222,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-view", roles = {"emm-admin"}) + @Permission(scope = "roles:view", roles = {"admin"}) Response getRole( @ApiParam( name = "roleName", @@ -282,7 +282,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", roles = {"emm-admin"}) + @Permission(scope = "roles:add", roles = {"admin"}) Response addRole( @ApiParam( name = "role", @@ -332,7 +332,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", roles = {"emm-admin"}) + @Permission(scope = "roles:modify", roles = {"admin"}) Response updateRole( @ApiParam( name = "roleName", @@ -369,7 +369,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", roles = {"emm-admin"}) + @Permission(scope = "roles:modify", roles = {"admin"}) Response deleteRole( @ApiParam( name = "roleName", @@ -427,7 +427,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles-modify", roles = {"emm-admin"}) + @Permission(scope = "roles:modify", roles = {"admin"}) 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/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 508820e7e4..8b102458ad 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 @@ -74,7 +74,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Permission(scope = "application-modify", roles = {"emm-admin"}) + @Permission(scope = "application:install", roles = {"admin"}) Response installApplication( @ApiParam( name = "applicationWrapper", @@ -113,7 +113,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Permission(scope = "application-modify", roles = {"emm-admin"}) + @Permission(scope = "application:uninstall", roles = {"admin"}) 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 7ae98c4d31..21fe80e3ed 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 @@ -84,7 +84,7 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission(scope = "device-view", roles = {"emm-admin"}) + @Permission(scope = "device:view", roles = {"admin"}) Response getDevicesByName( @ApiParam( name = "name", 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 51157551d2..85072428e8 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 @@ -67,7 +67,7 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", roles = {"emm-admin"}) + @Permission(scope = "user:modify", roles = {"admin"}) Response resetUserPassword( @ApiParam( name = "username", From ff82accb48d31d82e72ca05014ff9d4bdedb4170 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 4 Jul 2016 14:11:51 +0530 Subject: [PATCH 03/21] added scopes to notification API --- .../mgt/jaxrs/service/api/NotificationManagementService.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 b85c6a3549..442d58d5e1 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 @@ -142,9 +142,7 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Permission( - scope = "", - permissions = { "" } + @Permission(scope = "notification:modify", roles = {"admin"} ) Response updateNotificationStatus( @ApiParam( From aa6085ac8c93e8738611da620722868d9e85c877 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 4 Jul 2016 18:01:42 +0530 Subject: [PATCH 04/21] Added scopes to APIs --- .../org.wso2.carbon.certificate.mgt.api/pom.xml | 2 +- .../pom.xml | 4 ++-- .../api/CertificateManagementAdminService.java | 13 +++++++++---- .../api/NotificationManagementService.java | 3 +-- .../jaxrs/service/api/RoleManagementService.java | 14 +++++++------- .../jaxrs/service/api/UserManagementService.java | 16 ++++++++-------- .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- 8 files changed, 30 insertions(+), 26 deletions(-) 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 593be353ed..d6dd156a35 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 @@ -79,7 +79,7 @@ - + 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 bef88ced39..ba723c77f8 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 @@ -48,7 +48,7 @@ maven-war-plugin WEB-INF/lib/*cxf*.jar - api#certificate-mgt#v1.0 + api-certificate-mgt-v1.0 @@ -75,7 +75,7 @@ - + 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 d69b3987c5..644b85f659 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,6 +1,7 @@ package org.wso2.carbon.certificate.mgt.cert.jaxrs.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.certificate.mgt.cert.jaxrs.api.beans.CertificateList; import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate; @@ -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-device-mgt-android-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", roles = {"admin"}) + @Permission(scope = "certificate:add", roles = {"admin"}) 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", roles = {"emm-admin"}) + @Permission(scope = "certificate:view", roles = {"admin"}) 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", roles = {"emm-admin"}) + @Permission(scope = "certificate:view", roles = {"admin"}) 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", roles = {"emm-admin"}) + @Permission(scope = "certificate:modify", roles = {"admin"}) Response removeCertificate( @ApiParam( name = "serialNumber", 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 442d58d5e1..9ba7895093 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 @@ -142,8 +142,7 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Permission(scope = "notification:modify", roles = {"admin"} - ) + @Permission(scope = "notification:view", roles = {"admin"}) Response updateNotificationStatus( @ApiParam( name = "id", 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 cef486e935..7f770c5fc0 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 @@ -77,7 +77,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) - @Permission(scope = "roles:list", roles = {"admin"}) + @Permission(scope = "role:list", roles = {"admin"}) Response getRoles( @ApiParam( name = "filter", @@ -159,7 +159,7 @@ 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", roles = {"admin"}) + @Permission(scope = "role:view", roles = {"admin"}) Response getPermissionsOfRole( @ApiParam( name = "roleName", @@ -222,7 +222,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @Permission(scope = "roles:view", roles = {"admin"}) + @Permission(scope = "role:view", roles = {"admin"}) Response getRole( @ApiParam( name = "roleName", @@ -282,7 +282,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @Permission(scope = "roles:add", roles = {"admin"}) + @Permission(scope = "role:add", roles = {"admin"}) Response addRole( @ApiParam( name = "role", @@ -332,7 +332,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles:modify", roles = {"admin"}) + @Permission(scope = "role:modify", roles = {"admin"}) Response updateRole( @ApiParam( name = "roleName", @@ -369,7 +369,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles:modify", roles = {"admin"}) + @Permission(scope = "role:modify", roles = {"admin"}) Response deleteRole( @ApiParam( name = "roleName", @@ -427,7 +427,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @Permission(scope = "roles:modify", roles = {"admin"}) + @Permission(scope = "role:add", roles = {"admin"}) 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 25faccb5e1..0886dde7dd 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 @@ -82,7 +82,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while adding a new user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", roles = {"emm-admin"}) + @Permission(scope = "user:add", roles = {"admin"}) Response addUser( @ApiParam( name = "user", @@ -134,7 +134,7 @@ public interface UserManagementService { " fetching the requested user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", roles = {"emm-admin"}) + @Permission(scope = "user:view", roles = {"admin"}) Response getUser( @ApiParam( name = "username", @@ -191,7 +191,7 @@ public interface UserManagementService { "Server error occurred while updating the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", roles = {"emm-admin"}) + @Permission(scope = "user:modify", roles = {"admin"}) Response updateUser( @ApiParam( name = "username", @@ -226,7 +226,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Permission(scope = "user-modify", roles = {"emm-admin"}) + @Permission(scope = "user:modify", roles = {"admin"}) Response removeUser( @ApiParam(name = "username", value = "Username of the user to be deleted.", required = true) @PathParam("username") String username); @@ -275,7 +275,7 @@ public interface UserManagementService { " assigned to the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", roles = {"emm-admin"}) + @Permission(scope = "user:view", roles = {"admin"}) Response getRolesOfUser( @ApiParam(name = "username", value = "Username of the user.", required = true) @PathParam("username") String username); @@ -318,7 +318,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", roles = {"emm-admin"}) + @Permission(scope = "user:list", roles = {"admin"}) Response getUsers( @ApiParam( name = "filter", @@ -385,7 +385,7 @@ public interface UserManagementService { "list that matches the given filter.", response = ErrorResponse.class) }) - @Permission(scope = "user-view", roles = {"emm-admin"}) + @Permission(scope = "user:view", roles = {"admin"}) Response getUserNames( @ApiParam( name = "filter", @@ -439,7 +439,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user-modify", roles = {"emm-admin"}) + @Permission(scope = "user:modify", roles = {"admin"}) Response resetPassword( @ApiParam( name = "username", diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 4726e13d2d..3615c1bb77 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -59,7 +59,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - api#certificate-mgt#v1.0.war + api-certificate-mgt-v1.0.war diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf index b9e7e512bc..5b68eb9ab8 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf @@ -1,2 +1,2 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api#certificate-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#certificate-mgt#v1.0.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api-certificate-mgt-v1.0.war,target:${installFolder}/../../deployment/server/webapps/api-certificate-mgt-v1.0.war,overwrite:true);\ \ No newline at end of file From d3982c9797ef5ecd62fd3f902409abaeca294175 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 4 Jul 2016 19:26:15 +0530 Subject: [PATCH 05/21] Modified API definitions --- .../mgt/cert/jaxrs/api/CertificateManagementAdminService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 644b85f659..f7d1eaf61d 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 @@ -13,7 +13,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @API(name = "Certificate Management", version = "1.0.0", - context = "api-device-mgt-android-v1.0/admin/certificates", + context = "api-certificate-mgt-v1.0/admin/certificates", tags = {"devicemgt_admin"}) @Api(value = "Certificate Management", description = "This API carries all certificate management related operations " + From 789086a667c42688dd9d2c5db4d1887739fe9825 Mon Sep 17 00:00:00 2001 From: mharindu Date: Tue, 12 Jul 2016 01:31:35 +0530 Subject: [PATCH 06/21] Changed context paths --- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- .../jaxrs/swagger/extension/SecurityDefinitionConfigurator.java | 2 +- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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/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/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 1b128fb450..a1b9a5eaf3 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 @@ -57,7 +57,7 @@ - + From 186432e1df88573debfb4e74d3bcc469853355e5 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 18 Jul 2016 20:08:51 +0530 Subject: [PATCH 07/21] Fixed webapp name resolving issue --- .../lifecycle/util/AnnotationProcessor.java | 2 +- .../ExtendedFileProtocolIteratorFactory.java | 34 +++++++ .../util/ExtendedIteratorFactory.java | 51 ++++++++++ .../pom.xml | 4 +- .../CertificateManagementAdminService.java | 2 +- .../org.wso2.carbon.device.mgt.api/pom.xml | 4 +- .../api/ActivityInfoProviderService.java | 2 +- .../api/ConfigurationManagementService.java | 2 +- .../service/api/DeviceManagementService.java | 2 +- .../api/NotificationManagementService.java | 2 +- .../service/api/PolicyManagementService.java | 2 +- .../service/api/RoleManagementService.java | 2 +- .../service/api/UserManagementService.java | 2 +- .../ApplicationManagementAdminService.java | 2 +- .../admin/DeviceManagementAdminService.java | 2 +- .../admin/DeviceTypeManagementService.java | 2 +- .../api/admin/UserManagementAdminService.java | 2 +- .../permission/AnnotationProcessor.java | 2 +- .../permission/ExtendedAnnotationDB.java | 92 +++++++++++++++++++ .../ExtendedFileProtocolIteratorFactory.java | 32 +++++++ .../permission/ExtendedIteratorFactory.java | 54 +++++++++++ .../operation/mgt/OperationManagerImpl.java | 2 +- .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- .../pom.xml | 2 +- .../src/main/resources/p2.inf | 2 +- 26 files changed, 286 insertions(+), 23 deletions(-) create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java 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 7de4b6569b..0181ed8179 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 @@ -81,7 +81,7 @@ public class AnnotationProcessor { * @throws IOException */ public Set scanStandardContext(String className) throws IOException { - AnnotationDB db = new AnnotationDB(); + ExtendedAnnotationDB db = new ExtendedAnnotationDB(); db.addIgnoredPackages(PACKAGE_ORG_APACHE); db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java new file mode 100644 index 0000000000..34936f61c8 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedFileProtocolIteratorFactory.java @@ -0,0 +1,34 @@ +/* +* 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.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.archiveiterator.*; + +import java.io.File; +import java.io.IOException; +import java.net.URL; + +public class ExtendedFileProtocolIteratorFactory implements DirectoryIteratorFactory { + + private static final String ENCODING_SCHEME = "UTF-8"; + + @Override + public StreamIterator create(URL url, Filter filter) throws IOException { + File f = new File(java.net.URLDecoder.decode(url.getPath(), ENCODING_SCHEME)); + return f.isDirectory()?new FileIterator(f, filter):new JarIterator(url.openStream(), filter); + } + +} 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 new file mode 100644 index 0000000000..bbe24a33d6 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java @@ -0,0 +1,51 @@ +/* +* 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.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.archiveiterator.*; + +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/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 ef7e43ce4b..803d3bd954 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 @@ -46,7 +46,7 @@ maven-war-plugin WEB-INF/lib/*cxf*.jar - api-certificate-mgt-v1.0 + api#certificate-mgt#v1.0 @@ -72,7 +72,7 @@ - + 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 f7d1eaf61d..30584c92e5 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 @@ -13,7 +13,7 @@ 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", + context = "api/certificate-mgt/v1.0/admin/certificates", tags = {"devicemgt_admin"}) @Api(value = "Certificate Management", description = "This API carries all certificate management related operations " + 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 e6399a2500..0876d99c1f 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 @@ -46,7 +46,7 @@ maven-war-plugin WEB-INF/lib/*cxf*.jar - api-device-mgt-v1.0 + api#device-mgt#v1.0 @@ -72,7 +72,7 @@ - + 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 bb1320938a..16d05265c9 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 @@ -32,7 +32,7 @@ import javax.ws.rs.core.Response; /** * Activity related REST-API implementation. */ -@API(name = "Activity Info Provider", version = "1.0.0", context = "/api-device-mgt-v1.0/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 " + 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 32fa08fd96..d4cb218fdb 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 @@ -31,7 +31,7 @@ import javax.ws.rs.core.Response; /** * General Tenant Configuration REST-API. */ -@API(name = "Configuration Management", version = "1.0.0", context = "/api-device-mgt-v1.0/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 " + 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 0b0543e9d8..c758b9b82b 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 @@ -38,7 +38,7 @@ import javax.ws.rs.core.Response; /** * Device related REST-API. This can be used to manipulated device related details. */ -@API(name = "Device Management", version = "1.0.0", context = "/api-device-mgt-v1.0/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 " + 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 7767a9f0a7..914729f297 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 @@ -34,7 +34,7 @@ import javax.ws.rs.core.Response; /** * Notifications related REST-API. */ -@API(name = "Device Notification Management", version = "1.0.0", context = "/api-device-mgt-v1.0/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") 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 edd6ea4c8f..abd07511f2 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 @@ -35,7 +35,7 @@ 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", +@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 " + 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 7f770c5fc0..3541600c6c 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 @@ -31,7 +31,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; -@API(name = "Role Management", version = "1.0.0", context = "/api-device-mgt-v1.0/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.") 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 4825f1a405..b54190e8e9 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 @@ -29,7 +29,7 @@ import javax.ws.rs.core.Response; import java.util.List; -@API(name = "User Management", version = "1.0.0", context = "/api-device-mgt-v1.0/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.") 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 8b102458ad..17a8ef220f 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 @@ -32,7 +32,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API(name = "Application Management Admin", version = "1.0.0", context = "/api-device-mgt-v1.0/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 " + 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 21fe80e3ed..8e1886819f 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 @@ -28,7 +28,7 @@ import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -@API(name = "Device Management Admin", version = "1.0.0", context = "/api-device-mgt-v1.0/admin/devices", +@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 " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java index 2447e2c97c..958c634bb4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java @@ -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("/admin/device-types") @Api(value = "Device Type Management", description = "This API corresponds to all tasks related to device " + 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 85072428e8..23c0aa3f07 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 @@ -28,7 +28,7 @@ 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"}) +@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) 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 index 6e7fa12c71..a847255a6e 100644 --- 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 @@ -74,7 +74,7 @@ public class AnnotationProcessor { * @throws IOException */ public Set scanStandardContext(String className) throws IOException { - AnnotationDB db = new AnnotationDB(); + ExtendedAnnotationDB db = new ExtendedAnnotationDB(); db.addIgnoredPackages(PACKAGE_ORG_APACHE); db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS); db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK); 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/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java index e0df04dfee..d60e60d097 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java @@ -115,7 +115,7 @@ public class OperationManagerImpl implements OperationManager { org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING, org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.REPEATED); } - operationMappingDAO.addOperationMapping(operationId, device.getId()); + operationMappingDAO.addOperationMapping(operationId, device.getEnrolmentInfo().getId()); if (notificationStrategy != null) { try { notificationStrategy.execute(new NotificationContext(deviceId, operation)); diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml index 1113d595ff..b76c8a7462 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/pom.xml @@ -57,7 +57,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - api-certificate-mgt-v1.0.war + api#certificate-mgt#v1.0.war diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf index 5b68eb9ab8..b9e7e512bc 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api.feature/src/main/resources/p2.inf @@ -1,2 +1,2 @@ instructions.configure = \ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api-certificate-mgt-v1.0.war,target:${installFolder}/../../deployment/server/webapps/api-certificate-mgt-v1.0.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.certificate.mgt.cert.admin.api_${feature.version}/webapps/api#certificate-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#certificate-mgt#v1.0.war,overwrite:true);\ \ No newline at end of file diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml index 9d6f5a474b..628f54c55e 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/pom.xml @@ -57,7 +57,7 @@ ${project.build.directory}/maven-shared-archive-resources/webapps - api-device-mgt-v1.0.war + api#device-mgt#v1.0.war diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf index 032e7e18c8..e0423d3cc3 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf +++ b/features/device-mgt/org.wso2.carbon.device.mgt.api.feature/src/main/resources/p2.inf @@ -1,3 +1,3 @@ instructions.configure = \ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ -org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/api-device-mgt-v1.0.war,target:${installFolder}/../../deployment/server/webapps/api-device-mgt-v1.0.war,overwrite:true);\ \ No newline at end of file +org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.api_${feature.version}/webapps/api#device-mgt#v1.0.war,target:${installFolder}/../../deployment/server/webapps/api#device-mgt#v1.0.war,overwrite:true);\ \ No newline at end of file From 9932f061fb751ba41f5e5689c2f46d69453ab4bc Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 18 Jul 2016 20:09:16 +0530 Subject: [PATCH 08/21] Fixed webapp name resolving issue --- .../lifecycle/util/ExtendedAnnotationDB.java | 93 +++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java new file mode 100644 index 0000000000..6a9949b51f --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedAnnotationDB.java @@ -0,0 +1,93 @@ +/* +* 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.apimgt.webapp.publisher.lifecycle.util; + +import org.scannotation.AnnotationDB; +import org.scannotation.archiveiterator.Filter; +import org.scannotation.archiveiterator.IteratorFactory; +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; + } + } +} From 7f1e2fdf0b7c5d91f61e6f29fc2f03deac4b6088 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 21 Jul 2016 12:43:21 +0530 Subject: [PATCH 09/21] Implemented scope management service --- .../device/mgt/jaxrs/beans/RoleInfo.java | 31 ++-- .../service/api/RoleManagementService.java | 77 ++++++++-- .../impl/RoleManagementServiceImpl.java | 145 ++++++++---------- .../impl/util/RequestValidationUtil.java | 9 ++ .../mgt/jaxrs/util/DeviceMgtAPIUtils.java | 11 ++ .../org.wso2.carbon.device.mgt.common/pom.xml | 4 + .../scope/mgt/ScopeManagementException.java | 57 +++++++ .../scope/mgt/ScopeManagementService.java | 45 ++++++ .../internal/DeviceManagementDataHolder.java | 11 ++ .../DeviceManagementServiceComponent.java | 25 ++- .../scope/mgt/ScopeManagementServiceImpl.java | 78 ++++++++++ .../scope/mgt/dao/ScopeManagementDAO.java | 46 ++++++ .../mgt/dao/ScopeManagementDAOException.java | 57 +++++++ .../mgt/dao/ScopeManagementDAOFactory.java | 139 +++++++++++++++++ .../scope/mgt/dao/ScopeManagementDAOUtil.java | 57 +++++++ .../mgt/dao/impl/ScopeManagementDAOImpl.java | 96 ++++++++++++ 16 files changed, 765 insertions(+), 123 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java 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..82b6fd92f6 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,27 +20,23 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.apimgt.api.model.Scope; 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.") 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[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 +46,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 +62,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/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 3541600c6c..eb88e928c4 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 @@ -21,6 +21,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.api.model.Scope; 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; @@ -106,16 +107,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" ) @@ -123,7 +124,7 @@ public interface RoleManagementService { value = { @ApiResponse( code = 200, - message = "OK. \n Successfully fetched the permission list of the given role.", + message = "OK. \n Successfully fetched the scopes list.", response = UIPermissionNode.class, responseContainer = "List", responseHeaders = { @@ -159,19 +160,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 = "role:view", roles = {"admin"}) - Response getPermissionsOfRole( - @ApiParam( - name = "roleName", - value = "Name of the role.", - required = true) - @PathParam("roleName") String roleName, + @Permission(scope = "role:scope:read", roles = {"admin"}) + 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) + }) + @Permission(scope = "role:scope:write", roles = {"admin"}) + Response updateScopes( + @ApiParam( + name = "Scopes", + value = "List of scopes to be updated", + required = true) List scopes); + @GET @Path("/{roleName}") @ApiOperation( @@ -375,7 +420,11 @@ public interface RoleManagementService { 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") 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 4e788411e3..71eacf935a 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 @@ -21,7 +21,10 @@ 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.apimgt.api.model.Scope; 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; @@ -79,64 +82,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 = 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(scopes); } + return Response.status(Response.Status.OK).entity(scopes).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 @@ -151,7 +137,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 '" + @@ -159,16 +144,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( @@ -176,35 +154,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( @@ -260,14 +221,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(roleInfo.getScopes()); } } //TODO: Need to send the updated role information in the entity back to the client @@ -278,14 +237,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(); @@ -303,12 +269,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(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/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..e8ebe64ac4 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,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; +import org.wso2.carbon.apimgt.api.model.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; @@ -312,4 +313,12 @@ 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()); + } + } + } 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.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml index d8950c54e6..74c922ebdd 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 @@ -68,6 +68,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/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..3066d059d7 --- /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,45 @@ +/* +* 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; + +} 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..834eefb5b1 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(); @@ -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/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..3908abef77 --- /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,78 @@ +/* +* 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 adding scopes to database.", e); + } catch (ScopeManagementDAOException e) { + throw new ScopeManagementException("Error occurred while adding scopes to database.", e); + } finally { + ScopeManagementDAOFactory.closeConnection(); + } + return scopes; + } + +} 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..b39be499d5 --- /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,46 @@ +/* +* 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; + +} 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..354e94ff5a --- /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,96 @@ +/* +* 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(); + + if (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); + } + } + + private Connection getConnection() throws SQLException { + return ScopeManagementDAOFactory.getConnection(); + } + +} From b3d309583d045afb4f25d4c2bc8e7dcc755451b1 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 21 Jul 2016 20:13:38 +0530 Subject: [PATCH 10/21] Fixed issues in scope service --- .../org.wso2.carbon.device.mgt.api/pom.xml | 14 +++++---- .../device/mgt/jaxrs/beans/RoleInfo.java | 4 +-- .../service/api/RoleManagementService.java | 5 ++-- .../impl/RoleManagementServiceImpl.java | 23 +++++++-------- .../impl/util/RequestValidationUtil.java | 2 +- .../device/mgt/jaxrs/util/DeviceMgtUtil.java | 29 +++++++++++++++++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- .../org.wso2.carbon.device.mgt.common/pom.xml | 1 + .../mgt/dao/impl/ScopeManagementDAOImpl.java | 2 +- 9 files changed, 56 insertions(+), 26 deletions(-) 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..dd7de5aca2 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,17 +240,18 @@ org.wso2.carbon.devicemgt org.wso2.carbon.apimgt.annotations + provided org.wso2.carbon.devicemgt org.wso2.carbon.device.mgt.analytics.dashboard provided - - com.fasterxml.jackson.core - jackson-annotations - provided - + + + + + 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 82b6fd92f6..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,8 +20,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.apimgt.api.model.Scope; -import org.wso2.carbon.user.mgt.common.UIPermissionNode; import java.util.List; @@ -32,7 +30,7 @@ public class RoleInfo { @ApiModelProperty(name = "roleName", value = "The name of the role.", required = true) private String roleName; @ApiModelProperty(name = "scopes", value = "Lists out all the scopes associated with roles.", - required = true, dataType = "List[Scope]") + 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]") 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 eb88e928c4..f70073dcdf 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 @@ -21,11 +21,10 @@ 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.api.model.Scope; 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; @@ -125,7 +124,7 @@ public interface RoleManagementService { @ApiResponse( code = 200, message = "OK. \n Successfully fetched the scopes list.", - response = UIPermissionNode.class, + response = List.class, responseContainer = "List", responseHeaders = { @ResponseHeader( 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 71eacf935a..b3dd4a98e3 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,23 +20,22 @@ 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.apimgt.api.model.Scope; -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.mgt.UserRealmProxy; -import org.wso2.carbon.user.mgt.common.UIPermissionNode; -import org.wso2.carbon.user.mgt.common.UserAdminException; +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 javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -93,7 +92,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (scopeManagementService == null) { log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); } else { - scopes = scopeManagementService.getAllScopes(); + scopes = DeviceMgtUtil.convertAPIScopestoScopes(scopeManagementService.getAllScopes()); } return Response.status(Response.Status.OK).entity(scopes).build(); } catch (ScopeManagementException e) { @@ -114,9 +113,9 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (scopeManagementService == null) { log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); } else { - scopeManagementService.updateScopes(scopes); + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(scopes)); } - return Response.status(Response.Status.OK).entity(scopes).build(); + 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); @@ -226,7 +225,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (scopeManagementService == null) { log.error("Scope management service initialization is failed, hence scopes will not be updated"); } else { - scopeManagementService.updateScopes(roleInfo.getScopes()); + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(roleInfo.getScopes())); } } //TODO: Need to send the updated role information in the entity back to the client @@ -274,7 +273,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { if (scopeManagementService == null) { log.error("Scope management service initialization is failed, hence scopes will not be updated"); } else { - scopeManagementService.updateScopes(roleInfo.getScopes()); + scopeManagementService.updateScopes(DeviceMgtUtil.convertScopestoAPIScopes(roleInfo.getScopes())); } return Response.status(Response.Status.OK).build(); 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 e8ebe64ac4..a3b503640f 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,7 +18,7 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; -import org.wso2.carbon.apimgt.api.model.Scope; +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; 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..f9902fbe53 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,6 +18,7 @@ package org.wso2.carbon.device.mgt.jaxrs.util; +import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature; import org.wso2.carbon.policy.mgt.common.Profile; @@ -58,4 +59,32 @@ 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; + } } \ No newline at end of file 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 a1b9a5eaf3..1b128fb450 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 @@ -57,7 +57,7 @@ - + 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 74c922ebdd..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 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 index 354e94ff5a..8ac862b799 100644 --- 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 @@ -73,7 +73,7 @@ public class ScopeManagementDAOImpl implements ScopeManagementDAO { stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); - if (rs.next()) { + while (rs.next()) { scope = new Scope(); scope.setKey(rs.getString("SCOPE_KEY")); scope.setName(rs.getString("NAME")); From 827567733c9bd9e7a496da26d6285b36f3b40398 Mon Sep 17 00:00:00 2001 From: mharindu Date: Fri, 22 Jul 2016 16:41:40 +0530 Subject: [PATCH 11/21] Fixed scope update issue in API update --- .../pom.xml | 4 ++ .../webapp/publisher/APIPublisherUtil.java | 50 +++++++++++++++---- .../webapp/publisher/WebappPublisherUtil.java | 41 +++++++++++++++ .../scope/mgt/ScopeManagementService.java | 8 +++ .../scope/mgt/ScopeManagementServiceImpl.java | 23 ++++++++- .../scope/mgt/dao/ScopeManagementDAO.java | 8 +++ .../mgt/dao/impl/ScopeManagementDAOImpl.java | 25 ++++++++++ 7 files changed, 147 insertions(+), 12 deletions(-) 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..4080429141 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,6 +29,10 @@ 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.*; @@ -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 @@ -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/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 index 3066d059d7..b90011aaf0 100644 --- 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 @@ -42,4 +42,12 @@ public interface ScopeManagementService { */ 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/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 index 3908abef77..59418e760f 100644 --- 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 @@ -66,13 +66,32 @@ public class ScopeManagementServiceImpl implements ScopeManagementService { ScopeManagementDAOFactory.openConnection(); scopes = scopeManagementDAO.getAllScopes(); } catch (SQLException e) { - throw new ScopeManagementException("SQL error occurred while adding scopes to database.", e); + throw new ScopeManagementException("SQL error occurred while retrieving scopes from database.", e); } catch (ScopeManagementDAOException e) { - throw new ScopeManagementException("Error occurred while adding scopes to database.", 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 index b39be499d5..38517f6c4e 100644 --- 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 @@ -43,4 +43,12 @@ public interface ScopeManagementDAO { */ 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/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 index 8ac862b799..7e46392446 100644 --- 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 @@ -89,6 +89,31 @@ public class ScopeManagementDAOImpl implements ScopeManagementDAO { } } + @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(); } From 6e742ee6ac2c843921de9590739076c9a4734f2a Mon Sep 17 00:00:00 2001 From: mharindu Date: Tue, 26 Jul 2016 16:40:04 +0530 Subject: [PATCH 12/21] Added scope beans --- .../carbon/device/mgt/jaxrs/beans/Scope.java | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java 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; + } + +} From 4dc0e23f8d464ffbef27240bbb743ac8f06d435f Mon Sep 17 00:00:00 2001 From: mharindu Date: Fri, 29 Jul 2016 12:44:51 +0530 Subject: [PATCH 13/21] Added license file to features --- features/etc/feature.properties | 241 ++++++++++++++++++++++++++++++++ 1 file changed, 241 insertions(+) create mode 100644 features/etc/feature.properties diff --git a/features/etc/feature.properties b/features/etc/feature.properties new file mode 100644 index 0000000000..a84f4e33e9 --- /dev/null +++ b/features/etc/feature.properties @@ -0,0 +1,241 @@ +################################################################################ +# Copyright 2015 WSO2, Inc. (http://wso2.com) +# +# WSO2 Inc. 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. +################################################################################ + +providerName=WSO2 Inc. + +########################## license properties ################################## +licenseURL=http://www.apache.org/licenses/LICENSE-2.0 + +license=\ + Apache License\n\ + Version 2.0, January 2004\n\ + http://www.apache.org/licenses/\n\ +\n\ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\ +\n\ + 1. Definitions.\n\ +\n\ + "License" shall mean the terms and conditions for use, reproduction,\n\ + and distribution as defined by Sections 1 through 9 of this document.\n\ +\n\ + "Licensor" shall mean the copyright owner or entity authorized by\n\ + the copyright owner that is granting the License.\n\ +\n\ + "Legal Entity" shall mean the union of the acting entity and all\n\ + other entities that control, are controlled by, or are under common\n\ + control with that entity. For the purposes of this definition,\n\ + "control" means (i) the power, direct or indirect, to cause the\n\ + direction or management of such entity, whether by contract or\n\ + otherwise, or (ii) ownership of fifty percent (50%) or more of the\n\ + outstanding shares, or (iii) beneficial ownership of such entity.\n\ +\n\ + "You" (or "Your") shall mean an individual or Legal Entity\n\ + exercising permissions granted by this License.\n\ +\n\ + "Source" form shall mean the preferred form for making modifications,\n\ + including but not limited to software source code, documentation\n\ + source, and configuration files.\n\ +\n\ + "Object" form shall mean any form resulting from mechanical\n\ + transformation or translation of a Source form, including but\n\ + not limited to compiled object code, generated documentation,\n\ + and conversions to other media types.\n\ +\n\ + "Work" shall mean the work of authorship, whether in Source or\n\ + Object form, made available under the License, as indicated by a\n\ + copyright notice that is included in or attached to the work\n\ + (an example is provided in the Appendix below).\n\ +\n\ + "Derivative Works" shall mean any work, whether in Source or Object\n\ + form, that is based on (or derived from) the Work and for which the\n\ + editorial revisions, annotations, elaborations, or other modifications\n\ + represent, as a whole, an original work of authorship. For the purposes\n\ + of this License, Derivative Works shall not include works that remain\n\ + separable from, or merely link (or bind by name) to the interfaces of,\n\ + the Work and Derivative Works thereof.\n\ +\n\ + "Contribution" shall mean any work of authorship, including\n\ + the original version of the Work and any modifications or additions\n\ + to that Work or Derivative Works thereof, that is intentionally\n\ + submitted to Licensor for inclusion in the Work by the copyright owner\n\ + or by an individual or Legal Entity authorized to submit on behalf of\n\ + the copyright owner. For the purposes of this definition, "submitted"\n\ + means any form of electronic, verbal, or written communication sent\n\ + to the Licensor or its representatives, including but not limited to\n\ + communication on electronic mailing lists, source code control systems,\n\ + and issue tracking systems that are managed by, or on behalf of, the\n\ + Licensor for the purpose of discussing and improving the Work, but\n\ + excluding communication that is conspicuously marked or otherwise\n\ + designated in writing by the copyright owner as "Not a Contribution."\n\ +\n\ + "Contributor" shall mean Licensor and any individual or Legal Entity\n\ + on behalf of whom a Contribution has been received by Licensor and\n\ + subsequently incorporated within the Work.\n\ +\n\ + 2. Grant of Copyright License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + copyright license to reproduce, prepare Derivative Works of,\n\ + publicly display, publicly perform, sublicense, and distribute the\n\ + Work and such Derivative Works in Source or Object form.\n\ +\n\ + 3. Grant of Patent License. Subject to the terms and conditions of\n\ + this License, each Contributor hereby grants to You a perpetual,\n\ + worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n\ + (except as stated in this section) patent license to make, have made,\n\ + use, offer to sell, sell, import, and otherwise transfer the Work,\n\ + where such license applies only to those patent claims licensable\n\ + by such Contributor that are necessarily infringed by their\n\ + Contribution(s) alone or by combination of their Contribution(s)\n\ + with the Work to which such Contribution(s) was submitted. If You\n\ + institute patent litigation against any entity (including a\n\ + cross-claim or counterclaim in a lawsuit) alleging that the Work\n\ + or a Contribution incorporated within the Work constitutes direct\n\ + or contributory patent infringement, then any patent licenses\n\ + granted to You under this License for that Work shall terminate\n\ + as of the date such litigation is filed.\n\ +\n\ + 4. Redistribution. You may reproduce and distribute copies of the\n\ + Work or Derivative Works thereof in any medium, with or without\n\ + modifications, and in Source or Object form, provided that You\n\ + meet the following conditions:\n\ +\n\ + (a) You must give any other recipients of the Work or\n\ + Derivative Works a copy of this License; and\n\ +\n\ + (b) You must cause any modified files to carry prominent notices\n\ + stating that You changed the files; and\n\ +\n\ + (c) You must retain, in the Source form of any Derivative Works\n\ + that You distribute, all copyright, patent, trademark, and\n\ + attribution notices from the Source form of the Work,\n\ + excluding those notices that do not pertain to any part of\n\ + the Derivative Works; and\n\ +\n\ + (d) If the Work includes a "NOTICE" text file as part of its\n\ + distribution, then any Derivative Works that You distribute must\n\ + include a readable copy of the attribution notices contained\n\ + within such NOTICE file, excluding those notices that do not\n\ + pertain to any part of the Derivative Works, in at least one\n\ + of the following places: within a NOTICE text file distributed\n\ + as part of the Derivative Works; within the Source form or\n\ + documentation, if provided along with the Derivative Works; or,\n\ + within a display generated by the Derivative Works, if and\n\ + wherever such third-party notices normally appear. The contents\n\ + of the NOTICE file are for informational purposes only and\n\ + do not modify the License. You may add Your own attribution\n\ + notices within Derivative Works that You distribute, alongside\n\ + or as an addendum to the NOTICE text from the Work, provided\n\ + that such additional attribution notices cannot be construed\n\ + as modifying the License.\n\ +\n\ + You may add Your own copyright statement to Your modifications and\n\ + may provide additional or different license terms and conditions\n\ + for use, reproduction, or distribution of Your modifications, or\n\ + for any such Derivative Works as a whole, provided Your use,\n\ + reproduction, and distribution of the Work otherwise complies with\n\ + the conditions stated in this License.\n\ +\n\ + 5. Submission of Contributions. Unless You explicitly state otherwise,\n\ + any Contribution intentionally submitted for inclusion in the Work\n\ + by You to the Licensor shall be under the terms and conditions of\n\ + this License, without any additional terms or conditions.\n\ + Notwithstanding the above, nothing herein shall supersede or modify\n\ + the terms of any separate license agreement you may have executed\n\ + with Licensor regarding such Contributions.\n\ +\n\ + 6. Trademarks. This License does not grant permission to use the trade\n\ + names, trademarks, service marks, or product names of the Licensor,\n\ + except as required for reasonable and customary use in describing the\n\ + origin of the Work and reproducing the content of the NOTICE file.\n\ +\n\ + 7. Disclaimer of Warranty. Unless required by applicable law or\n\ + agreed to in writing, Licensor provides the Work (and each\n\ + Contributor provides its Contributions) on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n\ + implied, including, without limitation, any warranties or conditions\n\ + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n\ + PARTICULAR PURPOSE. You are solely responsible for determining the\n\ + appropriateness of using or redistributing the Work and assume any\n\ + risks associated with Your exercise of permissions under this License.\n\ +\n\ + 8. Limitation of Liability. In no event and under no legal theory,\n\ + whether in tort (including negligence), contract, or otherwise,\n\ + unless required by applicable law (such as deliberate and grossly\n\ + negligent acts) or agreed to in writing, shall any Contributor be\n\ + liable to You for damages, including any direct, indirect, special,\n\ + incidental, or consequential damages of any character arising as a\n\ + result of this License or out of the use or inability to use the\n\ + Work (including but not limited to damages for loss of goodwill,\n\ + work stoppage, computer failure or malfunction, or any and all\n\ + other commercial damages or losses), even if such Contributor\n\ + has been advised of the possibility of such damages.\n\ +\n\ + 9. Accepting Warranty or Additional Liability. While redistributing\n\ + the Work or Derivative Works thereof, You may choose to offer,\n\ + and charge a fee for, acceptance of support, warranty, indemnity,\n\ + or other liability obligations and/or rights consistent with this\n\ + License. However, in accepting such obligations, You may act only\n\ + on Your own behalf and on Your sole responsibility, not on behalf\n\ + of any other Contributor, and only if You agree to indemnify,\n\ + defend, and hold each Contributor harmless for any liability\n\ + incurred by, or claims asserted against, such Contributor by reason\n\ + of your accepting any such warranty or additional liability.\n\ +\n\ + END OF TERMS AND CONDITIONS\n\ +\n\ + APPENDIX: How to apply the Apache License to your work.\n\ +\n\ + To apply the Apache License to your work, attach the following\n\ + boilerplate notice, with the fields enclosed by brackets "[]"\n\ + replaced with your own identifying information. (Don't include\n\ + the brackets!) The text should be enclosed in the appropriate\n\ + comment syntax for the file format. We also recommend that a\n\ + file or class name and description of purpose be included on the\n\ + same "printed page" as the copyright notice for easier\n\ + identification within third-party archives.\n\ +\n\ + Copyright [yyyy] [name of copyright owner]\n\ +\n\ + Licensed under the Apache License, Version 2.0 (the "License");\n\ + you may not use this file except in compliance with the License.\n\ + You may obtain a copy of the License at\n\ +\n\ + http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ + Unless required by applicable law or agreed to in writing, software\n\ + distributed under the License is distributed on an "AS IS" BASIS,\n\ + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ + See the License for the specific language governing permissions and\n\ + limitations under the License.\n + +######################### copyright properties ################################# +copyrightURL=TODO + +copyright=\ +Copyright (c) WSO2 Inc. (http://wso2.com)\n\ +\n\ +WSO2 Inc. Licensed under the Apache License, Version 2.0 (the "License");\n\ +you may not use this file except in compliance with the License.\n\ +You may obtain a copy of the License at\n\ +\n\ +http://www.apache.org/licenses/LICENSE-2.0\n\ +\n\ +Unless required by applicable law or agreed to in writing, software\n\ +distributed under the License is distributed on an "AS IS" BASIS,\n\ +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\ +See the License for the specific language governing permissions and\n\ +limitations under the License.\n From ed4c762bfd3f61f19af4936b333a8d68beda21c5 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 4 Aug 2016 17:46:46 +0530 Subject: [PATCH 14/21] Refactored scopes --- .../api/{Permission.java => Scope.java} | 16 +++- .../config/PermissionConfiguration.java | 45 --------- .../config/PermissionManagementException.java | 60 ------------ .../lifecycle/util/AnnotationProcessor.java | 51 ++++------- .../lifecycle/util/PermissionUtils.java | 91 ------------------- .../mgt/jaxrs/api/CertificateMgtService.java | 4 +- .../CertificateManagementAdminService.java | 10 +- .../api/ActivityInfoProviderService.java | 6 +- .../api/ConfigurationManagementService.java | 6 +- .../service/api/DeviceManagementService.java | 17 ++-- .../service/api/GroupManagementService.java | 2 +- .../api/NotificationManagementService.java | 8 +- .../service/api/PolicyManagementService.java | 22 ++--- .../service/api/RoleManagementService.java | 17 ++-- .../service/api/UserManagementService.java | 20 ++-- .../ApplicationManagementAdminService.java | 6 +- .../admin/DeviceManagementAdminService.java | 4 +- .../admin/DeviceTypeManagementService.java | 4 +- .../admin/GroupManagementAdminService.java | 2 +- .../api/admin/UserManagementAdminService.java | 4 +- .../impl/util/RequestValidationUtil.java | 8 ++ 21 files changed, 103 insertions(+), 300 deletions(-) rename components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/{Permission.java => Scope.java} (80%) delete mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java delete mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java delete mode 100644 components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java 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 bc771b72c7..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[] roles(); + String 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/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java deleted file mode 100644 index 81a722e5ff..0000000000 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.wso2.carbon.apimgt.webapp.publisher.config; - -/** - * This class represents the information related to permissions. - */ -public class PermissionConfiguration { - - private String scopeName; - private String[] roles; - - public String getScopeName() { - return scopeName; - } - - public void setScopeName(String scope) { - this.scopeName = scope; - } - - public String[] getRoles() { - return roles; - } - - public void setRoles(String[] roles) { - this.roles = roles; - } - -} 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 72a1209448..ab213e8080 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 @@ -23,13 +23,9 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.*; @@ -242,15 +238,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.getRoles(), ","); - 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); } } @@ -348,35 +338,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 "roles": - String roles[] = invokeMethod(method, permissionAnnotation); - this.addPermission(roles); - permissionConf.setRoles(roles); + 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/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/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 d4b1d3e6da..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", roles = {"emm-admin"}) + @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/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 30584c92e5..226cc53710 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 @@ -2,7 +2,7 @@ package org.wso2.carbon.certificate.mgt.cert.jaxrs.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.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; @@ -77,7 +77,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n Server error occurred while adding certificates.", response = ErrorResponse.class) }) - @Permission(scope = "certificate:add", roles = {"admin"}) + @Scope(key = "certificate:write", name = "Add certificates", description = "") Response addCertificate( @ApiParam( name = "enrollmentCertificates", @@ -135,7 +135,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving information requested certificate.", response = ErrorResponse.class) }) - @Permission(scope = "certificate:view", roles = {"admin"}) + @Scope(key = "certificate:read", 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", @@ -207,7 +207,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving all certificates enrolled in the system.", response = ErrorResponse.class) }) - @Permission(scope = "certificate:view", roles = {"admin"}) + @Scope(key = "certificate:read", name = "View certificates", description = "") Response getAllCertificates( @ApiParam( name = "offset", @@ -250,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", roles = {"admin"}) + @Scope(key = "certificate:write", name = "Add certificates", description = "") Response removeCertificate( @ApiParam( name = "serialNumber", 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 16d05265c9..e01511c93e 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,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.operation.mgt.Activity; import org.wso2.carbon.device.mgt.jaxrs.beans.ActivityList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -91,7 +91,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity:view", roles = {"admin"}) + @Scope(key = "activity:read", name = "View Activities", description = "") Response getActivity( @ApiParam( name = "id", @@ -150,7 +150,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Permission(scope = "activity:view", roles = {"admin"}) + @Scope(key = "activity:read", 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 d4cb218fdb..d6a2b3bad9 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; @@ -81,7 +81,7 @@ public interface ConfigurationManagementService { "platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration:view", roles = {"admin"}) + @Scope(key = "configuration:read", name = "View Configurations", description = "") Response getConfiguration( @ApiParam( name = "If-Modified-Since", @@ -127,7 +127,7 @@ public interface ConfigurationManagementService { "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) }) - @Permission(scope = "configuration:modify", roles = {"admin"}) + @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 c758b9b82b..19bc4be795 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; @@ -91,7 +91,7 @@ public interface DeviceManagementService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission(scope = "device:list", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getDevices( @ApiParam( name = "name", @@ -200,7 +200,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getDevice( @ApiParam( name = "type", @@ -280,7 +280,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getFeaturesOfDevice( @ApiParam( name = "type", @@ -354,7 +354,7 @@ public interface DeviceManagementService { "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) - @Permission(scope = "device:search", roles = {"admin" }) + @Scope(key = "device:read", name = "View Devices", description = "") Response searchDevices( @ApiParam( name = "offset", @@ -433,7 +433,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getInstalledApplications( @ApiParam( name = "type", @@ -527,7 +527,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getDeviceOperations( @ApiParam( name = "type", @@ -623,7 +623,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:read", name = "View Devices", description = "") Response getEffectivePolicyOfDevice( @ApiParam( name = "type", @@ -674,6 +674,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) + @Scope(key = "device:read", name = "View Devices", description = "") Response getComplianceDataOfDevice( @ApiParam( name = "type", 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 914729f297..f479b310c9 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,10 +20,8 @@ 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; @@ -90,7 +88,7 @@ public interface NotificationManagementService { "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) }) - @Permission(scope = "notification:view", roles = {"admin"}) + @Scope(key = "notification:read", name = "View and manage notifications", description = "") Response getNotifications( @ApiParam( name = "status", @@ -142,7 +140,7 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Permission(scope = "notification:view", roles = {"admin"}) + @Scope(key = "notification:read", name = "View and manage notifications", description = "") Response updateNotificationStatus( @ApiParam( name = "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 abd07511f2..f75857e6f8 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 @@ -20,11 +20,11 @@ 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.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.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -99,7 +99,7 @@ public interface PolicyManagementService { "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy:add", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response addPolicy( @ApiParam( name = "policy", @@ -153,7 +153,7 @@ public interface PolicyManagementService { "policies."), response = ErrorResponse.class) }) - @Permission(scope = "policy:list", roles = {"admin"}) + @Scope(key = "policy:read", name = "Views policies", description = "") Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -219,7 +219,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy:view", roles = {"admin"}) + @Scope(key = "policy:read", name = "View policies", description = "") Response getPolicy( @ApiParam( name = "id", @@ -283,7 +283,7 @@ public interface PolicyManagementService { "Server error occurred while updating the policy.", response = ErrorResponse.class) }) - @Permission(scope = "policy:modify", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response updatePolicy( @ApiParam( name = "id", @@ -329,7 +329,7 @@ public interface PolicyManagementService { "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy:modify", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response removePolicies( @ApiParam( name = "policyIds", @@ -365,7 +365,7 @@ public interface PolicyManagementService { message = "ErrorResponse in activating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy:add", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response activatePolicies( @ApiParam( name = "policyIds", @@ -401,7 +401,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy:add", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -434,7 +434,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Permission(scope = "policy:add", roles = {"admin"}) + @Scope(key = "policy:write", name = "Add policies", description = "") Response applyChanges(); @@ -463,7 +463,7 @@ public interface PolicyManagementService { message = "Exception in updating policy priorities.", response = ErrorResponse.class) }) - @Permission(scope = "policy:add", roles = {"admin"}) + @Scope(key = "policy:write", 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 f70073dcdf..73fcb77bb2 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,7 +20,6 @@ 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; @@ -77,7 +76,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) - @Permission(scope = "role:list", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") Response getRoles( @ApiParam( name = "filter", @@ -159,7 +158,7 @@ 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 = "role:scope:read", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") Response getScopes( @ApiParam( name = "If-Modified-Since", @@ -209,7 +208,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the scopes.", response = ErrorResponse.class) }) - @Permission(scope = "role:scope:write", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") Response updateScopes( @ApiParam( name = "Scopes", @@ -266,7 +265,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @Permission(scope = "role:view", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") Response getRole( @ApiParam( name = "roleName", @@ -326,7 +325,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @Permission(scope = "role:add", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") Response addRole( @ApiParam( name = "role", @@ -376,7 +375,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @Permission(scope = "role:modify", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") Response updateRole( @ApiParam( name = "roleName", @@ -413,7 +412,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @Permission(scope = "role:modify", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") Response deleteRole( @ApiParam( name = "roleName", @@ -475,7 +474,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @Permission(scope = "role:add", roles = {"admin"}) + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", 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 b54190e8e9..d90cc14b7b 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.*; @@ -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:add", roles = {"admin"}) + @Scope(key = "user:write", 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", roles = {"admin"}) + @Scope(key = "user:read", 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", roles = {"admin"}) + @Scope(key = "user:write", name = "Add users", description = "") Response updateUser( @ApiParam( name = "username", @@ -227,7 +227,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Permission(scope = "user:modify", roles = {"admin"}) + @Scope(key = "user:write", 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", roles = {"admin"}) + @Scope(key = "user:read", 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:list", roles = {"admin"}) + @Scope(key = "user:read", 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", roles = {"admin"}) + @Scope(key = "user:read", 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", roles = {"admin"}) + @Scope(key = "user:read", 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", roles = {"admin"}) + @Scope(key = "user:write", 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 17a8ef220f..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,7 +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.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.ApplicationWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -74,7 +74,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Permission(scope = "application:install", roles = {"admin"}) + @Scope(key = "application:manage", name = "Install/Uninstall applications", description = "") Response installApplication( @ApiParam( name = "applicationWrapper", @@ -113,7 +113,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Permission(scope = "application:uninstall", roles = {"admin"}) + @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 8e1886819f..e90e346eeb 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,7 +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.Permission; +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; @@ -84,7 +84,7 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Permission(scope = "device:view", roles = {"admin"}) + @Scope(key = "device:admin:read", name = "View Devices", description = "") Response getDevicesByName( @ApiParam( name = "name", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java index 958c634bb4..39970a7e5d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java @@ -20,7 +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.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; @@ -78,7 +78,7 @@ public interface DeviceTypeManagementService { response = ErrorResponse.class) } ) - @Permission(scope = "device-types:read", roles = {"admin"}) + @Scope(key = "device-type:admin:read", 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/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 23c0aa3f07..aca7e73731 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 @@ -20,7 +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.Permission; +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; @@ -67,7 +67,7 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Permission(scope = "user:modify", roles = {"admin"}) + @Scope(key = "user:admin:reset-password", name = "View users", description = "") Response resetUserPassword( @ApiParam( name = "username", 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 bf9a9e8246..6e0000ab39 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 @@ -314,6 +314,14 @@ 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( From fa0891d9a2366d3eecee5389fa3c441e3c78a150 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 8 Aug 2016 14:23:11 +0530 Subject: [PATCH 15/21] Adding Policy View UI --- .../app/pages/cdmf.page.policy.view/view.hbs | 19 +- .../app/pages/cdmf.page.policy.view/view.js | 10 +- .../app/pages/cdmf.page.policy.view/view.json | 2 +- .../cdmf.unit.policy.view/public/js/view.js | 2289 ++++++++ .../templates/hidden-operations-android.hbs | 1227 +++++ .../templates/hidden-operations-ios.hbs | 4738 +++++++++++++++++ .../templates/hidden-operations-windows.hbs | 568 ++ .../app/units/cdmf.unit.policy.view/view.hbs | 88 + .../app/units/cdmf.unit.policy.view/view.js | 25 + .../app/units/cdmf.unit.policy.view/view.json | 3 + 10 files changed, 8955 insertions(+), 14 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/js/view.js create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-android.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-ios.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-windows.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.json 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..af7a8e700a 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 @@ -16,8 +16,8 @@ * under the License. */ -function onRequest(context) { - var utility = require("/app/modules/utility.js").utility; - var deviceType = request.getParameter("type"); - return {"deviceTypePolicyView": utility.getTenantedDeviceUnitName(deviceType, "policy-view")}; -} +//function onRequest(context) { +// 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/units/cdmf.unit.policy.view/public/js/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/js/view.js new file mode 100644 index 0000000000..81f8ca13e2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/js/view.js @@ -0,0 +1,2289 @@ +/* + * 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 validateStep = {}; +var skipStep = {}; +var stepForwardFrom = {}; +var stepBackFrom = {}; +var policy = {}; +var configuredOperations = []; + +var base_api_url = "/api/device-mgt/v1.0"; + +// Constants to define platform types available +var platformTypeConstants = { + "ANDROID": "android", + "IOS": "ios", + "WINDOWS": "windows" +}; + +// Constants to define Android Operation Constants +var androidOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "CAMERA_OPERATION": "camera", + "CAMERA_OPERATION_CODE": "CAMERA", + "ENCRYPT_STORAGE_OPERATION": "encrypt-storage", + "ENCRYPT_STORAGE_OPERATION_CODE": "ENCRYPT_STORAGE", + "WIFI_OPERATION": "wifi", + "WIFI_OPERATION_CODE": "WIFI" +}; + +// Constants to define Android Operation Constants +var windowsOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "CAMERA_OPERATION": "camera", + "CAMERA_OPERATION_CODE": "CAMERA", + "ENCRYPT_STORAGE_OPERATION": "encrypt-storage", + "ENCRYPT_STORAGE_OPERATION_CODE": "ENCRYPT_STORAGE" +}; + +// Constants to define iOS Operation Constants +var iosOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "RESTRICTIONS_OPERATION": "restrictions", + "RESTRICTIONS_OPERATION_CODE": "RESTRICTION", + "WIFI_OPERATION": "wifi", + "WIFI_OPERATION_CODE": "WIFI", + "EMAIL_OPERATION": "email", + "EMAIL_OPERATION_CODE": "EMAIL", + "AIRPLAY_OPERATION": "airplay", + "AIRPLAY_OPERATION_CODE": "AIR_PLAY", + "LDAP_OPERATION": "ldap", + "LDAP_OPERATION_CODE": "LDAP", + "CALENDAR_OPERATION": "calendar", + "CALENDAR_OPERATION_CODE": "CALDAV", + "CALENDAR_SUBSCRIPTION_OPERATION": "calendar-subscription", + "CALENDAR_SUBSCRIPTION_OPERATION_CODE": "CALENDAR_SUBSCRIPTION", + "APN_OPERATION": "apn", + "APN_OPERATION_CODE": "APN", + "CELLULAR_OPERATION": "cellular", + "CELLULAR_OPERATION_CODE": "CELLULAR" +}; + +/** + * Method to update the visibility (i.e. disabled or enabled view) + * of grouped input according to the values + * that they currently possess. + * @param domElement HTML grouped-input element with class name "grouped-input" + */ +var updateGroupedInputVisibility = function (domElement) { + if ($(".parent-input:first", domElement).is(":checked")) { + if ($(".grouped-child-input:first", domElement).hasClass("disabled")) { + $(".grouped-child-input:first", domElement).removeClass("disabled"); + } + $(".child-input", domElement).each(function () { + $(this).prop('disabled', false); + }); + } else { + if (!$(".grouped-child-input:first", domElement).hasClass("disabled")) { + $(".grouped-child-input:first", domElement).addClass("disabled"); + } + $(".child-input", domElement).each(function () { + $(this).prop('disabled', true); + }); + } +}; + +skipStep["policy-platform"] = function (policyPayloadObj) { + policy["name"] = policyPayloadObj["policyName"]; + policy["platform"] = policyPayloadObj["profile"]["deviceType"]; + var userRoleInput = $("#user-roles-input"); + var ownershipInput = $("#ownership-input"); + var userInput = $("#users-select-field"); + var actionInput = $("#action-input"); + var policyNameInput = $("#policy-name-input"); + var policyDescriptionInput = $("#policy-description-input"); + userRoleInput.val(policyPayloadObj.roles); + userInput.val(policyPayloadObj.users); + ownershipInput.val(policyPayloadObj.ownershipType); + actionInput.val(policyPayloadObj.compliance); + policyNameInput.val(policyPayloadObj["policyName"]); + policyDescriptionInput.val(policyPayloadObj["description"]); + // updating next-page wizard title with selected platform + $("#policy-heading").text(policy["platform"].toUpperCase() + " POLICY - " + policy["name"].toUpperCase()); + $("#policy-platform").text(policy["platform"].toUpperCase()); + $("#policy-assignment").text(policyPayloadObj.ownershipType); + $("#policy-action").text(policyPayloadObj.compliance.toUpperCase()); + $("#policy-description").text(policyPayloadObj["description"]); + var policyStatus = "Active"; + if (policyPayloadObj["active"] == true && policyPayloadObj["updated"] == true) { + policyStatus = ' Active/Updated'; + } else if (policyPayloadObj["active"] == true && policyPayloadObj["updated"] == false) { + policyStatus = ' Active'; + } else if (policyPayloadObj["active"] == false && policyPayloadObj["updated"] == true) { + policyStatus = ' Inactive/Updated'; + } else if (policyPayloadObj["active"] == false && policyPayloadObj["updated"] == false) { + policyStatus = ' Inactive'; + } + + $("#policy-status").html(policyStatus); + + if (policyPayloadObj.users.length > 0) { + $("#policy-users").text(policyPayloadObj.users.toString().split(",").join(", ")); + } else { + $("#users-row").addClass("hidden"); + } + + if (policyPayloadObj.roles.length > 0) { + $("#policy-roles").text(policyPayloadObj.roles.toString().split(",").join(", ")); + } else { + $("#roles-row").addClass("hidden"); + } + + var deviceType = policy["platform"]; + var hiddenOperationsByDeviceType = $("#hidden-operations-" + deviceType); + var hiddenOperationsByDeviceTypeCacheKey = deviceType + "HiddenOperations"; + var hiddenOperationsByDeviceTypeSrc = hiddenOperationsByDeviceType.attr("src"); + + setTimeout( + function () { + $.template(hiddenOperationsByDeviceTypeCacheKey, hiddenOperationsByDeviceTypeSrc, function (template) { + var content = template(); + // pushing profile feature input elements + $(".wr-advance-operations").html(content); + // populating values and getting the list of configured features + var configuredOperations = operationModule. + populateProfile(policy["platform"], policyPayloadObj["profile"]["profileFeaturesList"]); + // updating grouped input visibility according to the populated values + $(".wr-advance-operations li.grouped-input").each(function () { + updateGroupedInputVisibility(this); + }); + // enabling previously configured options of last update + for (var i = 0; i < configuredOperations.length; ++i) { + var configuredOperation = configuredOperations[i]; + $(".operation-data").filterByData("operation-code", configuredOperation). + find(".panel-title .wr-input-control.switch input[type=checkbox]").each(function () { + $(this).click(); + }); + } + }); + }, + 250 // time delayed for the execution of above function, 250 milliseconds + ); +}; + +/** + * Checks if provided number is valid against a range. + * + * @param numberInput Number Input + * @param min Minimum Limit + * @param max Maximum Limit + * @returns {boolean} Returns true if input is within the specified range + */ +var inputIsValidAgainstRange = function (numberInput, min, max) { + return (numberInput == min || (numberInput > min && numberInput < max) || numberInput == max); +}; + +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param input Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +var inputIsValidAgainstRegExp = function (regExp, input) { + return regExp.test(input); +}; + +validateStep["policy-profile"] = function () { + var validationStatusArray = []; + var validationStatus; + var operation; + + // starting validation process and updating validationStatus + if (policy["platform"] == platformTypeConstants["ANDROID"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(androidOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = androidOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + var continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + var passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + var passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CAMERA + if ($.inArray(androidOperationConstants["CAMERA_OPERATION_CODE"], configuredOperations) != -1) { + // if CAMERA is configured + operation = androidOperationConstants["CAMERA_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating ENCRYPT_STORAGE + if ($.inArray(androidOperationConstants["ENCRYPT_STORAGE_OPERATION_CODE"], configuredOperations) != -1) { + // if ENCRYPT_STORAGE is configured + operation = androidOperationConstants["ENCRYPT_STORAGE_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating WIFI + if ($.inArray(androidOperationConstants["WIFI_OPERATION_CODE"], configuredOperations) != -1) { + // if WIFI is configured + operation = androidOperationConstants["WIFI_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var wifiSSID = $("input#wifi-ssid").val(); + if (!wifiSSID) { + validationStatus = { + "error": true, + "subErrorMsg": "WIFI SSID is not given. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + } + } + if (policy["platform"] == platformTypeConstants["WINDOWS"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(windowsOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = windowsOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + var continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + var passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + var passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CAMERA + if ($.inArray(windowsOperationConstants["CAMERA_OPERATION_CODE"], configuredOperations) != -1) { + // if CAMERA is configured + operation = windowsOperationConstants["CAMERA_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating ENCRYPT_STORAGE + if ($.inArray(windowsOperationConstants["ENCRYPT_STORAGE_OPERATION_CODE"], configuredOperations) != -1) { + // if ENCRYPT_STORAGE is configured + operation = windowsOperationConstants["ENCRYPT_STORAGE_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + + } + } else if (policy["platform"] == platformTypeConstants["IOS"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(iosOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = iosOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating RESTRICTIONS + if ($.inArray(iosOperationConstants["RESTRICTIONS_OPERATION_CODE"], configuredOperations) != -1) { + // if RESTRICTION is configured + operation = iosOperationConstants["RESTRICTIONS_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // getting input values to be validated + var restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs = + "div#restrictions-autonomous-single-app-mode-permitted-app-ids .child-input"; + if ($(restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs).length > 0) { + var childInput; + var childInputArray = []; + var emptyChildInputCount = 0; + var duplicatesExist = false; + // looping through each child input + $(restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + var initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + var m, poppedChildInput; + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + var n; + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more permitted App ID entries in " + + "Autonomous Single App Mode are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with permitted App ID entries in " + + "Autonomous Single App Mode.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating WIFI + if ($.inArray(iosOperationConstants["WIFI_OPERATION_CODE"], configuredOperations) != -1) { + // if WIFI is configured + operation = iosOperationConstants["WIFI_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // getting input values to be validated + wifiSSID = $("input#wifi-ssid").val(); + var wifiDomainName = $("input#wifi-domain-name").val(); + if (!wifiSSID && !wifiDomainName) { + validationStatus = { + "error": true, + "subErrorMsg": "Both Wi-Fi SSID and Wi-Fi Domain Name are not given. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + // getting proxy-setup value + var wifiProxyType = $("select#wifi-proxy-type").find("option:selected").attr("value"); + if (wifiProxyType == "Manual") { + // adds up additional fields to be validated + var wifiProxyServer = $("input#wifi-proxy-server").val(); + if (!wifiProxyServer) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Server is required. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var wifiProxyPort = $("input#wifi-proxy-port").val(); + if (!wifiProxyPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port is required. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(wifiProxyPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(wifiProxyPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + } + + if (continueToCheckNextInputs) { + // getting encryption-type value + var wifiEncryptionType = $("select#wifi-encryption-type").find("option:selected").attr("value"); + if (wifiEncryptionType != "None") { + var wifiPayloadCertificateAnchorUUIDsGridChildInputs = + "div#wifi-payload-certificate-anchor-uuids .child-input"; + if ($(wifiPayloadCertificateAnchorUUIDsGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiPayloadCertificateAnchorUUIDsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Payload Certificate " + + "Anchor UUIDs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist " + + "with Payload Certificate Anchor UUIDs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var wifiTLSTrustedServerNamesGridChildInputs = + "div#wifi-tls-trusted-server-names .child-input"; + if ($(wifiTLSTrustedServerNamesGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiTLSTrustedServerNamesGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more TLS Trusted Server Names are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist " + + "with TLS Trusted Server Names.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + } + } + + if (continueToCheckNextInputs) { + var wifiRoamingConsortiumOIsGridChildInputs = "div#wifi-roaming-consortium-ois .child-input"; + if ($(wifiRoamingConsortiumOIsGridChildInputs).length > 0) { + emptyChildInputCount = 0; + var outOfAllowedLengthCount = 0; + var invalidAgainstRegExCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiRoamingConsortiumOIsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!inputIsValidAgainstLength(childInput, 6, 6) && !inputIsValidAgainstLength(childInput, 10, 10)) { + outOfAllowedLengthCount++; + } else if (!inputIsValidAgainstRegExp(/^[a-fA-F0-9]+$/, childInput)) { + invalidAgainstRegExCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (outOfAllowedLengthCount > 0) { + // if outOfMaxAllowedLength input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs " + + "are out of allowed length.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (invalidAgainstRegExCount > 0) { + // if invalid inputs in terms of hexadecimal format are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs " + + "contain non-hexadecimal characters.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with Roaming Consortium OIs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + var wifiNAIRealmNamesGridChildInputs = "div#wifi-nai-realm-names .child-input"; + if ($(wifiNAIRealmNamesGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiNAIRealmNamesGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more NAI Realm Names are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with NAI Realm Names.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + var wifiMCCAndMNCsGridChildInputs = "div#wifi-mcc-and-mncs .child-input"; + if ($(wifiMCCAndMNCsGridChildInputs).length > 0) { + var childInputCount = 0; + var stringPair; + emptyChildInputCount = 0; + outOfAllowedLengthCount = 0; + var notNumericInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiMCCAndMNCsGridChildInputs).each(function () { + childInput = $(this).val(); + // pushing each string pair to childInputArray + childInputCount++; + if (childInputCount % 2 == 1) { + // initialize stringPair value + stringPair = ""; + // append first part of the string + stringPair += childInput; + } else { + // append second part of the string + stringPair += childInput; + childInputArray.push(stringPair); + } + // updating emptyChildInputCount & outOfAllowedLengthCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!$.isNumeric(childInput)) { + notNumericInputCount++; + } else if (!inputIsValidAgainstLength(childInput, 3, 3)) { + outOfAllowedLengthCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (notNumericInputCount > 0) { + // if notNumeric input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs are not numeric.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (outOfAllowedLengthCount > 0) { + // if outOfAllowedLength input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs " + + "do not fulfill the accepted length of 6 digits.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with MCC/MNC pairs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating EMAIL + if ($.inArray(iosOperationConstants["EMAIL_OPERATION_CODE"], configuredOperations) != -1) { + // if EMAIL is configured + operation = iosOperationConstants["EMAIL_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var emailAddress = $("input#email-address").val(); + if (emailAddress && !inputIsValidAgainstRegExp(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, emailAddress)) { + validationStatus = { + "error": true, + "subErrorMsg": "Email Address is not valid.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var emailIncomingMailServerHostname = $("input#email-incoming-mail-server-hostname").val(); + if (!emailIncomingMailServerHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Hostname is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var emailIncomingMailServerPort = $("input#email-incoming-mail-server-port").val(); + if (!emailIncomingMailServerPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Port is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(emailIncomingMailServerPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(emailIncomingMailServerPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var emailOutgoingMailServerHostname = $("input#email-outgoing-mail-server-hostname").val(); + if (!emailOutgoingMailServerHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Hostname is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var emailOutgoingMailServerPort = $("input#email-outgoing-mail-server-port").val(); + if (!emailOutgoingMailServerPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Port is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(emailOutgoingMailServerPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(emailOutgoingMailServerPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating AIRPLAY + if ($.inArray(iosOperationConstants["AIRPLAY_OPERATION_CODE"], configuredOperations) != -1) { + // if AIRPLAY is configured + operation = iosOperationConstants["AIRPLAY_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var airplayCredentialsGridChildInputs = "div#airplay-credentials .child-input"; + var airplayDestinationsGridChildInputs = "div#airplay-destinations .child-input"; + if ($(airplayCredentialsGridChildInputs).length == 0 && + $(airplayDestinationsGridChildInputs).length == 0) { + validationStatus = { + "error": true, + "subErrorMsg": "AirPlay settings have zero configurations attached.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + if ($(airplayCredentialsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(airplayCredentialsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 2 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Device Names of " + + "AirPlay Credentials are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "Device Names of AirPlay Credentials.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + if ($(airplayDestinationsGridChildInputs).length > 0) { + childInputArray = []; + emptyChildInputCount = 0; + invalidAgainstRegExCount = 0; + duplicatesExist = false; + // looping through each child input + $(airplayDestinationsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!inputIsValidAgainstRegExp( + /([a-z|A-Z|0-9][a-z|A-Z|0-9][:]){5}([a-z|A-Z|0-9][a-z|A-Z|0-9])$/, childInput)) { + // if child input field is invalid against RegEx + invalidAgainstRegExCount++ + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more AirPlay Destination fields are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (invalidAgainstRegExCount > 0) { + // if invalidAgainstRegEx inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more AirPlay Destination fields " + + "do not fulfill expected format.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with AirPlay Destinations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating LDAP + if ($.inArray(iosOperationConstants["LDAP_OPERATION_CODE"], configuredOperations) != -1) { + // if LDAP is configured + operation = iosOperationConstants["LDAP_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var ldapAccountHostname = $("input#ldap-account-hostname").val(); + if (!ldapAccountHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "LDAP Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var ldapSearchSettingsGridChildInputs = "div#ldap-search-settings .child-input"; + if ($(ldapSearchSettingsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(ldapSearchSettingsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 3 == 2) { + // if child input is of second column + childInput = $(this).find("option:selected").attr("value"); + stringPair = ""; + stringPair += (childInput + " "); + } else if (childInputCount % 3 == 0) { + // if child input is of third column + childInput = $(this).val(); + stringPair += childInput; + childInputArray.push(stringPair); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Search Setting Scope fields are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "Search Setting Search Base and Scope pairs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CALENDAR + if ($.inArray(iosOperationConstants["CALENDAR_OPERATION_CODE"], configuredOperations) != -1) { + // if CALENDAR is configured + operation = iosOperationConstants["CALENDAR_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var calendarAccountHostname = $("input#calendar-account-hostname").val(); + if (!calendarAccountHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var calendarAccountPort = $("input#calendar-account-port").val(); + if (!calendarAccountPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(calendarAccountPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(calendarAccountPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CALENDAR_SUBSCRIPTION + if ($.inArray(iosOperationConstants["CALENDAR_SUBSCRIPTION_OPERATION_CODE"], configuredOperations) != -1) { + // if CALENDAR_SUBSCRIPTION is configured + operation = iosOperationConstants["CALENDAR_SUBSCRIPTION_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var calendarSubscriptionHostname = $("input#calendar-subscription-hostname").val(); + if (!calendarSubscriptionHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating APN + if ($.inArray(iosOperationConstants["APN_OPERATION_CODE"], configuredOperations) != -1) { + // if APN is configured + operation = iosOperationConstants["APN_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var apnConfigurationsGridChildInputs = "div#apn-configurations .child-input"; + if ($(apnConfigurationsGridChildInputs).length == 0) { + validationStatus = { + "error": true, + "subErrorMsg": "APN Settings have zero configurations attached.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if ($(apnConfigurationsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + // checking empty APN field count + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(apnConfigurationsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 5 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more APN fields of Configurations are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "APN fields of Configurations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CELLULAR + if ($.inArray(iosOperationConstants["CELLULAR_OPERATION_CODE"], configuredOperations) != -1) { + // if CELLULAR is configured + operation = iosOperationConstants["CELLULAR_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var cellularAttachAPNName = $("input#cellular-attach-apn-name").val(); + if (!cellularAttachAPNName) { + validationStatus = { + "error": true, + "subErrorMsg": "Cellular Configuration Name is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var cellularAPNConfigurationsGridChildInputs = "div#cellular-apn-configurations .child-input"; + if ($(cellularAPNConfigurationsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + // checking empty APN field count + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(cellularAPNConfigurationsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 6 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more APN fields of APN Configurations are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "APN fields of APN Configurations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + } + } + // ending validation process + + // start taking specific notifying actions upon validation + var wizardIsToBeContinued; + var errorCount = 0; + var mainErrorMsgWrapper, mainErrorMsg, + subErrorMsgWrapper, subErrorMsg, subErrorIcon, subOkIcon, featureConfiguredIcon; + var i; + for (i = 0; i < validationStatusArray.length; i++) { + validationStatus = validationStatusArray[i]; + if (validationStatus["error"]) { + errorCount++; + if (validationStatus["mainErrorMsg"]) { + mainErrorMsgWrapper = "#policy-profile-main-error-msg"; + mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else if (validationStatus["subErrorMsg"]) { + subErrorMsgWrapper = "#" + validationStatus["erroneousFeature"] + "-feature-error-msg"; + subErrorMsg = subErrorMsgWrapper + " span"; + subErrorIcon = "#" + validationStatus["erroneousFeature"] + "-error"; + subOkIcon = "#" + validationStatus["erroneousFeature"] + "-ok"; + featureConfiguredIcon = "#" + validationStatus["erroneousFeature"] + "-configured"; + // hiding featureConfiguredState as the first step + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // updating error state and corresponding messages + $(subErrorMsg).text(validationStatus["subErrorMsg"]); + if ($(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).removeClass("hidden"); + } + if (!$(subOkIcon).hasClass("hidden")) { + $(subOkIcon).addClass("hidden"); + } + if ($(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).removeClass("hidden"); + } + } + } else { + if (validationStatus["okFeature"]) { + subErrorMsgWrapper = "#" + validationStatus["okFeature"] + "-feature-error-msg"; + subErrorIcon = "#" + validationStatus["okFeature"] + "-error"; + subOkIcon = "#" + validationStatus["okFeature"] + "-ok"; + featureConfiguredIcon = "#" + validationStatus["okFeature"] + "-configured"; + // hiding featureConfiguredState as the first step + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // updating success state and corresponding messages + if (!$(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).addClass("hidden"); + } + if (!$(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).addClass("hidden"); + } + if ($(subOkIcon).hasClass("hidden")) { + $(subOkIcon).removeClass("hidden"); + } + } + } + } + + wizardIsToBeContinued = (errorCount == 0); + return wizardIsToBeContinued; +}; + +stepForwardFrom["policy-profile"] = function () { + policy["profile"] = operationModule.generateProfile(policy["platform"], configuredOperations); + // updating next-page wizard title with selected platform + $("#policy-criteria-page-wizard-title").text(policy["platform"] + " POLICY - " + policy["name"]); +}; + +stepForwardFrom["policy-criteria"] = function () { + $("input[type='radio'].select-users-radio").each(function () { + if ($(this).is(':radio')) { + if ($(this).is(":checked")) { + if ($(this).attr("id") == "users-radio-btn") { + policy["selectedUsers"] = $("#users-input").val(); + } else if ($(this).attr("id") == "user-roles-radio-btn") { + policy["selectedUserRoles"] = $("#user-roles-input").val(); + } + } + } + }); + policy["selectedNonCompliantAction"] = $("#action-input").find(":selected").data("action"); + policy["selectedOwnership"] = $("#ownership-input").val(); + // updating next-page wizard title with selected platform + $("#policy-naming-page-wizard-title").text(policy["platform"] + " POLICY - " + policy["name"]); +}; + +/** + * Checks if provided input is valid against provided length range. + * + * @param input Alphanumeric or non-alphanumeric input + * @param minLength Minimum Required Length + * @param maxLength Maximum Required Length + * @returns {boolean} Returns true if input matches the provided minimum length and maximum length + */ +var inputIsValidAgainstLength = function (input, minLength, maxLength) { + var length = input.length; + return (length == minLength || (length > minLength && length < maxLength) || length == maxLength); +}; + +validateStep["policy-naming"] = function () { + var validationStatus = {}; + + // taking values of inputs to be validated + var policyName = $("input#policy-name-input").val(); + // starting validation process and updating validationStatus + if (!policyName) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = "Policy name is empty. You cannot proceed."; + } else if (!inputIsValidAgainstLength(policyName, 1, 30)) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = + "Policy name exceeds maximum allowed length."; + } else { + validationStatus["error"] = false; + } + // ending validation process + + // start taking specific actions upon validation + var wizardIsToBeContinued; + if (validationStatus["error"]) { + wizardIsToBeContinued = false; + var mainErrorMsgWrapper = "#policy-naming-main-error-msg"; + var mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else { + wizardIsToBeContinued = true; + } + + return wizardIsToBeContinued; +}; + +validateStep["policy-naming-publish"] = function () { + var validationStatus = {}; + + // taking values of inputs to be validated + var policyName = $("input#policy-name-input").val(); + // starting validation process and updating validationStatus + if (!policyName) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = "Policy name is empty. You cannot proceed."; + } else if (!inputIsValidAgainstLength(policyName, 1, 30)) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = + "Policy name exceeds maximum allowed length."; + } else { + validationStatus["error"] = false; + } + // ending validation process + + // start taking specific actions upon validation + var wizardIsToBeContinued; + if (validationStatus["error"]) { + wizardIsToBeContinued = false; + var mainErrorMsgWrapper = "#policy-naming-main-error-msg"; + var mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else { + wizardIsToBeContinued = true; + } + + return wizardIsToBeContinued; +}; + +stepForwardFrom["policy-naming-publish"] = function () { + policy["policyName"] = $("#policy-name-input").val(); + policy["description"] = $("#policy-description-input").val(); + //All data is collected. Policy can now be updated. + updatePolicy(policy, "publish"); +}; +stepForwardFrom["policy-naming"] = function () { + policy["policyName"] = $("#policy-name-input").val(); + policy["description"] = $("#policy-description-input").val(); + //All data is collected. Policy can now be updated. + updatePolicy(policy, "save"); +}; + +var updatePolicy = function (policy, state) { + var profilePayloads = []; + // traverses key by key in policy["profile"] + var key; + for (key in policy["profile"]) { + if (policy["profile"].hasOwnProperty(key)) { + profilePayloads.push({ + "featureCode": key, + "deviceType": policy["platform"], + "content": policy["profile"][key] + }); + } + } + var payload = { + "policyName": policy["policyName"], + "description": policy["description"], + "compliance": policy["selectedNonCompliantAction"], + "ownershipType": policy["selectedOwnership"], + "profile": { + "profileName": policy["policyName"], + "deviceType": policy["platform"], + "profileFeaturesList": profilePayloads + } + }; + + if (policy["selectedUsers"]) { + payload["users"] = policy["selectedUsers"]; + } else if (policy["selectedUserRoles"]) { + payload["roles"] = policy["selectedUserRoles"]; + } else { + payload["users"] = []; + payload["roles"] = []; + } + var serviceURL = base_api_url + "/policies/" + getParameterByName("id"); + invokerUtil.put( + serviceURL, + payload, + // on success + function () { + if (state == "save") { + var policyList = []; + policyList.push(getParameterByName("id")); + serviceURL = base_api_url + "/policies/deactivate-policy"; + invokerUtil.put( + serviceURL, + policyList, + // on success + function () { + $(".policy-message").removeClass("hidden"); + $(".add-policy").addClass("hidden"); + }, + // on error + function (data) { + console.log(data); + } + ); + } else if (state == "publish") { + var policyList = []; + policyList.push(getParameterByName("id")); + serviceURL = base_api_url + "/policies/activate-policy"; + invokerUtil.put( + serviceURL, + policyList, + // on success + function () { + $(".policy-message").removeClass("hidden"); + $(".add-policy").addClass("hidden"); + }, + // on error + function (data) { + console.log(data); + } + ); + } + }, + // on error + function (data) { + console.log(data); + } + ); +}; + +// Start of HTML embedded invoke methods +var showAdvanceOperation = function (operation, button) { + $(button).addClass('selected'); + $(button).siblings().removeClass('selected'); + var hiddenOperation = ".wr-hidden-operations-content > div"; + $(hiddenOperation + '[data-operation="' + operation + '"]').show(); + $(hiddenOperation + '[data-operation="' + operation + '"]').siblings().hide(); +}; + +/** + * Method to slide down a provided pane upon provided value set. + * + * @param selectElement Select HTML Element to consider + * @param paneID HTML ID of div element to slide down + * @param valueSet Applicable Value Set + */ +var slideDownPaneAgainstValueSet = function (selectElement, paneID, valueSet) { + var selectedValueOnChange = $(selectElement).find("option:selected").val(); + if ($(selectElement).is("input:checkbox")) { + selectedValueOnChange = $(selectElement).is(":checked").toString(); + } + + var i, slideDownVotes = 0; + for (i = 0; i < valueSet.length; i++) { + if (selectedValueOnChange == valueSet[i]) { + slideDownVotes++; + } + } + var paneSelector = "#" + paneID; + if (slideDownVotes > 0) { + if (!$(paneSelector).hasClass("expanded")) { + $(paneSelector).addClass("expanded"); + } + $(paneSelector).slideDown(); + } else { + if ($(paneSelector).hasClass("expanded")) { + $(paneSelector).removeClass("expanded"); + } + $(paneSelector).slideUp(); + /* now follows the code to reinitialize all inputs of the slidable pane. + reinitializing input fields into the defaults.*/ + $(paneSelector + " input").each( + function () { + if ($(this).is("input:text")) { + $(this).val($(this).data("default")); + } else if ($(this).is("input:password")) { + $(this).val(""); + } else if ($(this).is("input:checkbox")) { + $(this).prop("checked", $(this).data("default")); + // if this checkbox is the parent input of a grouped-input + if ($(this).hasClass("parent-input")) { + var groupedInput = $(this).parent().parent().parent(); + updateGroupedInputVisibility(groupedInput); + } + } + } + ); + // reinitializing select fields into the defaults + $(paneSelector + " select").each( + function () { + var defaultOption = $(this).data("default"); + $("option:eq(" + defaultOption + ")", this).prop("selected", "selected"); + } + ); + // collapsing expanded-panes (upon the selection of html-select-options) if any + $(paneSelector + " .expanded").each( + function () { + if ($(this).hasClass("expanded")) { + $(this).removeClass("expanded"); + } + $(this).slideUp(); + } + ); + // removing all entries of grid-input elements if exist + $(paneSelector + " .grouped-array-input").each( + function () { + var gridInputs = $(this).find("[data-add-form-clone]"); + if (gridInputs.length > 0) { + gridInputs.remove(); + } + var helpTexts = $(this).find("[data-help-text=add-form]"); + if (helpTexts.length > 0) { + helpTexts.show(); + } + } + ); + } +}; +// End of HTML embedded invoke methods + + +// Start of functions related to grid-input-view + +/** + * Method to set count id to cloned elements. + * @param {object} addFormContainer + */ +var setId = function (addFormContainer) { + $(addFormContainer).find("[data-add-form-clone]").each(function (i) { + $(this).attr("id", $(this).attr("data-add-form-clone").slice(1) + "-" + (i + 1)); + if ($(this).find(".index").length > 0) { + $(this).find(".index").html(i + 1); + } + }); +}; + +/** + * Method to set count id to cloned elements. + * @param {object} addFormContainer + */ +var showHideHelpText = function (addFormContainer) { + var helpText = "[data-help-text=add-form]"; + if ($(addFormContainer).find("[data-add-form-clone]").length > 0) { + $(addFormContainer).find(helpText).hide(); + } else { + $(addFormContainer).find(helpText).show(); + } +}; + +/** + * This method will display appropriate fields based on wifi type + * @param {object} wifi type select object + */ +var changeAndroidWifiPolicy = function (select) { + slideDownPaneAgainstValueSet(select, 'control-wifi-password', ['wep', 'wpa', '802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-eap', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-phase2', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-identity', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-anoidentity', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-cacert', ['802eap']); +}; + +/** + * This method will display appropriate fields based on wifi EAP type + * @param {object} wifi eap select object + * @param {object} wifi type select object + */ +var changeAndroidWifiPolicyEAP = function (select, superSelect) { + slideDownPaneAgainstValueSet(select, 'control-wifi-password', ['peap', 'ttls', 'pwd' , 'fast', 'leap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-phase2', ['peap', 'ttls', 'fast']); + slideDownPaneAgainstValueSet(select, 'control-wifi-provisioning', ['fast']); + slideDownPaneAgainstValueSet(select, 'control-wifi-identity', ['peap', 'tls', 'ttls', 'pwd', 'fast', 'leap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-anoidentity', ['peap', 'ttls']); + slideDownPaneAgainstValueSet(select, 'control-wifi-cacert', ['peap', 'tls', 'ttls']); + if (superSelect.value != '802eap') { + changeAndroidWifiPolicy(superSelect); + } +}; + +// End of functions related to grid-input-view + +/** + * This method will return query parameter value given its name. + * @param name Query parameter name + * @returns {string} Query parameter value + */ +var getParameterByName = function (name) { + name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), + results = regex.exec(location.search); + return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); +}; + +$(document).ready(function () { + $('#appbar-btn-apply-changes').addClass('hidden'); + // Adding initial state of wizard-steps. + $("#policy-profile-wizard-steps").html($(".wr-steps").html()); + + var policyPayloadObj; + invokerUtil.get( + base_api_url + "/policies/" + getParameterByName("id"), + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200 && data) { + policyPayloadObj = JSON.parse(data); + skipStep["policy-platform"](policyPayloadObj); + } + }, + // on error + function (jqXHR) { + console.log(jqXHR); + // should be redirected to an error page + } + ); + + $("select.select2[multiple=multiple]").select2({ + "tags": true + }); + + $("#users-select-field").hide(); + $("#user-roles-select-field").show(); + + $("input[type='radio'].select-users-radio").change(function () { + if ($("#users-radio-btn").is(":checked")) { + $("#user-roles-select-field").hide(); + $("#users-select-field").show(); + } + if ($("#user-roles-radio-btn").is(":checked")) { + $("#users-select-field").hide(); + $("#user-roles-select-field").show(); + } + }); + + // Support for special input type "ANY" on user(s) & user-role(s) selection + $("#users-input, #user-roles-input").select2({ + "tags": true + }).on("select2:select", function (e) { + if (e.params.data.id == "ANY") { + $(this).val("ANY").trigger("change"); + } else { + $("option[value=ANY]", this).prop("selected", false).parent().trigger("change"); + } + }); + + // Maintains an array of configured features of the profile + var advanceOperations = ".wr-advance-operations"; + $(advanceOperations).on("click", ".wr-input-control.switch", function (event) { + var operationCode = $(this).parents(".operation-data").data("operation-code"); + var operation = $(this).parents(".operation-data").data("operation"); + var operationDataWrapper = $(this).data("target"); + // prevents event bubbling by figuring out what element it's being called from. + if (event.target.tagName == "INPUT") { + var featureConfiguredIcon; + if ($("input[type='checkbox']", this).is(":checked")) { + configuredOperations.push(operationCode); + // when a feature is enabled, if "zero-configured-features" msg is available, hide that. + var zeroConfiguredOperationsErrorMsg = "#policy-profile-main-error-msg"; + if (!$(zeroConfiguredOperationsErrorMsg).hasClass("hidden")) { + $(zeroConfiguredOperationsErrorMsg).addClass("hidden"); + } + // add configured-state-icon to the feature + featureConfiguredIcon = "#" + operation + "-configured"; + if ($(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).removeClass("hidden"); + } + } else { + //splicing the array if operation is present. + var index = $.inArray(operationCode, configuredOperations); + if (index != -1) { + configuredOperations.splice(index, 1); + } + // when a feature is disabled, clearing all its current configured, error or success states + var subErrorMsgWrapper = "#" + operation + "-feature-error-msg"; + var subErrorIcon = "#" + operation + "-error"; + var subOkIcon = "#" + operation + "-ok"; + featureConfiguredIcon = "#" + operation + "-configured"; + + if (!$(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).addClass("hidden"); + } + if (!$(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).addClass("hidden"); + } + if (!$(subOkIcon).hasClass("hidden")) { + $(subOkIcon).addClass("hidden"); + } + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // reinitializing input fields into the defaults + $(operationDataWrapper + " input").each( + function () { + if ($(this).is("input:text")) { + $(this).val($(this).data("default")); + } else if ($(this).is("input:password")) { + $(this).val(""); + } else if ($(this).is("input:checkbox")) { + $(this).prop("checked", $(this).data("default")); + // if this checkbox is the parent input of a grouped-input + if ($(this).hasClass("parent-input")) { + var groupedInput = $(this).parent().parent().parent(); + updateGroupedInputVisibility(groupedInput); + } + } + } + ); + // reinitializing select fields into the defaults + $(operationDataWrapper + " select").each( + function () { + var defaultOption = $(this).data("default"); + $("option:eq(" + defaultOption + ")", this).prop("selected", "selected"); + } + ); + // collapsing expanded-panes (upon the selection of html-select-options) if any + $(operationDataWrapper + " .expanded").each( + function () { + if ($(this).hasClass("expanded")) { + $(this).removeClass("expanded"); + } + $(this).slideUp(); + } + ); + // removing all entries of grid-input elements if exist + $(operationDataWrapper + " .grouped-array-input").each( + function () { + var gridInputs = $(this).find("[data-add-form-clone]"); + if (gridInputs.length > 0) { + gridInputs.remove(); + } + var helpTexts = $(this).find("[data-help-text=add-form]"); + if (helpTexts.length > 0) { + helpTexts.show(); + } + } + ); + } + } + }); + + // adding support for cloning multiple profiles per feature with cloneable class definitions + $(advanceOperations).on("click", ".multi-view.add.enabled", function () { + // get a copy of .cloneable and create new .cloned div element + var cloned = "

    " + $(".cloneable", $(this).parent().parent()).html() + "
    "; + // append newly created .cloned div element to panel-body + $(this).parent().parent().append(cloned); + // enable remove action of newly cloned div element + $(".cloned", $(this).parent().parent()).each( + function () { + if ($(".multi-view.remove", this).hasClass("disabled")) { + $(".multi-view.remove", this).removeClass("disabled"); + } + if (!$(".multi-view.remove", this).hasClass("enabled")) { + $(".multi-view.remove", this).addClass("enabled"); + } + } + ); + }); + + $(advanceOperations).on("click", ".multi-view.remove.enabled", function () { + $(this).parent().remove(); + }); + + // enabling or disabling grouped-input based on the status of a parent check-box + $(advanceOperations).on("click", ".grouped-input", function () { + updateGroupedInputVisibility(this); + }); + + // add form entry click function for grid inputs + $(advanceOperations).on("click", "[data-click-event=add-form]", function () { + var addFormContainer = $("[data-add-form-container=" + $(this).attr("href") + "]"); + var clonedForm = $("[data-add-form=" + $(this).attr("href") + "]").clone(). + find("[data-add-form-element=clone]").attr("data-add-form-clone", $(this).attr("href")); + + // adding class .child-input to capture text-input-array-values + $("input, select", clonedForm).addClass("child-input"); + + $(addFormContainer).append(clonedForm); + setId(addFormContainer); + showHideHelpText(addFormContainer); + }); + + // remove form entry click function for grid inputs + $(advanceOperations).on("click", "[data-click-event=remove-form]", function () { + var addFormContainer = $("[data-add-form-container=" + $(this).attr("href") + "]"); + + $(this).closest("[data-add-form-element=clone]").remove(); + setId(addFormContainer); + showHideHelpText(addFormContainer); + }); + + $(".wizard-stepper").click(function () { + // button clicked here can be either a continue button or a back button. + var currentStep = $(this).data("current"); + var validationIsRequired = $(this).data("validate"); + var wizardIsToBeContinued; + + if (validationIsRequired) { + wizardIsToBeContinued = validateStep[currentStep](); + } else { + wizardIsToBeContinued = true; + } + + if (wizardIsToBeContinued) { + // When moving back and forth, following code segment will + // remove if there are any visible error-messages. + var errorMsgWrappers = ".alert.alert-danger"; + $(errorMsgWrappers).each( + function () { + if (!$(this).hasClass("hidden")) { + $(this).addClass("hidden"); + } + } + ); + + var nextStep = $(this).data("next"); + var isBackBtn = $(this).data("is-back-btn"); + + // if current button is a continuation... + if (!isBackBtn) { + // initiate stepForwardFrom[*] functions to gather form data. + if (stepForwardFrom[currentStep]) { + stepForwardFrom[currentStep](this); + } + } else { + // initiate stepBackFrom[*] functions to rollback. + if (stepBackFrom[currentStep]) { + stepBackFrom[currentStep](); + } + } + + // following step occurs only at the last stage of the wizard. + if (!nextStep) { + window.location.href = $(this).data("direct"); + } + + // updating next wizard step as current. + $(".itm-wiz").each(function () { + var step = $(this).data("step"); + if (step == nextStep) { + $(this).addClass("itm-wiz-current"); + } else { + $(this).removeClass("itm-wiz-current"); + } + }); + + // adding next update of wizard-steps. + $("#" + nextStep + "-wizard-steps").html($(".wr-steps").html()); + + // hiding current section of the wizard and showing next section. + $("." + currentStep).addClass("hidden"); + $("." + nextStep).removeClass("hidden"); + } + }); +}); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-android.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-android.hbs new file mode 100644 index 0000000000..570a2e88aa --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-android.hbs @@ -0,0 +1,1227 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + Bellow restrictions will be applied on devices with Android version 5.0 Lollipop onwards only + +

    +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    + +
    + +
    +
    +
    + Bellow restrictions will be applied on devices with Android version 6.0 Marshmallow onwards only. + +

    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you do not need the device to be encrypted. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + + + + + + + + + + + + + + Please note that * sign represents required fields of data. +
    +
    + +
    + + +
    +
    + + +
    + + + + + + + + +
    +
    +
    + + +
    +
    + +
    + + + + +
    +
    + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + +
    + + + + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    +
    +
    diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-ios.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-ios.hbs new file mode 100644 index 0000000000..07c2e2dbf3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-ios.hbs @@ -0,0 +1,4738 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    +Please note that * sign represents required fields of data. +
    +
    + + +
    + + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + + + + + + + + + + + +
    No:KeyValue
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    + + +
    + + + + +
    +
    +
    + + + +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + + +
    + + +
    +
    + +
    +
    + + +
    + + + + + + + + + + + + + +
    No:Safari Domain
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + + +
    + + +
    + + + + + + + + + + + + + + +
    No:App IdentifierVPN UUID
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + +
    + +
    + + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + + + +
    + + +
    + + + +
    + + +
    + + + + + + + + + + + + + +
    No:Roaming Consortium OI
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + +
    No:NAI Realm Name
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + + +
    No:Mobile Country Code ( MCC )Mobile Network Code ( MNC )
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    +Incoming Mail Settings : +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +Outgoing Mail Settings : +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + + + + + + + + + + + + + + +
    No:Device NamePassword
    + No entries added yet . +
    + + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + +
    No:Destination
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + + + + + + + + + + + + + + + +
    No:DescriptionSearch BaseScope
    + No entries added yet . +
    + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + + + + + + + + + + + + + + + + + +
    No:APNUsernamePasswordProxyPort
    + No entries added yet . +
    + + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + + + + + + + + + + + + + + + + + + +
    No:APNAuth.TypeUsernamePasswordProxyPort
    + No entries added yet . +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +Restrictions on Device Functionality : +
    +
    +
      +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
        +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    +
    +
    +Restrictions on Applications : +
    +
    +
      +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
        +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + + +
        +
      • +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    +
    + + + +
    +
    +
    + +
    +
    \ 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/public/templates/hidden-operations-windows.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-windows.hbs new file mode 100644 index 0000000000..0c0359d8c0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/public/templates/hidden-operations-windows.hbs @@ -0,0 +1,568 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you need to disable camera. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you need to disable storage-encryption. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + +
    +
    + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    \ 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.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/app/units/cdmf.unit.policy.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js new file mode 100644 index 0000000000..2d2a438263 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.view/view.js @@ -0,0 +1,25 @@ +/* + * 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"); + +// 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 From 1b07b18678ba3b6290fc2dc6134b995e442afdcd Mon Sep 17 00:00:00 2001 From: hasuniea Date: Mon, 8 Aug 2016 18:05:12 +0530 Subject: [PATCH 16/21] adding security fixes --- .../org.wso2.carbon.device.mgt.api/pom.xml | 8 ++ .../device/mgt/jaxrs/beans/ErrorResponse.java | 2 +- .../device/mgt/jaxrs/beans/PolicyWrapper.java | 5 + .../device/mgt/jaxrs/beans/Profile.java | 1 - .../jaxrs/exception/BadRequestException.java | 34 +++++ .../ConstraintViolationException.java | 55 ++++++++ .../device/mgt/jaxrs/exception/ErrorDTO.java | 86 ++++++++++++ .../jaxrs/exception/ForbiddenException.java | 51 ++++++++ .../exception/GlobalThrowableMapper.java | 113 ++++++++++++++++ .../jaxrs/exception/NotFoundException.java | 47 +++++++ .../UnexpectedServerErrorException.java | 49 +++++++ .../exception/ValidationInterceptor.java | 122 ++++++++++++++++++ .../api/ActivityInfoProviderService.java | 5 +- .../service/api/DeviceManagementService.java | 105 +++++++++------ .../api/NotificationManagementService.java | 8 +- .../service/api/PolicyManagementService.java | 7 +- .../admin/DeviceManagementAdminService.java | 9 +- .../api/admin/UserManagementAdminService.java | 5 +- .../impl/ActivityProviderServiceImpl.java | 4 +- .../impl/ConfigurationServiceImpl.java | 1 - .../impl/DeviceManagementServiceImpl.java | 39 +++--- .../NotificationManagementServiceImpl.java | 6 +- .../impl/PolicyManagementServiceImpl.java | 7 +- .../DeviceManagementAdminServiceImpl.java | 5 +- .../admin/UserManagementAdminServiceImpl.java | 5 +- .../impl/util/RequestValidationUtil.java | 12 +- .../device/mgt/jaxrs/util/Constants.java | 14 ++ .../device/mgt/jaxrs/util/DeviceMgtUtil.java | 50 +++++++ .../src/main/webapp/WEB-INF/cxf-servlet.xml | 19 ++- .../DeviceAccessAuthorizationServiceImpl.java | 2 +- pom.xml | 21 +-- 31 files changed, 788 insertions(+), 109 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java 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..127e554f50 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 @@ -248,6 +248,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/exception/BadRequestException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java new file mode 100644 index 0000000000..d97b78b6dd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java @@ -0,0 +1,34 @@ +/* + * 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 javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.Response; + +/** + * Custom exception class for wrapping BadRequest related exceptions. + */ +public class BadRequestException extends WebApplicationException { + + public BadRequestException(ErrorResponse error) { + super(Response.status(Response.Status.BAD_REQUEST).entity(error).build()); + } +} \ 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..78ce621a05 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 @@ -25,6 +25,7 @@ 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; @@ -100,7 +101,9 @@ public interface ActivityInfoProviderService { 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", 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..a72a4e5657 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 @@ -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; @@ -100,62 +101,68 @@ public interface DeviceManagementService { 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 @@ -206,8 +213,8 @@ public interface DeviceManagementService { @Permission( scope = "device-view", permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" + "/permission/admin/device-mgt/admin/devices/view", + "/permission/admin/device-mgt/user/devices/view" } ) Response getDevice( @@ -216,19 +223,21 @@ public interface DeviceManagementService { 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") @@ -292,7 +301,7 @@ public interface DeviceManagementService { @Permission( scope = "device-search", permissions = {"/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" + "/permission/admin/device-mgt/user/devices/view" } ) Response getFeaturesOfDevice( @@ -301,19 +310,21 @@ public interface DeviceManagementService { 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") @@ -370,7 +381,7 @@ public interface DeviceManagementService { }) @Permission( scope = "device-search", - permissions = {"/permission/admin/device-mgt/admin/devices/list" } + permissions = {"/permission/admin/device-mgt/admin/devices/list"} ) Response searchDevices( @ApiParam( @@ -378,18 +389,18 @@ public interface DeviceManagementService { 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") @@ -453,8 +464,8 @@ public interface DeviceManagementService { @Permission( scope = "operation-view", permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" + "/permission/admin/device-mgt/admin/devices/view", + "/permission/admin/device-mgt/user/devices/view" } ) Response getInstalledApplications( @@ -462,31 +473,33 @@ public interface DeviceManagementService { 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 @@ -553,8 +566,8 @@ public interface DeviceManagementService { @Permission( scope = "operation-view", permissions = { - "/permission/admin/device-mgt/admin/devices/view", - "/permission/admin/device-mgt/user/devices/view" + "/permission/admin/device-mgt/admin/devices/view", + "/permission/admin/device-mgt/user/devices/view" } ) Response getDeviceOperations( @@ -563,32 +576,34 @@ public interface DeviceManagementService { 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") @@ -658,21 +673,22 @@ public interface DeviceManagementService { 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 @@ -708,10 +724,13 @@ public interface DeviceManagementService { 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/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..67851128e3 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 @@ -21,12 +21,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.device.mgt.common.DeviceIdentifier; 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; @@ -103,7 +103,7 @@ public interface NotificationManagementService { value = "Status of the notification.", allowableValues = "NEW, CHECKED", required = false) - @QueryParam("status") + @QueryParam("status") @Size(max = 45) String status, @ApiParam( name = "If-Modified-Since", @@ -157,6 +157,6 @@ public interface NotificationManagementService { 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..2531435683 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 @@ -22,9 +22,10 @@ import io.swagger.annotations.*; 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.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; @@ -105,7 +106,7 @@ public interface PolicyManagementService { name = "policy", value = "Policy details related to the operation.", required = true) - PolicyWrapper policy); + @Valid PolicyWrapper policy); @GET @ApiOperation( @@ -306,7 +307,7 @@ public interface PolicyManagementService { name = "policy", value = "Policy details related to the operation.", required = true) - PolicyWrapper policy); + @Valid PolicyWrapper policy); @POST @Path("/remove-policy") 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..34d3ba0fe3 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 @@ -23,6 +23,7 @@ import org.wso2.carbon.apimgt.annotations.api.API; 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; @@ -88,12 +89,16 @@ public interface DeviceManagementAdminService { 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/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..8d3700473c 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 @@ -23,6 +23,7 @@ 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.PasswordResetWrapper; +import javax.validation.constraints.Size; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @@ -70,7 +71,9 @@ public interface UserManagementAdminService { 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 b80889f41b..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; 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 2fafc9b129..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,12 +63,12 @@ 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, @@ -80,7 +81,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { PaginationResult result; DeviceList devices = new DeviceList(); - if(name != null && !name.isEmpty()){ + if (name != null && !name.isEmpty()) { request.setDeviceName(name); } if (type != null && !type.isEmpty()) { @@ -180,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 { @@ -207,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; @@ -258,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) { @@ -287,8 +288,8 @@ 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) { @@ -318,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); @@ -339,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 acfe66f043..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,7 +48,7 @@ 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) { @@ -79,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 a47e85e5c1..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()); @@ -187,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/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 26ac8dd8d2..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 @@ -31,6 +31,7 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminS 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; @@ -45,8 +46,8 @@ 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, 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 3a4c4b5c63..6e99def60f 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 @@ -19,10 +19,10 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl.util; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.PaginationRequest; 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; @@ -317,13 +317,19 @@ public class RequestValidationUtil { if (offset < 0) { throw new InputValidationException( new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter offset is s " + - "negative value.").build()); + "negative value.").build()); } if (limit < 0) { throw new InputValidationException( new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter limit is a " + - "negative value.").build()); + "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/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/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..6d53ee2bc9 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,16 @@ package org.wso2.carbon.device.mgt.jaxrs.util; +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 +63,49 @@ public class DeviceMgtUtil { return profileFeature; } + + /** + * 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/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 1b128fb450..dd3d26f070 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.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..45149c970e 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)) { diff --git a/pom.xml b/pom.xml index f14a0c3a44..e3b11d02f7 100644 --- a/pom.xml +++ b/pom.xml @@ -1080,10 +1080,6 @@ asm asm - - org.apache.cxf - cxf-api - org.apache.cxf cxf-rt-core @@ -1111,10 +1107,6 @@ javax.ws.rs jsr311-api - - org.apache.cxf - cxf-api - org.apache.cxf cxf-rt-core @@ -1140,12 +1132,6 @@ org.apache.cxf cxf-rt-transports-http ${cxf.version} - - - org.apache.cxf - cxf-api - - org.apache.cxf @@ -1521,6 +1507,11 @@ encoder ${owasp.encoder.version} + + org.hibernate + hibernate-validator + ${hibernate-validator.version} + @@ -1891,6 +1882,8 @@ 1.0.2 2.7.4 1.2.0.wso2v1 + + 5.0.2.Final From 2e79dd290e01327d5e48e94d4c406107b8053c11 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 8 Aug 2016 18:24:44 +0530 Subject: [PATCH 17/21] Modified scopes --- .../api/CertificateManagementAdminService.java | 8 ++++---- .../api/ActivityInfoProviderService.java | 4 ++-- .../api/ConfigurationManagementService.java | 2 +- .../service/api/DeviceManagementService.java | 16 ++++++++-------- .../api/NotificationManagementService.java | 4 ++-- .../service/api/PolicyManagementService.java | 18 +++++++++--------- .../service/api/RoleManagementService.java | 16 ++++++++-------- .../service/api/UserManagementService.java | 18 +++++++++--------- .../admin/DeviceManagementAdminService.java | 2 +- .../api/admin/DeviceTypeManagementService.java | 2 +- 10 files changed, 45 insertions(+), 45 deletions(-) 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 226cc53710..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 @@ -77,7 +77,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n Server error occurred while adding certificates.", response = ErrorResponse.class) }) - @Scope(key = "certificate:write", name = "Add certificates", description = "") + @Scope(key = "certificate:manage", name = "Add certificates", description = "") Response addCertificate( @ApiParam( name = "enrollmentCertificates", @@ -135,7 +135,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving information requested certificate.", response = ErrorResponse.class) }) - @Scope(key = "certificate:read", name = "View certificates", description = "") + @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", @@ -207,7 +207,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving all certificates enrolled in the system.", response = ErrorResponse.class) }) - @Scope(key = "certificate:read", name = "View certificates", description = "") + @Scope(key = "certificate:view", name = "View certificates", description = "") Response getAllCertificates( @ApiParam( name = "offset", @@ -250,7 +250,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n " + "Server error occurred while removing the certificate.", response = ErrorResponse.class)}) - @Scope(key = "certificate:write", name = "Add certificates", description = "") + @Scope(key = "certificate:manage", name = "Add certificates", description = "") Response removeCertificate( @ApiParam( name = "serialNumber", 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 e01511c93e..50f596be47 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 @@ -91,7 +91,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Scope(key = "activity:read", name = "View Activities", description = "") + @Scope(key = "activity:view", name = "View Activities", description = "") Response getActivity( @ApiParam( name = "id", @@ -150,7 +150,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Scope(key = "activity:read", name = "View Activities", description = "") + @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 d6a2b3bad9..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 @@ -81,7 +81,7 @@ public interface ConfigurationManagementService { "platform configuration.", response = ErrorResponse.class) }) - @Scope(key = "configuration:read", name = "View Configurations", description = "") + @Scope(key = "configuration:view", name = "View Configurations", description = "") Response getConfiguration( @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/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 19bc4be795..35d97cc48e 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 @@ -91,7 +91,7 @@ public interface DeviceManagementService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getDevices( @ApiParam( name = "name", @@ -200,7 +200,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getDevice( @ApiParam( name = "type", @@ -280,7 +280,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getFeaturesOfDevice( @ApiParam( name = "type", @@ -354,7 +354,7 @@ public interface DeviceManagementService { "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response searchDevices( @ApiParam( name = "offset", @@ -433,7 +433,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getInstalledApplications( @ApiParam( name = "type", @@ -527,7 +527,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getDeviceOperations( @ApiParam( name = "type", @@ -623,7 +623,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getEffectivePolicyOfDevice( @ApiParam( name = "type", @@ -674,7 +674,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device:read", name = "View Devices", description = "") + @Scope(key = "device:view", name = "View Devices", description = "") Response getComplianceDataOfDevice( @ApiParam( name = "type", 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 f479b310c9..181c2e5983 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 @@ -88,7 +88,7 @@ public interface NotificationManagementService { "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) }) - @Scope(key = "notification:read", name = "View and manage notifications", description = "") + @Scope(key = "notification:view", name = "View and manage notifications", description = "") Response getNotifications( @ApiParam( name = "status", @@ -140,7 +140,7 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Scope(key = "notification:read", name = "View and manage notifications", description = "") + @Scope(key = "notification:view", name = "View and manage notifications", description = "") Response updateNotificationStatus( @ApiParam( name = "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 f75857e6f8..00175e3ca9 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 @@ -99,7 +99,7 @@ public interface PolicyManagementService { "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response addPolicy( @ApiParam( name = "policy", @@ -153,7 +153,7 @@ public interface PolicyManagementService { "policies."), response = ErrorResponse.class) }) - @Scope(key = "policy:read", name = "Views policies", description = "") + @Scope(key = "policy:view", name = "Views policies", description = "") Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -219,7 +219,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:read", name = "View policies", description = "") + @Scope(key = "policy:view", name = "View policies", description = "") Response getPolicy( @ApiParam( name = "id", @@ -283,7 +283,7 @@ public interface PolicyManagementService { "Server error occurred while updating the policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response updatePolicy( @ApiParam( name = "id", @@ -329,7 +329,7 @@ public interface PolicyManagementService { "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response removePolicies( @ApiParam( name = "policyIds", @@ -365,7 +365,7 @@ public interface PolicyManagementService { message = "ErrorResponse in activating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response activatePolicies( @ApiParam( name = "policyIds", @@ -401,7 +401,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -434,7 +434,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @Scope(key = "policy:manage", name = "Add policies", description = "") Response applyChanges(); @@ -463,7 +463,7 @@ public interface PolicyManagementService { message = "Exception in updating policy priorities.", response = ErrorResponse.class) }) - @Scope(key = "policy:write", name = "Add policies", description = "") + @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 73fcb77bb2..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 @@ -76,7 +76,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") Response getRoles( @ApiParam( name = "filter", @@ -158,7 +158,7 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") Response getScopes( @ApiParam( name = "If-Modified-Since", @@ -208,7 +208,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the scopes.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response updateScopes( @ApiParam( name = "Scopes", @@ -265,7 +265,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:read", name = "View roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") Response getRole( @ApiParam( name = "roleName", @@ -325,7 +325,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response addRole( @ApiParam( name = "role", @@ -375,7 +375,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response updateRole( @ApiParam( name = "roleName", @@ -412,7 +412,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") + @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") Response deleteRole( @ApiParam( name = "roleName", @@ -474,7 +474,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:add", name = "Add roles", description = "") + @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 d90cc14b7b..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 @@ -83,7 +83,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while adding a new user.", response = ErrorResponse.class) }) - @Scope(key = "user:write", name = "Add users", description = "") + @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) }) - @Scope(key = "user:read", name = "View users", description = "") + @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) }) - @Scope(key = "user:write", name = "Add users", description = "") + @Scope(key = "user:manage", name = "Add users", description = "") Response updateUser( @ApiParam( name = "username", @@ -227,7 +227,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Scope(key = "user:write", name = "Add users", description = "") + @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) }) - @Scope(key = "user:read", name = "View users", description = "") + @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) }) - @Scope(key = "user:read", name = "View users", description = "") + @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) }) - @Scope(key = "user:read", name = "View users", description = "") + @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) }) - @Scope(key = "user:read", name = "View users", description = "") + @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) }) - @Scope(key = "user:write", name = "Add users", description = "") + @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/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 e90e346eeb..266357366e 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 @@ -84,7 +84,7 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Scope(key = "device:admin:read", name = "View Devices", description = "") + @Scope(key = "device:admin:view", name = "View Devices", description = "") Response getDevicesByName( @ApiParam( name = "name", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java index 39970a7e5d..4212f65ceb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceTypeManagementService.java @@ -78,7 +78,7 @@ public interface DeviceTypeManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device-type:admin:read", name = "View device types", description = "") + @Scope(key = "device-type:admin:view", name = "View device types", description = "") Response getDeviceTypes( @ApiParam( name = "If-Modified-Since", From 952905c60da5b4be7e4b5e2c39e1608733dd40fe Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 8 Aug 2016 18:26:50 +0530 Subject: [PATCH 18/21] Adding Policy Edit UI --- .../app/modules/business-controllers/user.js | 3 +- .../app/pages/cdmf.page.policy.edit/edit.hbs | 19 +- .../app/pages/cdmf.page.policy.edit/edit.js | 10 +- .../app/pages/cdmf.page.policy.edit/edit.json | 2 +- .../app/units/cdmf.unit.policy.edit/edit.hbs | 233 + .../app/units/cdmf.unit.policy.edit/edit.js | 36 + .../app/units/cdmf.unit.policy.edit/edit.json | 3 + .../cdmf.unit.policy.edit/public/js/edit.js | 2554 +++++++++ .../templates/hidden-operations-android.hbs | 1225 +++++ .../templates/hidden-operations-ios.hbs | 4679 +++++++++++++++++ .../templates/hidden-operations-windows.hbs | 568 ++ 11 files changed, 9317 insertions(+), 15 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.js create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.json create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/js/edit.js create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-android.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-ios.hbs create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-windows.hbs diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index 720cbc4629..8e885cd00b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -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; 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..2bed273c68 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 @@ -16,8 +16,8 @@ * under the License. */ -function onRequest(context) { - var utility = require("/app/modules/utility.js").utility; - var deviceType = request.getParameter("type"); - return {"deviceTypePolicyEdit": utility.getTenantedDeviceUnitName(deviceType, "policy-edit")}; -} +//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/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.edit/public/js/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/js/edit.js new file mode 100644 index 0000000000..89252aaf16 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/js/edit.js @@ -0,0 +1,2554 @@ +/* + * 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 validateStep = {}; +var skipStep = {}; +var stepForwardFrom = {}; +var stepBackFrom = {}; +var policy = {}; +var configuredOperations = []; +var currentlyEffected = {}; + +var validateInline = {}; +var clearInline = {}; + +var enableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).addClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).removeClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).removeClass(" hidden"); + } +}; + +var disableInlineError = function (inputField, errorMsg, errorSign) { + var fieldIdentifier = "#" + inputField; + var errorMsgIdentifier = "#" + inputField + " ." + errorMsg; + var errorSignIdentifier = "#" + inputField + " ." + errorSign; + + if (inputField) { + $(fieldIdentifier).removeClass(" has-error has-feedback"); + } + + if (errorMsg) { + $(errorMsgIdentifier).addClass(" hidden"); + } + + if (errorSign) { + $(errorSignIdentifier).addClass(" hidden"); + } +}; + +/** + *clear inline validation messages. + */ +clearInline["policy-name"] = function () { + disableInlineError("policy-name-field", "nameEmpty", "nameError"); +}; + + +/** + * Validate if provided policy name is valid against RegEx configures. + */ +validateInline["policy-name"] = function () { + var policyName = $("input#policy-name-input").val(); + if (policyName && inputIsValidAgainstLength(policyName, 1, 30)) { + disableInlineError("policy-name-field", "nameEmpty", "nameError"); + } else { + enableInlineError("policy-name-field", "nameEmpty", "nameError"); + } +}; + +$("#policy-name-input").focus(function(){ + clearInline["policy-name"](); +}).blur(function(){ + validateInline["policy-name"](); +}); + +// Constants to define platform types available +var platformTypeConstants = { + "ANDROID": "android", + "IOS": "ios", + "WINDOWS": "windows" +}; + +// Constants to define platform types ids. +var platformTypeIds = { + "ANDROID": 1, + "IOS": 3, + "WINDOWS": 2 +}; + +// Constants to define Android Operation Constants +var androidOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "CAMERA_OPERATION": "camera", + "CAMERA_OPERATION_CODE": "CAMERA", + "ENCRYPT_STORAGE_OPERATION": "encrypt-storage", + "ENCRYPT_STORAGE_OPERATION_CODE": "ENCRYPT_STORAGE", + "WIFI_OPERATION": "wifi", + "WIFI_OPERATION_CODE": "WIFI", + "APPLICATION_OPERATION":"app-restriction", + "APPLICATION_OPERATION_CODE":"APP-RESTRICTION" +}; + +// Constants to define Android Operation Constants +var windowsOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "CAMERA_OPERATION": "camera", + "CAMERA_OPERATION_CODE": "CAMERA", + "ENCRYPT_STORAGE_OPERATION": "encrypt-storage", + "ENCRYPT_STORAGE_OPERATION_CODE": "ENCRYPT_STORAGE" +}; + +// Constants to define iOS Operation Constants +var iosOperationConstants = { + "PASSCODE_POLICY_OPERATION": "passcode-policy", + "PASSCODE_POLICY_OPERATION_CODE": "PASSCODE_POLICY", + "RESTRICTIONS_OPERATION": "restrictions", + "RESTRICTIONS_OPERATION_CODE": "RESTRICTION", + "WIFI_OPERATION": "wifi", + "WIFI_OPERATION_CODE": "WIFI", + "EMAIL_OPERATION": "email", + "EMAIL_OPERATION_CODE": "EMAIL", + "AIRPLAY_OPERATION": "airplay", + "AIRPLAY_OPERATION_CODE": "AIR_PLAY", + "LDAP_OPERATION": "ldap", + "LDAP_OPERATION_CODE": "LDAP", + "CALENDAR_OPERATION": "calendar", + "CALENDAR_OPERATION_CODE": "CALDAV", + "CALENDAR_SUBSCRIPTION_OPERATION": "calendar-subscription", + "CALENDAR_SUBSCRIPTION_OPERATION_CODE": "CALENDAR_SUBSCRIPTION", + "APN_OPERATION": "apn", + "APN_OPERATION_CODE": "APN", + "CELLULAR_OPERATION": "cellular", + "CELLULAR_OPERATION_CODE": "CELLULAR" +}; + +/** + * Method to update the visibility (i.e. disabled or enabled view) + * of grouped input according to the values + * that they currently possess. + * @param domElement HTML grouped-input element with class name "grouped-input" + */ +var updateGroupedInputVisibility = function (domElement) { + if ($(".parent-input:first", domElement).is(":checked")) { + if ($(".grouped-child-input:first", domElement).hasClass("disabled")) { + $(".grouped-child-input:first", domElement).removeClass("disabled"); + } + $(".child-input", domElement).each(function () { + $(this).prop('disabled', false); + }); + } else { + if (!$(".grouped-child-input:first", domElement).hasClass("disabled")) { + $(".grouped-child-input:first", domElement).addClass("disabled"); + } + $(".child-input", domElement).each(function () { + $(this).prop('disabled', true); + }); + } +}; + +skipStep["policy-platform"] = function (policyPayloadObj) { + policy["name"] = policyPayloadObj["policyName"]; + policy["platform"] = policyPayloadObj["profile"]["deviceType"]; + + var userRoleInput = $("#user-roles-input"); + var ownershipInput = $("#ownership-input"); + var userInput = $("#users-input"); + var actionInput = $("#action-input"); + var policyNameInput = $("#policy-name-input"); + var policyDescriptionInput = $("#policy-description-input"); + + currentlyEffected["roles"] = policyPayloadObj.roles; + currentlyEffected["users"] = policyPayloadObj.users; + + if (currentlyEffected["roles"].length > 0) { + $("#user-roles-radio-btn").prop("checked", true); + $("#user-roles-select-field").show(); + $("#users-select-field").hide(); + userRoleInput.val(currentlyEffected["roles"]).trigger("change"); + } else if (currentlyEffected["users"].length > 0) { + $("#users-radio-btn").prop("checked", true); + $("#users-select-field").show(); + $("#user-roles-select-field").hide(); + userInput.val(currentlyEffected["users"]).trigger("change"); + } + + ownershipInput.val(policyPayloadObj.ownershipType); + actionInput.val(policyPayloadObj.compliance); + policyNameInput.val(policyPayloadObj["policyName"]); + policyDescriptionInput.val(policyPayloadObj["description"]); + // updating next-page wizard title with selected platform + $("#policy-profile-page-wizard-title").text("EDIT " + policy["platform"] + " POLICY - " + policy["name"]); + + var deviceType = policy["platform"]; + var hiddenOperationsByDeviceType = $("#hidden-operations-" + deviceType); + var hiddenOperationsByDeviceTypeCacheKey = deviceType + "HiddenOperations"; + var hiddenOperationsByDeviceTypeSrc = hiddenOperationsByDeviceType.attr("src"); + + setTimeout( + function () { + $.template(hiddenOperationsByDeviceTypeCacheKey, hiddenOperationsByDeviceTypeSrc, function (template) { + var content = template(); + // pushing profile feature input elements + $(".wr-advance-operations").html(content); + // populating values and getting the list of configured features + var configuredOperations = operationModule. + populateProfile(policy["platform"], policyPayloadObj["profile"]["profileFeaturesList"]); + // updating grouped input visibility according to the populated values + $(".wr-advance-operations li.grouped-input").each(function () { + updateGroupedInputVisibility(this); + }); + // enabling previously configured options of last update + for (var i = 0; i < configuredOperations.length; ++i) { + var configuredOperation = configuredOperations[i]; + $(".operation-data").filterByData("operation-code", configuredOperation). + find(".panel-title .wr-input-control.switch input[type=checkbox]"). + each(function () {$(this).click();}); + } + }); + }, + 250 // time delayed for the execution of above function, 250 milliseconds + ); +}; + +/** + * Checks if provided number is valid against a range. + * + * @param numberInput Number Input + * @param min Minimum Limit + * @param max Maximum Limit + * @returns {boolean} Returns true if input is within the specified range + */ +var inputIsValidAgainstRange = function (numberInput, min, max) { + return (numberInput == min || (numberInput > min && numberInput < max) || numberInput == max); +}; + +/** + * Checks if provided input is valid against RegEx input. + * + * @param regExp Regular expression + * @param input Input string to check + * @returns {boolean} Returns true if input matches RegEx + */ +var inputIsValidAgainstRegExp = function (regExp, input) { + return regExp.test(input); +}; + +validateStep["policy-profile"] = function () { + var validationStatusArray = []; + var validationStatus; + var operation; + + // starting validation process and updating validationStatus + if (policy["platform"] == platformTypeConstants["ANDROID"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(androidOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = androidOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + var continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + var passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + var passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CAMERA + if ($.inArray(androidOperationConstants["CAMERA_OPERATION_CODE"], configuredOperations) != -1) { + // if CAMERA is configured + operation = androidOperationConstants["CAMERA_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating ENCRYPT_STORAGE + if ($.inArray(androidOperationConstants["ENCRYPT_STORAGE_OPERATION_CODE"], configuredOperations) != -1) { + // if ENCRYPT_STORAGE is configured + operation = androidOperationConstants["ENCRYPT_STORAGE_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating WIFI + if ($.inArray(androidOperationConstants["WIFI_OPERATION_CODE"], configuredOperations) != -1) { + // if WIFI is configured + operation = androidOperationConstants["WIFI_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var wifiSSID = $("input#wifi-ssid").val(); + if (!wifiSSID) { + validationStatus = { + "error": true, + "subErrorMsg": "WIFI SSID is not given. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + if ($.inArray(androidOperationConstants["APPLICATION_OPERATION_CODE"], configuredOperations) != -1) { + //If application restriction configured + operation = androidOperationConstants["APPLICATION_OPERATION"]; + // Initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var appRestrictionType = $("#app-restriction-type").val(); + + var restrictedApplicationsGridChildInputs = "div#restricted-applications .child-input"; + + if (!appRestrictionType) { + validationStatus = { + "error": true, + "subErrorMsg": "Applications restriction type is not provided.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + if ($(restrictedApplicationsGridChildInputs).length == 0) { + validationStatus = { + "error": true, + "subErrorMsg": "Applications are not provided in application restriction list.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + else { + childInputCount = 0; + childInputArray = []; + emptyChildInputCount = 0; + duplicatesExist = false; + // Looping through each child input + $(restrictedApplicationsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 2 == 0) { + // If child input is of second column + childInput = $(this).val(); + childInputArray.push(childInput); + // Updating emptyChildInputCount + if (!childInput) { + // If child input field is empty + emptyChildInputCount++; + } + } + }); + // Checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // Updating validationStatus + if (emptyChildInputCount > 0) { + // If empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more package names of " + + "applications are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // If duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "for package names.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + } + } + + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // Updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + + + } + } + } if (policy["platform"] == platformTypeConstants["WINDOWS"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(windowsOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = windowsOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + var continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + var passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + var passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CAMERA + if ($.inArray(windowsOperationConstants["CAMERA_OPERATION_CODE"], configuredOperations) != -1) { + // if CAMERA is configured + operation = windowsOperationConstants["CAMERA_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating ENCRYPT_STORAGE + if ($.inArray(windowsOperationConstants["ENCRYPT_STORAGE_OPERATION_CODE"], configuredOperations) != -1) { + // if ENCRYPT_STORAGE is configured + operation = windowsOperationConstants["ENCRYPT_STORAGE_OPERATION"]; + // updating validationStatus + validationStatus = { + "error": false, + "okFeature": operation + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + + } + } else if (policy["platform"] == platformTypeConstants["IOS"]) { + if (configuredOperations.length == 0) { + // updating validationStatus + validationStatus = { + "error": true, + "mainErrorMsg": "You cannot continue. Zero configured features." + }; + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } else { + // validating each and every configured Operation + // Validating PASSCODE_POLICY + if ($.inArray(iosOperationConstants["PASSCODE_POLICY_OPERATION_CODE"], configuredOperations) != -1) { + // if PASSCODE_POLICY is configured + operation = iosOperationConstants["PASSCODE_POLICY_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // validating first input: passcodePolicyMaxPasscodeAgeInDays + passcodePolicyMaxPasscodeAgeInDays = $("input#passcode-policy-max-passcode-age-in-days").val(); + if (passcodePolicyMaxPasscodeAgeInDays) { + if (!$.isNumeric(passcodePolicyMaxPasscodeAgeInDays)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyMaxPasscodeAgeInDays, 1, 730)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode age is not with in the range of 1-to-730.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // validating second and last input: passcodePolicyPasscodeHistory + if (continueToCheckNextInputs) { + passcodePolicyPasscodeHistory = $("input#passcode-policy-passcode-history").val(); + if (passcodePolicyPasscodeHistory) { + if (!$.isNumeric(passcodePolicyPasscodeHistory)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not a number.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(passcodePolicyPasscodeHistory, 1, 50)) { + validationStatus = { + "error": true, + "subErrorMsg": "Provided passcode history is not with in the range of 1-to-50.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating RESTRICTIONS + if ($.inArray(iosOperationConstants["RESTRICTIONS_OPERATION_CODE"], configuredOperations) != -1) { + // if RESTRICTION is configured + operation = iosOperationConstants["RESTRICTIONS_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // getting input values to be validated + var restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs = + "div#restrictions-autonomous-single-app-mode-permitted-app-ids .child-input"; + if ($(restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs).length > 0) { + var childInput; + var childInputArray = []; + var emptyChildInputCount = 0; + var duplicatesExist = false; + // looping through each child input + $(restrictionsAutonomousSingleAppModePermittedAppIDsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + var initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + var m, poppedChildInput; + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + var n; + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more permitted App ID entries in " + + "Autonomous Single App Mode are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with permitted App ID entries in " + + "Autonomous Single App Mode.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating WIFI + if ($.inArray(iosOperationConstants["WIFI_OPERATION_CODE"], configuredOperations) != -1) { + // if WIFI is configured + operation = iosOperationConstants["WIFI_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + // getting input values to be validated + wifiSSID = $("input#wifi-ssid").val(); + var wifiDomainName = $("input#wifi-domain-name").val(); + if (!wifiSSID && !wifiDomainName) { + validationStatus = { + "error": true, + "subErrorMsg": "Both Wi-Fi SSID and Wi-Fi Domain Name are not given. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + // getting proxy-setup value + var wifiProxyType = $("select#wifi-proxy-type").find("option:selected").attr("value"); + if (wifiProxyType == "Manual") { + // adds up additional fields to be validated + var wifiProxyServer = $("input#wifi-proxy-server").val(); + if (!wifiProxyServer) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Server is required. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var wifiProxyPort = $("input#wifi-proxy-port").val(); + if (!wifiProxyPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port is required. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(wifiProxyPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(wifiProxyPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Wi-Fi Proxy Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + } + + if (continueToCheckNextInputs) { + // getting encryption-type value + var wifiEncryptionType = $("select#wifi-encryption-type").find("option:selected").attr("value"); + if (wifiEncryptionType != "None") { + var wifiPayloadCertificateAnchorUUIDsGridChildInputs = + "div#wifi-payload-certificate-anchor-uuids .child-input"; + if ($(wifiPayloadCertificateAnchorUUIDsGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiPayloadCertificateAnchorUUIDsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Payload Certificate " + + "Anchor UUIDs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist " + + "with Payload Certificate Anchor UUIDs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var wifiTLSTrustedServerNamesGridChildInputs = + "div#wifi-tls-trusted-server-names .child-input"; + if ($(wifiTLSTrustedServerNamesGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiTLSTrustedServerNamesGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more TLS Trusted Server Names are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist " + + "with TLS Trusted Server Names.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + } + } + + if (continueToCheckNextInputs) { + var wifiRoamingConsortiumOIsGridChildInputs = "div#wifi-roaming-consortium-ois .child-input"; + if ($(wifiRoamingConsortiumOIsGridChildInputs).length > 0) { + emptyChildInputCount = 0; + var outOfAllowedLengthCount = 0; + var invalidAgainstRegExCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiRoamingConsortiumOIsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!inputIsValidAgainstLength(childInput, 6, 6) && !inputIsValidAgainstLength(childInput, 10, 10)) { + outOfAllowedLengthCount++; + } else if (!inputIsValidAgainstRegExp(/^[a-fA-F0-9]+$/, childInput)) { + invalidAgainstRegExCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (outOfAllowedLengthCount > 0) { + // if outOfMaxAllowedLength input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs " + + "are out of allowed length.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (invalidAgainstRegExCount > 0) { + // if invalid inputs in terms of hexadecimal format are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Roaming Consortium OIs " + + "contain non-hexadecimal characters.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with Roaming Consortium OIs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + var wifiNAIRealmNamesGridChildInputs = "div#wifi-nai-realm-names .child-input"; + if ($(wifiNAIRealmNamesGridChildInputs).length > 0) { + emptyChildInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiNAIRealmNamesGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more NAI Realm Names are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with NAI Realm Names.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + var wifiMCCAndMNCsGridChildInputs = "div#wifi-mcc-and-mncs .child-input"; + if ($(wifiMCCAndMNCsGridChildInputs).length > 0) { + var childInputCount = 0; + var stringPair; + emptyChildInputCount = 0; + outOfAllowedLengthCount = 0; + var notNumericInputCount = 0; + childInputArray = []; + duplicatesExist = false; + // looping through each child input + $(wifiMCCAndMNCsGridChildInputs).each(function () { + childInput = $(this).val(); + // pushing each string pair to childInputArray + childInputCount++; + if (childInputCount % 2 == 1) { + // initialize stringPair value + stringPair = ""; + // append first part of the string + stringPair += childInput; + } else { + // append second part of the string + stringPair += childInput; + childInputArray.push(stringPair); + } + // updating emptyChildInputCount & outOfAllowedLengthCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!$.isNumeric(childInput)) { + notNumericInputCount++; + } else if (!inputIsValidAgainstLength(childInput, 3, 3)) { + outOfAllowedLengthCount++; + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (notNumericInputCount > 0) { + // if notNumeric input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs are not numeric.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (outOfAllowedLengthCount > 0) { + // if outOfAllowedLength input is present + validationStatus = { + "error": true, + "subErrorMsg": "One or more MCC/MNC pairs " + + "do not fulfill the accepted length of 6 digits.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with MCC/MNC pairs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating EMAIL + if ($.inArray(iosOperationConstants["EMAIL_OPERATION_CODE"], configuredOperations) != -1) { + // if EMAIL is configured + operation = iosOperationConstants["EMAIL_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var emailAddress = $("input#email-address").val(); + if (emailAddress && !inputIsValidAgainstRegExp(/^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/, emailAddress)) { + validationStatus = { + "error": true, + "subErrorMsg": "Email Address is not valid.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var emailIncomingMailServerHostname = $("input#email-incoming-mail-server-hostname").val(); + if (!emailIncomingMailServerHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Hostname is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var emailIncomingMailServerPort = $("input#email-incoming-mail-server-port").val(); + if (emailIncomingMailServerPort && emailIncomingMailServerPort != '') { + if (!$.isNumeric(emailIncomingMailServerPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(emailIncomingMailServerPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Incoming Mail Server Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + var emailOutgoingMailServerHostname = $("input#email-outgoing-mail-server-hostname").val(); + if (!emailOutgoingMailServerHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Hostname is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + if (continueToCheckNextInputs) { + var emailOutgoingMailServerPort = $("input#email-outgoing-mail-server-port").val(); + if (emailOutgoingMailServerPort && emailOutgoingMailServerPort != '') { + if (!$.isNumeric(emailOutgoingMailServerPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(emailOutgoingMailServerPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Outgoing Mail Server Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating AIRPLAY + if ($.inArray(iosOperationConstants["AIRPLAY_OPERATION_CODE"], configuredOperations) != -1) { + // if AIRPLAY is configured + operation = iosOperationConstants["AIRPLAY_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var airplayCredentialsGridChildInputs = "div#airplay-credentials .child-input"; + var airplayDestinationsGridChildInputs = "div#airplay-destinations .child-input"; + if ($(airplayCredentialsGridChildInputs).length == 0 && + $(airplayDestinationsGridChildInputs).length == 0) { + validationStatus = { + "error": true, + "subErrorMsg": "AirPlay settings have zero configurations attached.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + if ($(airplayCredentialsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(airplayCredentialsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 2 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Device Names of " + + "AirPlay Credentials are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "Device Names of AirPlay Credentials.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + if (continueToCheckNextInputs) { + if ($(airplayDestinationsGridChildInputs).length > 0) { + childInputArray = []; + emptyChildInputCount = 0; + invalidAgainstRegExCount = 0; + duplicatesExist = false; + // looping through each child input + $(airplayDestinationsGridChildInputs).each(function () { + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } else if (!inputIsValidAgainstRegExp( + /([a-z|A-Z|0-9][a-z|A-Z|0-9][:]){5}([a-z|A-Z|0-9][a-z|A-Z|0-9])$/, childInput)) { + // if child input field is invalid against RegEx + invalidAgainstRegExCount++ + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more AirPlay Destination fields are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (invalidAgainstRegExCount > 0) { + // if invalidAgainstRegEx inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more AirPlay Destination fields " + + "do not fulfill expected format.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with AirPlay Destinations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating LDAP + if ($.inArray(iosOperationConstants["LDAP_OPERATION_CODE"], configuredOperations) != -1) { + // if LDAP is configured + operation = iosOperationConstants["LDAP_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var ldapAccountHostname = $("input#ldap-account-hostname").val(); + if (!ldapAccountHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "LDAP Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var ldapSearchSettingsGridChildInputs = "div#ldap-search-settings .child-input"; + if ($(ldapSearchSettingsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(ldapSearchSettingsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 3 == 2) { + // if child input is of second column + childInput = $(this).find("option:selected").attr("value"); + stringPair = ""; + stringPair += (childInput + " "); + } else if (childInputCount % 3 == 0) { + // if child input is of third column + childInput = $(this).val(); + stringPair += childInput; + childInputArray.push(stringPair); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more Search Setting Scope fields are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "Search Setting Search Base and Scope pairs.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CALENDAR + if ($.inArray(iosOperationConstants["CALENDAR_OPERATION_CODE"], configuredOperations) != -1) { + // if CALENDAR is configured + operation = iosOperationConstants["CALENDAR_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var calendarAccountHostname = $("input#calendar-account-hostname").val(); + if (!calendarAccountHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var calendarAccountPort = $("input#calendar-account-port").val(); + if (!calendarAccountPort) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!$.isNumeric(calendarAccountPort)) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port requires a number input.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (!inputIsValidAgainstRange(calendarAccountPort, 0, 65535)) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Port is not within the range " + + "of valid port numbers.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CALENDAR_SUBSCRIPTION + if ($.inArray(iosOperationConstants["CALENDAR_SUBSCRIPTION_OPERATION_CODE"], configuredOperations) != -1) { + // if CALENDAR_SUBSCRIPTION is configured + operation = iosOperationConstants["CALENDAR_SUBSCRIPTION_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var calendarSubscriptionHostname = $("input#calendar-subscription-hostname").val(); + if (!calendarSubscriptionHostname) { + validationStatus = { + "error": true, + "subErrorMsg": "Account Hostname URL is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating APN + if ($.inArray(iosOperationConstants["APN_OPERATION_CODE"], configuredOperations) != -1) { + // if APN is configured + operation = iosOperationConstants["APN_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var apnConfigurationsGridChildInputs = "div#apn-configurations .child-input"; + if ($(apnConfigurationsGridChildInputs).length == 0) { + validationStatus = { + "error": true, + "subErrorMsg": "APN Settings have zero configurations attached.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if ($(apnConfigurationsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + // checking empty APN field count + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(apnConfigurationsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 5 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more APN fields of Configurations are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "APN fields of Configurations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + // Validating CELLULAR + if ($.inArray(iosOperationConstants["CELLULAR_OPERATION_CODE"], configuredOperations) != -1) { + // if CELLULAR is configured + operation = iosOperationConstants["CELLULAR_OPERATION"]; + // initializing continueToCheckNextInputs to true + continueToCheckNextInputs = true; + + var cellularAttachAPNName = $("input#cellular-attach-apn-name").val(); + if (!cellularAttachAPNName) { + validationStatus = { + "error": true, + "subErrorMsg": "Cellular Configuration Name is empty. You cannot proceed.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + + if (continueToCheckNextInputs) { + var cellularAPNConfigurationsGridChildInputs = "div#cellular-apn-configurations .child-input"; + if ($(cellularAPNConfigurationsGridChildInputs).length > 0) { + childInputCount = 0; + childInputArray = []; + // checking empty APN field count + emptyChildInputCount = 0; + duplicatesExist = false; + // looping through each child input + $(cellularAPNConfigurationsGridChildInputs).each(function () { + childInputCount++; + if (childInputCount % 6 == 1) { + // if child input is of first column + childInput = $(this).val(); + childInputArray.push(childInput); + // updating emptyChildInputCount + if (!childInput) { + // if child input field is empty + emptyChildInputCount++; + } + } + }); + // checking for duplicates + initialChildInputArrayLength = childInputArray.length; + if (emptyChildInputCount == 0 && initialChildInputArrayLength > 1) { + for (m = 0; m < (initialChildInputArrayLength - 1); m++) { + poppedChildInput = childInputArray.pop(); + for (n = 0; n < childInputArray.length; n++) { + if (poppedChildInput == childInputArray[n]) { + duplicatesExist = true; + break; + } + } + if (duplicatesExist) { + break; + } + } + } + // updating validationStatus + if (emptyChildInputCount > 0) { + // if empty child inputs are present + validationStatus = { + "error": true, + "subErrorMsg": "One or more APN fields of APN Configurations are empty.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } else if (duplicatesExist) { + // if duplicate input is present + validationStatus = { + "error": true, + "subErrorMsg": "Duplicate values exist with " + + "APN fields of APN Configurations.", + "erroneousFeature": operation + }; + continueToCheckNextInputs = false; + } + } + } + + // at-last, if the value of continueToCheckNextInputs is still true + // this means that no error is found + if (continueToCheckNextInputs) { + validationStatus = { + "error": false, + "okFeature": operation + }; + } + + // updating validationStatusArray with validationStatus + validationStatusArray.push(validationStatus); + } + } + } + // ending validation process + + // start taking specific notifying actions upon validation + var wizardIsToBeContinued; + var errorCount = 0; + var mainErrorMsgWrapper, mainErrorMsg, + subErrorMsgWrapper, subErrorMsg, subErrorIcon, subOkIcon, featureConfiguredIcon; + var i; + for (i = 0; i < validationStatusArray.length; i++) { + validationStatus = validationStatusArray[i]; + if (validationStatus["error"]) { + errorCount++; + if (validationStatus["mainErrorMsg"]) { + mainErrorMsgWrapper = "#policy-profile-main-error-msg"; + mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else if (validationStatus["subErrorMsg"]) { + subErrorMsgWrapper = "#" + validationStatus["erroneousFeature"] + "-feature-error-msg"; + subErrorMsg = subErrorMsgWrapper + " span"; + subErrorIcon = "#" + validationStatus["erroneousFeature"] + "-error"; + subOkIcon = "#" + validationStatus["erroneousFeature"] + "-ok"; + featureConfiguredIcon = "#" + validationStatus["erroneousFeature"] + "-configured"; + // hiding featureConfiguredState as the first step + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // updating error state and corresponding messages + $(subErrorMsg).text(validationStatus["subErrorMsg"]); + if ($(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).removeClass("hidden"); + } + if (!$(subOkIcon).hasClass("hidden")) { + $(subOkIcon).addClass("hidden"); + } + if ($(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).removeClass("hidden"); + } + } + } else { + if (validationStatus["okFeature"]) { + subErrorMsgWrapper = "#" + validationStatus["okFeature"] + "-feature-error-msg"; + subErrorIcon = "#" + validationStatus["okFeature"] + "-error"; + subOkIcon = "#" + validationStatus["okFeature"] + "-ok"; + featureConfiguredIcon = "#" + validationStatus["okFeature"] + "-configured"; + // hiding featureConfiguredState as the first step + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // updating success state and corresponding messages + if (!$(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).addClass("hidden"); + } + if (!$(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).addClass("hidden"); + } + if ($(subOkIcon).hasClass("hidden")) { + $(subOkIcon).removeClass("hidden"); + } + } + } + } + + wizardIsToBeContinued = (errorCount == 0); + return wizardIsToBeContinued; +}; + +stepForwardFrom["policy-profile"] = function () { + policy["profile"] = operationModule.generateProfile(policy["platform"], configuredOperations); + // updating next-page wizard title with selected platform + $("#policy-criteria-page-wizard-title").text("EDIT " + policy["platform"] + " POLICY - " + policy["name"]); + // updating ownership type options according to platform + if (policy["platform"] == platformTypeConstants["IOS"] || + policy["platform"] == platformTypeConstants["WINDOWS"]) { + var ownershipTypeSelectOptions = $("#ownership-input"); + ownershipTypeSelectOptions.empty(); + ownershipTypeSelectOptions.append($(""). + attr("value", "BYOD").text("BYOD (Bring Your Own Device)")); + ownershipTypeSelectOptions.attr("disabled", true); + } +}; + +stepForwardFrom["policy-criteria"] = function () { + $("input[type='radio'].select-users-radio").each(function () { + if ($(this).is(':radio')) { + if ($(this).is(":checked")) { + if ($(this).attr("id") == "users-radio-btn") { + policy["selectedUsers"] = $("#users-input").val(); + policy["selectedUserRoles"] = null; + } else if ($(this).attr("id") == "user-roles-radio-btn") { + policy["selectedUsers"] = null; + policy["selectedUserRoles"] = $("#user-roles-input").val(); + } + } + } + }); + policy["selectedNonCompliantAction"] = $("#action-input").find(":selected").data("action"); + policy["selectedOwnership"] = $("#ownership-input").val(); + // updating next-page wizard title with selected platform + $("#policy-naming-page-wizard-title").text("EDIT " + policy["platform"] + " POLICY - " + policy["name"]); +}; + +/** + * Checks if provided input is valid against provided length range. + * + * @param input Alphanumeric or non-alphanumeric input + * @param minLength Minimum Required Length + * @param maxLength Maximum Required Length + * @returns {boolean} Returns true if input matches the provided minimum length and maximum length + */ +var inputIsValidAgainstLength = function (input, minLength, maxLength) { + var length = input.length; + return (length == minLength || (length > minLength && length < maxLength) || length == maxLength); +}; + +validateStep["policy-criteria"] = function () { + var validationStatus = {}; + var selectedAssignees; + var selectedField = "Role(s)"; + + $("input[type='radio'].select-users-radio").each(function () { + if ($(this).is(":checked")) { + if ($(this).attr("id") == "users-radio-btn") { + selectedAssignees = $("#users-input").val(); + selectedField = "User(s)"; + } else if ($(this).attr("id") == "user-roles-radio-btn") { + selectedAssignees = $("#user-roles-input").val(); + } + return false; + } + }); + + if (selectedAssignees) { + validationStatus["error"] = false; + } else { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = selectedField + " is a required field. It cannot be empty"; + } + + var wizardIsToBeContinued; + if (validationStatus["error"]) { + wizardIsToBeContinued = false; + var mainErrorMsgWrapper = "#policy-criteria-main-error-msg"; + var mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else { + wizardIsToBeContinued = true; + } + + return wizardIsToBeContinued; +}; + +validateStep["policy-naming"] = function () { + var validationStatus = {}; + + // taking values of inputs to be validated + var policyName = $("input#policy-name-input").val(); + // starting validation process and updating validationStatus + if (!policyName) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = "Policy name is empty. You cannot proceed."; + } else if (!inputIsValidAgainstLength(policyName, 1, 30)) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = + "Policy name exceeds maximum allowed length."; + } else { + validationStatus["error"] = false; + } + // ending validation process + + // start taking specific actions upon validation + var wizardIsToBeContinued; + if (validationStatus["error"]) { + wizardIsToBeContinued = false; + var mainErrorMsgWrapper = "#policy-naming-main-error-msg"; + var mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else { + wizardIsToBeContinued = true; + } + + return wizardIsToBeContinued; +}; + +validateStep["policy-naming-publish"] = function () { + var validationStatus = {}; + + // taking values of inputs to be validated + var policyName = $("input#policy-name-input").val(); + // starting validation process and updating validationStatus + if (!policyName) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = "Policy name is empty. You cannot proceed."; + } else if (!inputIsValidAgainstLength(policyName, 1, 30)) { + validationStatus["error"] = true; + validationStatus["mainErrorMsg"] = + "Policy name exceeds maximum allowed length."; + } else { + validationStatus["error"] = false; + } + // ending validation process + + // start taking specific actions upon validation + var wizardIsToBeContinued; + if (validationStatus["error"]) { + wizardIsToBeContinued = false; + var mainErrorMsgWrapper = "#policy-naming-main-error-msg"; + var mainErrorMsg = mainErrorMsgWrapper + " span"; + $(mainErrorMsg).text(validationStatus["mainErrorMsg"]); + $(mainErrorMsgWrapper).removeClass("hidden"); + } else { + wizardIsToBeContinued = true; + } + + return wizardIsToBeContinued; +}; + +stepForwardFrom["policy-naming-publish"] = function () { + policy["policyName"] = $("#policy-name-input").val(); + policy["description"] = $("#policy-description-input").val(); + //All data is collected. Policy can now be updated. + updatePolicy(policy, "publish"); +}; +stepForwardFrom["policy-naming"] = function () { + policy["policyName"] = $("#policy-name-input").val(); + policy["description"] = $("#policy-description-input").val(); + //All data is collected. Policy can now be updated. + updatePolicy(policy, "save"); +}; + +var updatePolicy = function (policy, state) { + var profilePayloads = []; + // traverses key by key in policy["profile"] + var key; + for (key in policy["profile"]) { + if (policy["platform"] == platformTypeConstants["WINDOWS"] && + key == windowsOperationConstants["PASSCODE_POLICY_OPERATION_CODE"]) { + policy["profile"][windowsOperationConstants["PASSCODE_POLICY_OPERATION_CODE"]].enablePassword = true; + } + + if (policy["profile"].hasOwnProperty(key)) { + profilePayloads.push({ + "featureCode": key, + "deviceType": policy["platform"], + "content": policy["profile"][key] + }); + } + } + + $.each(profilePayloads, function (i, item) { + $.each(item.content, function (key, value) { + if (value === null || value === undefined || value === "") { + item.content[key] = null; + } + }); + }); + + var payload = { + "policyName": policy["policyName"], + "description": policy["description"], + "compliance": policy["selectedNonCompliantAction"], + "ownershipType": policy["selectedOwnership"], + "profile": { + "profileName": policy["policyName"], + "deviceType": policy["platform"], + "profileFeaturesList": profilePayloads + } + }; + + if (policy["selectedUsers"]) { + payload["users"] = policy["selectedUsers"]; + payload["roles"] = []; + } else if (policy["selectedUserRoles"]) { + payload["users"] = []; + payload["roles"] = policy["selectedUserRoles"]; + } else { + payload["users"] = []; + payload["roles"] = []; + } + + var serviceURL = "/api/device-mgt/v1.0/policies/" + getParameterByName("id"); + invokerUtil.put( + serviceURL, + payload, + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + var policyList = []; + policyList.push(getParameterByName("id")); + if (state == "save") { + serviceURL = "/api/device-mgt/v1.0/policies/deactivate-policy"; + invokerUtil.put( + serviceURL, + policyList, + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $(".add-policy").addClass("hidden"); + $(".policy-message").removeClass("hidden"); + } + }, + // on error + function (jqXHR) { + console.log("error in saving policy. Received error code : " + jqXHR.status); + } + ); + } else if (state == "publish") { + serviceURL = "/api/device-mgt/v1.0/policies/activate-policy"; + invokerUtil.put( + serviceURL, + policyList, + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200) { + $(".add-policy").addClass("hidden"); + $(".policy-naming").addClass("hidden"); + $(".policy-message").removeClass("hidden"); + } + }, + // on error + function (jqXHR) { + console.log("error in publishing policy. Received error code : " + jqXHR.status); + } + ); + } + } + }, + // on error + function (jqXHR) { + console.log("error in updating policy. Received error code : " + jqXHR.status); + } + ); +}; + +// Start of HTML embedded invoke methods +var showAdvanceOperation = function (operation, button) { + $(button).addClass('selected'); + $(button).siblings().removeClass('selected'); + var hiddenOperation = ".wr-hidden-operations-content > div"; + $(hiddenOperation + '[data-operation="' + operation + '"]').show(); + $(hiddenOperation + '[data-operation="' + operation + '"]').siblings().hide(); +}; + +/** + * This method will display appropriate fields based on wifi type + * @param {object} wifi type select object + */ +var changeAndroidWifiPolicy = function (select) { + slideDownPaneAgainstValueSet(select, 'control-wifi-password', ['wep', 'wpa', '802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-eap', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-phase2', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-identity', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-anoidentity', ['802eap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-cacert', ['802eap']); +} + +/** + * This method will display appropriate fields based on wifi EAP type + * @param {object} wifi eap select object + * @param {object} wifi type select object + */ +var changeAndroidWifiPolicyEAP = function (select, superSelect) { + slideDownPaneAgainstValueSet(select, 'control-wifi-password', ['peap', 'ttls', 'pwd' ,'fast', 'leap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-phase2', ['peap', 'ttls', 'fast']); + slideDownPaneAgainstValueSet(select, 'control-wifi-provisioning', ['fast']); + slideDownPaneAgainstValueSet(select, 'control-wifi-identity', ['peap', 'tls', 'ttls', 'pwd', 'fast', 'leap']); + slideDownPaneAgainstValueSet(select, 'control-wifi-anoidentity', ['peap', 'ttls']); + slideDownPaneAgainstValueSet(select, 'control-wifi-cacert', ['peap', 'tls', 'ttls']); + if(superSelect.value != '802eap'){ + changeAndroidWifiPolicy(superSelect); + } +} + +/** + * This method will encode the fileinput and enter the values to given input files + * @param {object} fileInput + * @param {object} fileHiddenInput + * @param {object} fileNameHiddenInput + */ +var base64EncodeFile = function (fileInput, fileHiddenInput, fileNameHiddenInput) { + var file = fileInput.files[0]; + if (file) { + var reader = new FileReader(); + reader.onload = function(readerEvt) { + var binaryString = readerEvt.target.result; + fileHiddenInput.value = (btoa(binaryString)); + fileNameHiddenInput.value = file.name.substr(0,file.name.lastIndexOf(".")); + }; + reader.readAsBinaryString(file); + } +} + + + +/** + * Method to slide down a provided pane upon provided value set. + * + * @param selectElement Select HTML Element to consider + * @param paneID HTML ID of div element to slide down + * @param valueSet Applicable Value Set + */ +var slideDownPaneAgainstValueSet = function (selectElement, paneID, valueSet) { + var selectedValueOnChange = $(selectElement).find("option:selected").val(); + if ($(selectElement).is("input:checkbox")) { + selectedValueOnChange = $(selectElement).is(":checked").toString(); + } + var i, slideDownVotes = 0; + for (i = 0; i < valueSet.length; i++) { + if (selectedValueOnChange == valueSet[i]) { + slideDownVotes++; + } + } + var paneSelector = "#" + paneID; + if (slideDownVotes > 0) { + if (!$(paneSelector).hasClass("expanded")) { + $(paneSelector).addClass("expanded"); + } + $(paneSelector).slideDown(); + } else { + if ($(paneSelector).hasClass("expanded")) { + $(paneSelector).removeClass("expanded"); + } + $(paneSelector).slideUp(); + /** now follows the code to reinitialize all inputs of the slidable pane */ + // reinitializing input fields into the defaults + $(paneSelector + " input").each( + function () { + if ($(this).is("input:text")) { + $(this).val($(this).data("default")); + } else if ($(this).is("input:password")) { + $(this).val(""); + } else if ($(this).is("input:checkbox")) { + $(this).prop("checked", $(this).data("default")); + // if this checkbox is the parent input of a grouped-input + if ($(this).hasClass("parent-input")) { + var groupedInput = $(this).parent().parent().parent(); + updateGroupedInputVisibility(groupedInput); + } + } + } + ); + // reinitializing select fields into the defaults + $(paneSelector + " select").each( + function () { + var defaultOption = $(this).data("default"); + $("option:eq(" + defaultOption + ")", this).prop("selected", "selected"); + } + ); + // collapsing expanded-panes (upon the selection of html-select-options) if any + $(paneSelector + " .expanded").each( + function () { + if ($(this).hasClass("expanded")) { + $(this).removeClass("expanded"); + } + $(this).slideUp(); + } + ); + // removing all entries of grid-input elements if exist + $(paneSelector + " .grouped-array-input").each( + function () { + var gridInputs = $(this).find("[data-add-form-clone]"); + if (gridInputs.length > 0) { + gridInputs.remove(); + } + var helpTexts = $(this).find("[data-help-text=add-form]"); + if (helpTexts.length > 0) { + helpTexts.show(); + } + } + ); + } +}; +// End of HTML embedded invoke methods + + +// Start of functions related to grid-input-view + +/** + * Method to set count id to cloned elements. + * @param {object} addFormContainer + */ +var setId = function (addFormContainer) { + $(addFormContainer).find("[data-add-form-clone]").each(function (i) { + $(this).attr("id", $(this).attr("data-add-form-clone").slice(1) + "-" + (i + 1)); + if ($(this).find(".index").length > 0) { + $(this).find(".index").html(i + 1); + } + }); +}; + +/** + * Method to set count id to cloned elements. + * @param {object} addFormContainer + */ +var showHideHelpText = function (addFormContainer) { + var helpText = "[data-help-text=add-form]"; + if ($(addFormContainer).find("[data-add-form-clone]").length > 0) { + $(addFormContainer).find(helpText).hide(); + } else { + $(addFormContainer).find(helpText).show(); + } +}; + +// End of functions related to grid-input-view + +/** + * This method will return query parameter value given its name. + * @param name Query parameter name + * @returns {string} Query parameter value + */ +var getParameterByName = function (name) { + name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); + var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), + results = regex.exec(location.search); + return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); +}; + +//function formatRepo(user) { +// if (user.loading) { +// return user.text +// } +// if (!user.username) { +// return; +// } +// var markup = '
    ' + +// '
    ' + +// '
    ' + +// '
    ' + user.username + '
    '; +// if (user.firstname) { +// markup += '
    ' + user.firstname + '
    '; +// } +// if (user.emailAddress) { +// markup += '
    ' + user.emailAddress + '
    '; +// } +// markup += '
    '; +// return markup; +//} +// +//function formatRepoSelection(user) { +// return user.username || user.text; +//} + +$(document).ready(function () { + // Adding initial state of wizard-steps. + invokerUtil.get( + "/api/device-mgt/v1.0/policies/" + getParameterByName("id"), + // on success + function (data, textStatus, jqXHR) { + if (jqXHR.status == 200 && data) { + var policy = JSON.parse(data); + skipStep["policy-platform"](policy); + } + }, + // on error + function (jqXHR) { + console.log(jqXHR); + // should be redirected to an error page + } + ); + + $("input[type='radio'].select-users-radio").change(function () { + if ($("#users-radio-btn").is(":checked")) { + $("#user-roles-select-field").hide(); + $("#users-select-field").show(); + } + if ($("#user-roles-radio-btn").is(":checked")) { + $("#users-select-field").hide(); + $("#user-roles-select-field").show(); + } + }); + + // Support for special input type "ANY" on user(s) & user-role(s) selection + $("#user-roles-input").select2({ + "tags": false + }).on("select2:select", function (e) { + if (e.params.data.id == "ANY") { + $(this).val("ANY").trigger("change"); + } else { + $("option[value=ANY]", this).prop("selected", false).parent().trigger("change"); + } + }); + + $("#users-input").select2({ + "tags": false + }).on("select2:select", function (e) { + if (e.params.data.id == "ANY") { + $(this).val("ANY").trigger("change"); + } else { + $("option[value=ANY]", this).prop("selected", false).parent().trigger("change"); + } + }); + + $("#policy-profile-wizard-steps").html($(".wr-steps").html()); + + // Maintains an array of configured features of the profile + var advanceOperations = ".wr-advance-operations"; + $(advanceOperations).on("click", ".wr-input-control.switch", function (event) { + var operationCode = $(this).parents(".operation-data").data("operation-code"); + var operation = $(this).parents(".operation-data").data("operation"); + var operationDataWrapper = $(this).data("target"); + // prevents event bubbling by figuring out what element it's being called from. + if (event.target.tagName == "INPUT") { + var featureConfiguredIcon; + if ($("input[type='checkbox']", this).is(":checked")) { + configuredOperations.push(operationCode); + // when a feature is enabled, if "zero-configured-features" msg is available, hide that. + var zeroConfiguredOperationsErrorMsg = "#policy-profile-main-error-msg"; + if (!$(zeroConfiguredOperationsErrorMsg).hasClass("hidden")) { + $(zeroConfiguredOperationsErrorMsg).addClass("hidden"); + } + // add configured-state-icon to the feature + featureConfiguredIcon = "#" + operation + "-configured"; + if ($(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).removeClass("hidden"); + } + } else { + //splicing the array if operation is present. + var index = $.inArray(operationCode, configuredOperations); + if (index != -1) { + configuredOperations.splice(index, 1); + } + // when a feature is disabled, clearing all its current configured, error or success states + var subErrorMsgWrapper = "#" + operation + "-feature-error-msg"; + var subErrorIcon = "#" + operation + "-error"; + var subOkIcon = "#" + operation + "-ok"; + featureConfiguredIcon = "#" + operation + "-configured"; + + if (!$(subErrorMsgWrapper).hasClass("hidden")) { + $(subErrorMsgWrapper).addClass("hidden"); + } + if (!$(subErrorIcon).hasClass("hidden")) { + $(subErrorIcon).addClass("hidden"); + } + if (!$(subOkIcon).hasClass("hidden")) { + $(subOkIcon).addClass("hidden"); + } + if (!$(featureConfiguredIcon).hasClass("hidden")) { + $(featureConfiguredIcon).addClass("hidden"); + } + // reinitializing input fields into the defaults + $(operationDataWrapper + " input").each( + function () { + if ($(this).is("input:text")) { + $(this).val($(this).data("default")); + } else if ($(this).is("input:password")) { + $(this).val(""); + } else if ($(this).is("input:checkbox")) { + $(this).prop("checked", $(this).data("default")); + // if this checkbox is the parent input of a grouped-input + if ($(this).hasClass("parent-input")) { + var groupedInput = $(this).parent().parent().parent(); + updateGroupedInputVisibility(groupedInput); + } + } + } + ); + // reinitializing select fields into the defaults + $(operationDataWrapper + " select").each( + function () { + var defaultOption = $(this).data("default"); + $("option:eq(" + defaultOption + ")", this).prop("selected", "selected"); + } + ); + // collapsing expanded-panes (upon the selection of html-select-options) if any + $(operationDataWrapper + " .expanded").each( + function () { + if ($(this).hasClass("expanded")) { + $(this).removeClass("expanded"); + } + $(this).slideUp(); + } + ); + // removing all entries of grid-input elements if exist + $(operationDataWrapper + " .grouped-array-input").each( + function () { + var gridInputs = $(this).find("[data-add-form-clone]"); + if (gridInputs.length > 0) { + gridInputs.remove(); + } + var helpTexts = $(this).find("[data-help-text=add-form]"); + if (helpTexts.length > 0) { + helpTexts.show(); + } + } + ); + } + } + }); + + // adding support for cloning multiple profiles per feature with cloneable class definitions + $(advanceOperations).on("click", ".multi-view.add.enabled", function () { + // get a copy of .cloneable and create new .cloned div element + var cloned = "

    " + $(".cloneable", $(this).parent().parent()).html() + "
    "; + // append newly created .cloned div element to panel-body + $(this).parent().parent().append(cloned); + // enable remove action of newly cloned div element + $(".cloned", $(this).parent().parent()).each( + function () { + if ($(".multi-view.remove", this).hasClass("disabled")) { + $(".multi-view.remove", this).removeClass("disabled"); + } + if (!$(".multi-view.remove", this).hasClass("enabled")) { + $(".multi-view.remove", this).addClass("enabled"); + } + } + ); + }); + + $(advanceOperations).on("click", ".multi-view.remove.enabled", function () { + $(this).parent().remove(); + }); + + // enabling or disabling grouped-input based on the status of a parent check-box + $(advanceOperations).on("click", ".grouped-input", function () { + updateGroupedInputVisibility(this); + }); + + // add form entry click function for grid inputs + $(advanceOperations).on("click", "[data-click-event=add-form]", function () { + var addFormContainer = $("[data-add-form-container=" + $(this).attr("href") + "]"); + var clonedForm = $("[data-add-form=" + $(this).attr("href") + "]").clone(). + find("[data-add-form-element=clone]").attr("data-add-form-clone", $(this).attr("href")); + + // adding class .child-input to capture text-input-array-values + $("input, select", clonedForm).addClass("child-input"); + + $(addFormContainer).append(clonedForm); + setId(addFormContainer); + showHideHelpText(addFormContainer); + }); + + // remove form entry click function for grid inputs + $(advanceOperations).on("click", "[data-click-event=remove-form]", function () { + var addFormContainer = $("[data-add-form-container=" + $(this).attr("href") + "]"); + + $(this).closest("[data-add-form-element=clone]").remove(); + setId(addFormContainer); + showHideHelpText(addFormContainer); + }); + + $(".wizard-stepper").click(function () { + // button clicked here can be either a continue button or a back button. + var currentStep = $(this).data("current"); + var validationIsRequired = $(this).data("validate"); + var wizardIsToBeContinued; + + if (validationIsRequired) { + wizardIsToBeContinued = validateStep[currentStep](); + } else { + wizardIsToBeContinued = true; + } + + if (wizardIsToBeContinued) { + // When moving back and forth, following code segment will + // remove if there are any visible error-messages. + var errorMsgWrappers = ".alert.alert-danger"; + $(errorMsgWrappers).each( + function () { + if (!$(this).hasClass("hidden")) { + $(this).addClass("hidden"); + } + } + ); + + var nextStep = $(this).data("next"); + var isBackBtn = $(this).data("is-back-btn"); + + // if current button is a continuation... + if (!isBackBtn) { + // initiate stepForwardFrom[*] functions to gather form data. + if (stepForwardFrom[currentStep]) { + stepForwardFrom[currentStep](this); + } + } else { + // initiate stepBackFrom[*] functions to rollback. + if (stepBackFrom[currentStep]) { + stepBackFrom[currentStep](); + } + } + + // following step occurs only at the last stage of the wizard. + if (!nextStep) { + window.location.href = $(this).data("direct"); + } + + // updating next wizard step as current. + $(".itm-wiz").each(function () { + var step = $(this).data("step"); + if (step == nextStep) { + $(this).addClass("itm-wiz-current"); + } else { + $(this).removeClass("itm-wiz-current"); + } + }); + + // adding next update of wizard-steps. + $("#" + nextStep + "-wizard-steps").html($(".wr-steps").html()); + + // hiding current section of the wizard and showing next section. + $("." + currentStep).addClass("hidden"); + $("." + nextStep).removeClass("hidden"); + } + }); + +}); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-android.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-android.hbs new file mode 100644 index 0000000000..7a0f2bdd3c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-android.hbs @@ -0,0 +1,1225 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    + +
    +
    +
    + +
    +
    + Below restrictions will be applied on devices with Android version 5.0 Lollipop onwards only + +

    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    + +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + +
    +
    +
    + Bellow restrictions will be applied on devices with Android version 6.0 Marshmallow onwards only. + +

    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you do not need the device to be encrypted. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + + + + + + + + + + + + + + Please note that * sign represents required fields of data. +
    +
    + +
    + + +
    +
    + + +
    + + + + + + + + + +
    +
    +
    + + +
    +
    + +
    + + + + + +
    + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + +
    + + + + +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    +
    +
    +
    diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-ios.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-ios.hbs new file mode 100644 index 0000000000..cde1b54837 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-ios.hbs @@ -0,0 +1,4679 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    +Please note that * sign represents required fields of data. +
    +
    + + +
    + + +
    +
    + +
    +
    + +
    + +
    + +
    + + + + + + + + + + + + + + +
    No:KeyValue
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    + + +
    + + + + +
    +
    +
    + + + +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + + +
    + + +
    +
    + +
    +
    + +
    + + + + + + + + + + + + + +
    No:Safari Domain
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + +
    + Please note that * sign represents required fields of data. +
    +
    + + +
    + +
    + + + + + + + + + + + + + + +
    No:App IdentifierVPN UUID
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + + + +
    + + +
    + + + +
    + + +
    + + + + + + + + + + + + + +
    No:Roaming Consortium OI
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + +
    No:NAI Realm Name
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + + +
    No:Mobile Country Code ( MCC )Mobile Network Code ( MNC )
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + + +
    + + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + +
    + +
    +Incoming Mail Settings : +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +Outgoing Mail Settings : +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + + + + + + + + + + + + + + +
    No:Device NamePassword
    + No entries added yet . +
    + + + + + + + + + + +
    +
    + +
    + +
    + + +
    + + + + + + + + + + + + + +
    No:Destination
    + No entries added yet . +
    + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + + + + + + + + + + + + + + + +
    No:DescriptionSearch BaseScope
    + No entries added yet . +
    + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + + + + + + + + + + + + + + + + + +
    No:APNUsernamePasswordProxyPort
    + No entries added yet . +
    + + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + + + + + + + + + + + + + + + + + + +
    No:APNAuth.TypeUsernamePasswordProxyPort
    + No entries added yet . +
    + + + + + + + + + + + + + + +
    +
    + +
    +
    +
    + + + +
    +
    + +
    + + + +Restrictions on Device Functionality : +
    +
    +
      +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
        +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    +
    +
    +Restrictions on Applications : +
    +
    +
      +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
        +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + +
        +
      • +
      • +
        + + +
        +
      • +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    • +
      + +
      +
    • +
    +
    + + + +
    +
    +
    + +
    +
    \ 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/public/templates/hidden-operations-windows.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-windows.hbs new file mode 100644 index 0000000000..7c689586c9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/public/templates/hidden-operations-windows.hbs @@ -0,0 +1,568 @@ +
    + + +
    + +
    +
    + +
    + + + +
    + +
    + +
    + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    + +
    + + +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you need to disable camera. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + Un-check following checkbox in case you need to disable storage-encryption. +
    +
    +
    + +
    +
    +
    +
    +
    + + + +
    +
    + +
    + + + + + +
    + +
    + + + + + + + + + + + + + + +
    No:Application Name/DescriptionPackage Name
    + No entries added yet . +
    + + + + + + + + + + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    \ No newline at end of file From 734aaa8c9e9c94eedc69296ba05e04d3a133a8fd Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 8 Aug 2016 19:24:57 +0530 Subject: [PATCH 19/21] Fixed null pointer exception --- .../mgt/core/permission/mgt/PermissionManagerServiceImpl.java | 4 ++++ 1 file changed, 4 insertions(+) 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 9dd03555a2..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 @@ -62,6 +62,10 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { 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); } } From c693a11d7c143441b599ced3b3d7e00042272a7d Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 9 Aug 2016 07:56:56 +0530 Subject: [PATCH 20/21] Fixing user,device,role listing pages --- .../devicemgt/api/data-tables-invoker-api.jag | 22 +- .../app/pages/cdmf.page.user.view/view.js | 1 - .../cdmf.page.users/public/js/listing.js | 290 +++++++++--------- .../app/pages/cdmf.page.users/users.hbs | 71 +++-- .../app/pages/cdmf.page.users/users.js | 2 +- .../dataTables.extended.serversidepaging.js | 44 +-- 6 files changed, 241 insertions(+), 189 deletions(-) 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 ce0dbd1d41..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 @@ -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/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 ffb86426bb..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 @@ -20,7 +20,6 @@ function onRequest(context) { 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"); 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) { + + + $("#loading-content").show(); - var dataFilter = function (data) { + + 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 df93724633..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,7 +28,7 @@ function onRequest(context) { }); var page = {}; - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; page["adminUser"] = deviceMgtProps["adminUser"]; 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 } }); From aa7d3385ce3dc0685c6c30674dd9b4c737221349 Mon Sep 17 00:00:00 2001 From: Ace Date: Tue, 9 Aug 2016 08:10:51 +0530 Subject: [PATCH 21/21] Adding missed role-listing changes --- .../units/cdmf.unit.role.listing/listing.hbs | 13 -- .../public/js/role-listing.js | 152 +++++++++++------- 2 files changed, 90 insertions(+), 75 deletions(-) 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/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(); - } - - //$(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(); + 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(); }); }); }; @@ -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();