From 49623a4693dcbd35f6b5305c3e29d31254fcb4ce Mon Sep 17 00:00:00 2001 From: mharindu Date: Sun, 3 Jul 2016 15:03:47 +0530 Subject: [PATCH 01/76] 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/76] 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/76] 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/76] 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/76] 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/76] 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 0ea2c458e7fc789470142cee67ed63c874bdd854 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Fri, 15 Jul 2016 09:39:50 +0200 Subject: [PATCH 07/76] instanceof will return false for null references, the null check is not needed. --- .../mgt/core/impl/CertificateGenerator.java | 118 +++++++----------- 1 file changed, 45 insertions(+), 73 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index f71162904c..ffbe5cc5ba 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -46,14 +46,7 @@ import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.Store; -import org.jscep.message.CertRep; -import org.jscep.message.MessageDecodingException; -import org.jscep.message.MessageEncodingException; -import org.jscep.message.PkcsPkiEnvelopeDecoder; -import org.jscep.message.PkcsPkiEnvelopeEncoder; -import org.jscep.message.PkiMessage; -import org.jscep.message.PkiMessageDecoder; -import org.jscep.message.PkiMessageEncoder; +import org.jscep.message.*; import org.jscep.transaction.FailInfo; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; @@ -72,31 +65,11 @@ import org.wso2.carbon.device.mgt.common.TransactionManagementException; import javax.security.auth.x500.X500Principal; import javax.xml.bind.DatatypeConverter; -import java.io.ByteArrayInputStream; -import java.io.DataInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.KeyFactory; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.NoSuchProviderException; -import java.security.PrivateKey; -import java.security.SecureRandom; -import java.security.Security; -import java.security.SignatureException; +import java.security.*; import java.security.cert.Certificate; -import java.security.cert.CertificateEncodingException; -import java.security.cert.CertificateException; -import java.security.cert.CertificateExpiredException; -import java.security.cert.CertificateFactory; -import java.security.cert.CertificateNotYetValidException; -import java.security.cert.X509Certificate; +import java.security.cert.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; @@ -108,6 +81,46 @@ public class CertificateGenerator { private static final Log log = LogFactory.getLog(CertificateGenerator.class); + public static String getCommonName(X509Certificate requestCertificate) { + String distinguishedName = requestCertificate.getSubjectDN().getName(); + if (distinguishedName != null && !distinguishedName.isEmpty()) { + String[] dnSplits = distinguishedName.split(","); + for (String dnSplit : dnSplits) { + if (dnSplit.contains("CN=")) { + String[] cnSplits = dnSplit.split("="); + if (cnSplits[1] != null) { + return cnSplits[1]; + } + } + } + } + return null; + } + + public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) + throws CertificateManagementDAOException { + try { + if (certificateBytes != null) { + java.security.cert.Certificate x509Certificate = + (java.security.cert.Certificate) Serializer.deserialize(certificateBytes); + if (x509Certificate instanceof X509Certificate) { + X509Certificate certificate = (X509Certificate) x509Certificate; + certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); + certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); + certificateResponse.setCertificateserial(certificate.getSerialNumber()); + certificateResponse.setIssuer(certificate.getIssuerDN().getName()); + certificateResponse.setSubject(certificate.getSubjectDN().getName()); + certificateResponse.setCertificateVersion(certificate.getVersion()); + } + } + } catch (ClassNotFoundException | IOException e) { + String errorMsg = "Error while deserializing the certificate."; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } + + } + public List getRootCertificates(byte[] ca, byte[] ra) throws KeystoreException { if (ca == null) { @@ -329,22 +342,6 @@ public class CertificateGenerator { return lookUpCertificate; } - public static String getCommonName(X509Certificate requestCertificate) { - String distinguishedName = requestCertificate.getSubjectDN().getName(); - if (distinguishedName != null && !distinguishedName.isEmpty()) { - String[] dnSplits = distinguishedName.split(","); - for (String dnSplit : dnSplits) { - if (dnSplit.contains("CN=")) { - String[] cnSplits = dnSplit.split("="); - if (cnSplits[1] != null) { - return cnSplits[1]; - } - } - } - } - return null; - } - public X509Certificate pemToX509Certificate(String pem) throws KeystoreException { InputStream inputStream = null; @@ -395,7 +392,7 @@ public class CertificateGenerator { Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias( reqCert.getSerialNumber().toString()); - if (lookUpCertificate != null && (lookUpCertificate instanceof X509Certificate)) { + if (lookUpCertificate instanceof X509Certificate) { return (X509Certificate) lookUpCertificate; } } @@ -681,7 +678,6 @@ public class CertificateGenerator { } } - public String extractChallengeToken(X509Certificate certificate) { byte[] challengePassword = certificate.getExtensionValue( @@ -742,28 +738,4 @@ public class CertificateGenerator { certCA.getIssuerX500Principal().getName()); return signedCertificate; } - - public static void extractCertificateDetails(byte[] certificateBytes, CertificateResponse certificateResponse) - throws CertificateManagementDAOException { - try { - if (certificateBytes != null) { - java.security.cert.Certificate x509Certificate = - (java.security.cert.Certificate) Serializer.deserialize(certificateBytes); - if (x509Certificate instanceof X509Certificate) { - X509Certificate certificate = (X509Certificate) x509Certificate; - certificateResponse.setNotAfter(certificate.getNotAfter().getTime()); - certificateResponse.setNotBefore(certificate.getNotBefore().getTime()); - certificateResponse.setCertificateserial(certificate.getSerialNumber()); - certificateResponse.setIssuer(certificate.getIssuerDN().getName()); - certificateResponse.setSubject(certificate.getSubjectDN().getName()); - certificateResponse.setCertificateVersion(certificate.getVersion()); - } - } - } catch (ClassNotFoundException | IOException e) { - String errorMsg = "Error while deserializing the certificate."; - log.error(errorMsg, e); - throw new CertificateManagementDAOException(errorMsg, e); - } - - } } \ No newline at end of file From 0ac4752b2b811f256a5fd1be148f53f1068332a1 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Fri, 15 Jul 2016 09:47:08 +0200 Subject: [PATCH 08/76] Fixed null pointer dereference --- .../carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java index 1530b8edfc..d622270e92 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java @@ -473,8 +473,8 @@ public class PolicyDAOImpl implements PolicyDAO { try { conn = this.getConnection(); String query = "SELECT * FROM DM_POLICY_CHANGE_MGT WHERE TENANT_ID = ?"; - stmt.setInt(1, tenantId); stmt = conn.prepareStatement(query); + stmt.setInt(1, tenantId); resultSet = stmt.executeQuery(); while (resultSet.next()) { @@ -1302,11 +1302,7 @@ public class PolicyDAOImpl implements PolicyDAO { if (log.isDebugEnabled()) { log.debug("Policy (" + policyId + ") delete from database."); } - if (deleted > 0) { - return true; - } else { - return false; - } + return deleted > 0; } catch (SQLException e) { throw new PolicyManagerDAOException("Unable to delete the policy (" + policyId + ") from database", e); } finally { @@ -1584,7 +1580,7 @@ public class PolicyDAOImpl implements PolicyDAO { byte[] contentBytes; try { - contentBytes = (byte[]) resultSet.getBytes("POLICY_CONTENT"); + contentBytes = resultSet.getBytes("POLICY_CONTENT"); bais = new ByteArrayInputStream(contentBytes); ois = new ObjectInputStream(bais); policy = (Policy) ois.readObject(); From ed077745525ce2a4bb624188a68c8b11601f5752 Mon Sep 17 00:00:00 2001 From: Timo Briddigkeit Date: Fri, 15 Jul 2016 16:25:31 +0200 Subject: [PATCH 09/76] Fixed literal string comparison. This line is in the form of String str = ... str.equals("someOtherString"); //or str.compareTo("someOtherString"); A NullPointerException may occur if the String variable str is null. If instead the code was restructured to String str = ... "someOtherString".equals(str); //or "someOtherString".compareTo(str); that is, call equals() or compareTo() on the string literal, passing the variable as an argument, this exception could never happen as both equals() and compareTo() check for null. --- ...ApiApplicationRegistrationServiceImpl.java | 4 +-- .../APIManagementProviderServiceImpl.java | 11 ++----- .../extension/util/APIManagerUtil.java | 2 +- .../webapp/publisher/APIPublisherUtil.java | 6 ++-- .../lifecycle/util/AnnotationProcessor.java | 5 ++-- .../data/publisher/DeviceDataPublisher.java | 10 +++---- .../impl/RoleManagementServiceImpl.java | 6 ++-- .../search/mgt/impl/QueryBuilderImpl.java | 5 ++-- .../mgt/core/util/DeviceManagerUtil.java | 2 +- .../policy/evaluator/FeatureFilterImpl.java | 14 ++++----- .../impl/ComplianceDecisionPointImpl.java | 2 +- .../mgt/core/util/PolicyManagerUtil.java | 2 +- .../framework/WebappAuthenticationValve.java | 7 ++--- .../authenticator/JWTAuthenticator.java | 29 +++++++++---------- 14 files changed, 46 insertions(+), 59 deletions(-) diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java index d01a2fb7ec..e88d80e67c 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationServiceImpl.java @@ -22,13 +22,13 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; +import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil; import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.apimgt.application.extension.api.util.APIUtil; import org.wso2.carbon.user.api.UserStoreException; import javax.ws.rs.DELETE; @@ -46,7 +46,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi public Response register(@QueryParam("tenantDomain") String tenantDomain, @QueryParam("applicationName") String applicationName) { String authenticatedTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); - if (!authenticatedTenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(authenticatedTenantDomain)) { return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } try { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java index bc02828ee3..304cab7df0 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java @@ -23,12 +23,7 @@ import org.apache.commons.logging.LogFactory; import org.json.simple.JSONObject; import org.wso2.carbon.apimgt.api.APIConsumer; import org.wso2.carbon.apimgt.api.APIManagementException; -import org.wso2.carbon.apimgt.api.model.API; -import org.wso2.carbon.apimgt.api.model.APIIdentifier; -import org.wso2.carbon.apimgt.api.model.APIKey; -import org.wso2.carbon.apimgt.api.model.Application; -import org.wso2.carbon.apimgt.api.model.SubscribedAPI; -import org.wso2.carbon.apimgt.api.model.Subscriber; +import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; @@ -415,7 +410,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe int applicationId = createApplication(apiConsumer, apiApplicationName, username, groupId); String tenantDomain = MultitenantUtils.getTenantDomain(username); Set userVisibleAPIs = apiConsumer.getAllPublishedAPIs(tenantDomain); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { userVisibleAPIs.addAll(apiConsumer.getAllPublishedAPIs(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)); } Subscriber subscriber = apiConsumer.getSubscriber(username); @@ -443,7 +438,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe try { APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username); loginInfoJsonObj.put("user", username); - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { loginInfoJsonObj.put("isSuperTenant", true); } else { loginInfoJsonObj.put("isSuperTenant", false); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java index 530dfa662f..8c204c422e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/util/APIManagerUtil.java @@ -37,7 +37,7 @@ public final class APIManagerUtil { */ public static int getTenantId(String tenantDomain) throws APIManagerException { try { - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { return MultitenantConstants.SUPER_TENANT_ID; } TenantManager tenantManager = APIApplicationManagerExtensionDataHolder.getInstance().getTenantManager(); diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/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..3a2385d67c 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 @@ -36,10 +36,10 @@ import java.util.*; public class APIPublisherUtil { - private static final Log log = LogFactory.getLog(APIPublisherUtil.class); - private static final String DEFAULT_API_VERSION = "1.0.0"; public static final String API_VERSION_PARAM = "{version}"; public static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox"; + private static final Log log = LogFactory.getLog(APIPublisherUtil.class); + private static final String DEFAULT_API_VERSION = "1.0.0"; private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0"; private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint"; private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner"; @@ -242,7 +242,7 @@ public class APIPublisherUtil { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME; apiConfig.setTenantDomain(tenantDomain); String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER; - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER; } apiConfig.setContextTemplate(contextTemplate); 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..d08055aed5 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 @@ -63,11 +63,10 @@ public class AnnotationProcessor { private static final String HTTP_PORT = "httpPort"; private static final String STRING_ARR = "string_arr"; private static final String STRING = "string"; - + Class apiClazz; private StandardContext context; private Method[] pathClazzMethods; private Class pathClazz; - Class apiClazz; private ClassLoader classLoader; private ServletContext servletContext; @@ -319,7 +318,7 @@ public class AnnotationProcessor { * @return */ private String makeContextURLReady(String context) { - if (context != null && !context.equalsIgnoreCase("")) { + if (context != null && context.length() > 0) { if (context.startsWith("/")) { return context; } else { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java index 04f9030760..537e5b01b4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/src/main/java/org/wso2/carbon/device/mgt/analytics/data/publisher/DeviceDataPublisher.java @@ -60,6 +60,10 @@ public class DeviceDataPublisher { private static Map dataPublisherMap; private static DeviceDataPublisher deviceDataPublisher; + public DeviceDataPublisher() { + dataPublisherMap = new ConcurrentHashMap<>(); + } + public static DeviceDataPublisher getInstance() { if (deviceDataPublisher == null) { synchronized (DeviceDataPublisher.class) { @@ -71,10 +75,6 @@ public class DeviceDataPublisher { return deviceDataPublisher; } - public DeviceDataPublisher() { - dataPublisherMap = new ConcurrentHashMap<>(); - } - /** * this return the data publisher for the tenant. * @@ -95,7 +95,7 @@ public class DeviceDataPublisher { String analyticsServerUrlGroups = analyticsConfig.getReceiverServerUrl(); String analyticsServerUsername = analyticsConfig.getAdminUsername(); String analyticsServerPassword = analyticsConfig.getAdminPassword(); - if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String userInfo[] = getAnalyticsServerUserInfo(tenantId); if (userInfo != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/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..bab738ac1b 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 @@ -125,11 +125,11 @@ public class RoleManagementServiceImpl implements RoleManagementService { UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2]; for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) { - if (permissionNode.getResourcePath().equals("/permission/admin")) { + if ("/permission/admin".equals(permissionNode.getResourcePath())) { for (UIPermissionNode node : permissionNode.getNodeList()) { - if (node.getResourcePath().equals("/permission/admin/device-mgt")) { + if ("/permission/admin/device-mgt".equals(node.getResourcePath())) { deviceMgtPermissions[0] = node; - } else if (node.getResourcePath().equals("/permission/admin/login")) { + } else if ("/permission/admin/login".equals(node.getResourcePath())) { deviceMgtPermissions[1] = node; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java index b86e3c1bcc..3a841f2aa0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/search/mgt/impl/QueryBuilderImpl.java @@ -47,8 +47,7 @@ public class QueryBuilderImpl implements QueryBuilder { Condition locCondition = new Condition(); if (conditions.size() == 1) { - - if (conditions.get(0).getKey().equalsIgnoreCase(Constants.LOCATION)) { + if (Constants.LOCATION.equalsIgnoreCase(conditions.get(0).getKey())) { locCondition = conditions.get(0); } else if (Utils.checkDeviceDetailsColumns(conditions.get(0).getKey()) || Utils.checkDeviceLocationColumns(conditions.get(0).getKey())) { @@ -58,7 +57,7 @@ public class QueryBuilderImpl implements QueryBuilder { } } else { for (Condition con : conditions) { - if (con.getKey().equalsIgnoreCase(Constants.LOCATION)) { + if (Constants.LOCATION.equalsIgnoreCase(con.getKey())) { locCondition = con; } else if (Utils.checkDeviceDetailsColumns(con.getKey()) || Utils.checkDeviceLocationColumns(con.getKey())) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index a9d472d498..bf563790d7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -227,7 +227,7 @@ public final class DeviceManagerUtil { */ public static int getTenantId(String tenantDomain) throws DeviceManagementException { try { - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { return MultitenantConstants.SUPER_TENANT_ID; } TenantManager tenantManager = DeviceManagementDataHolder.getInstance().getTenantManager(); diff --git a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java index 0e4723e23f..9857c8f753 100644 --- a/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java +++ b/components/policy-mgt/org.wso2.carbon.complex.policy.decision.point/src/main/java/org/wso2/carbon/policy/evaluator/FeatureFilterImpl.java @@ -67,25 +67,25 @@ public class FeatureFilterImpl implements FeatureFilter { for (FeatureRules rule : featureRulesList) { String ruleName = rule.getEvaluationCriteria(); String featureName = rule.getName(); - if (ruleName.equalsIgnoreCase(Constants.DENY_OVERRIDES)) { + if (Constants.DENY_OVERRIDES.equalsIgnoreCase(ruleName)) { getDenyOverridesFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.PERMIT_OVERRIDES)) { + if (Constants.PERMIT_OVERRIDES.equalsIgnoreCase(ruleName)) { getPermitOverridesFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.FIRST_APPLICABLE)) { + if (Constants.FIRST_APPLICABLE.equalsIgnoreCase(ruleName)) { getFirstApplicableFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.LAST_APPLICABLE)) { + if (Constants.LAST_APPLICABLE.equalsIgnoreCase(ruleName)) { getLastApplicableFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.ALL_APPLICABLE)) { + if (Constants.ALL_APPLICABLE.equalsIgnoreCase(ruleName)) { getAllApplicableFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.HIGHEST_APPLICABLE)) { + if (Constants.HIGHEST_APPLICABLE.equalsIgnoreCase(ruleName)) { getHighestApplicableFeatures(featureName, featureList, effectiveFeatureList); } - if (ruleName.equalsIgnoreCase(Constants.LOWEST_APPLICABLE)) { + if (Constants.LOWEST_APPLICABLE.equalsIgnoreCase(ruleName)) { getLowestApplicableFeatures(featureName, featureList, effectiveFeatureList); } } diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java index 94b1107440..1322834634 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/ComplianceDecisionPointImpl.java @@ -253,7 +253,7 @@ public class ComplianceDecisionPointImpl implements ComplianceDecisionPoint { Policy policy = complianceData.getPolicy(); String compliance = this.getNoneComplianceRule(policy); - if (compliance.equals("")) { + if ("".equals(compliance)) { String msg = "Compliance rule is empty for the policy " + policy.getPolicyName() + ". Therefore " + "Monitoring Engine cannot run."; throw new PolicyComplianceException(msg); diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java index ee55646f11..d0d9fce352 100644 --- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java +++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/util/PolicyManagerUtil.java @@ -203,7 +203,7 @@ public class PolicyManagerUtil { if (configuration != null && !configuration.isEmpty()) { for (ConfigurationEntry cEntry : configuration) { - if (cEntry.getName().equalsIgnoreCase(MONITORING_FREQUENCY)) { + if (MONITORING_FREQUENCY.equalsIgnoreCase(cEntry.getName())) { if (cEntry.getValue() == null) { throw new PolicyManagementException("Invalid value, i.e. '" + cEntry.getValue() + "', is configured as the monitoring frequency"); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java index feb5c77415..df15f9f1c7 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/WebappAuthenticationValve.java @@ -105,7 +105,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { ctx = tokenizer.nextToken(); } } - return (ctx.equalsIgnoreCase("carbon") || ctx.equalsIgnoreCase("services")); + return ("carbon".equalsIgnoreCase(ctx) || "services".equalsIgnoreCase(ctx)); } private boolean isNonSecuredEndPoint(Request request) { @@ -132,10 +132,7 @@ public class WebappAuthenticationValve extends CarbonTomcatValve { } } } - if (nonSecuredEndpoints.containsKey(uri)) { - return true; - } - return false; + return nonSecuredEndpoints.containsKey(uri); } private void processRequest(Request request, Response response, CompositeValve compositeValve, diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java index 8746cb1455..9184682d3a 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/JWTAuthenticator.java @@ -65,6 +65,13 @@ public class JWTAuthenticator implements WebappAuthenticator { private static final Map publicKeyHolder = new HashMap<>(); private Properties properties; + private static void loadTenantRegistry(int tenantId) throws RegistryException { + TenantRegistryLoader tenantRegistryLoader = AuthenticatorFrameworkDataHolder.getInstance(). + getTenantRegistryLoader(); + AuthenticatorFrameworkDataHolder.getInstance().getTenantIndexingLoader().loadTenantIndex(tenantId); + tenantRegistryLoader.loadTenantRegistry(tenantId); + } + @Override public void init() { @@ -73,10 +80,7 @@ public class JWTAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { String authorizationHeader = request.getHeader(JWTAuthenticator.JWT_ASSERTION_HEADER); - if ((authorizationHeader != null) && !authorizationHeader.isEmpty()) { - return true; - } - return false; + return (authorizationHeader != null) && !authorizationHeader.isEmpty(); } @Override @@ -106,7 +110,7 @@ public class JWTAuthenticator implements WebappAuthenticator { if (publicKey == null) { loadTenantRegistry(tenantId); KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId); - if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { + if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { String defaultPublicKey = properties.getProperty("DefaultPublicKey"); if (defaultPublicKey != null && !defaultPublicKey.isEmpty()) { boolean isDefaultPublicKey = Boolean.parseBoolean(defaultPublicKey); @@ -182,13 +186,13 @@ public class JWTAuthenticator implements WebappAuthenticator { } @Override - public void setProperties(Properties properties) { - this.properties = properties; + public Properties getProperties() { + return properties; } @Override - public Properties getProperties() { - return properties; + public void setProperties(Properties properties) { + this.properties = properties; } @Override @@ -198,11 +202,4 @@ public class JWTAuthenticator implements WebappAuthenticator { } return this.properties.getProperty(name); } - - private static void loadTenantRegistry(int tenantId) throws RegistryException { - TenantRegistryLoader tenantRegistryLoader = AuthenticatorFrameworkDataHolder.getInstance(). - getTenantRegistryLoader(); - AuthenticatorFrameworkDataHolder.getInstance().getTenantIndexingLoader().loadTenantIndex(tenantId); - tenantRegistryLoader.loadTenantRegistry(tenantId); - } } From 186432e1df88573debfb4e74d3bcc469853355e5 Mon Sep 17 00:00:00 2001 From: mharindu Date: Mon, 18 Jul 2016 20:08:51 +0530 Subject: [PATCH 10/76] 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 11/76] 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 12/76] 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 13/76] 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 14/76] 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 15/76] 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 16/76] 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 2efdc301774b36d9b80a80d7e759d8a58dac6644 Mon Sep 17 00:00:00 2001 From: dilanua Date: Fri, 29 Jul 2016 14:44:16 +0530 Subject: [PATCH 17/76] Refactoring OAuth utilities at UI Layer --- .../devicemgt/api/data-tables-invoker-api.jag | 2 +- .../jaggeryapps/devicemgt/api/device-api.jag | 2 +- .../jaggeryapps/devicemgt/api/group-api.jag | 2 +- .../jaggeryapps/devicemgt/api/invoker-api.jag | 6 +- .../devicemgt/api/operation-api.jag | 2 +- .../jaggeryapps/devicemgt/api/token.jag | 2 +- .../jaggeryapps/devicemgt/api/user-api.jag | 2 +- .../devicemgt/app/conf/config.json | 153 ++++--- .../devicemgt/app/modules/device.js | 2 +- .../devicemgt/app/modules/group.js | 2 +- .../app/modules/invoker-request-wrapper.js | 2 +- .../devicemgt/app/modules/login.js | 2 +- .../devicemgt/app/modules/operation.js | 2 +- .../devicemgt/app/modules/policy.js | 2 +- ...{api-wrapper-util.js => token-handlers.js} | 22 +- ...js => token-protected-service-invokers.js} | 4 +- .../jaggeryapps/devicemgt/app/modules/user.js | 2 +- .../jaggeryapps/devicemgt/app/modules/util.js | 425 ++++++++++-------- 18 files changed, 358 insertions(+), 278 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{api-wrapper-util.js => token-handlers.js} (92%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{backend-service-invoker.js => token-protected-service-invokers.js} (99%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag index e52746e9df..59c142ff2c 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 @@ -23,7 +23,7 @@ var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; function appendQueryParam (url, queryParam , value) { if (url.indexOf("?") > 0) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 1a163d76e4..a1d496f174 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -26,7 +26,7 @@ var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag index d5f9bb2628..46ac2913f5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -24,7 +24,7 @@ var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 6fa133523e..29da7a76b9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -24,7 +24,7 @@ var uriMatcher = new URIMatcher(String(uri)); var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; if (uriMatcher.match("/{context}/api/invoker/execute/")) { var restAPIRequestDetails = request.getContent(); @@ -97,8 +97,8 @@ if (uriMatcher.match("/{context}/api/invoker/execute/")) { break; } } catch (e) { - log.error("Exception occurred while trying to access backend " + - "REST API services from Jaggery API invoker layer", e); + throw new Error("Exception occurred while trying to access " + + "backend REST API services from Jaggery API invoker layer", e); } } %> diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index 46b4595b66..a08a662588 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -22,7 +22,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/operation-api.jag"); -var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; +var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; if (uriMatcher.match("/{context}/api/operation/paginate")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag index 45210346bb..557d4f5a77 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag @@ -21,7 +21,7 @@ @Deprecated - new */ -// var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; +// var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; // var tokenCookie = apiWrapperUtil.refreshToken(); // print(tokenCookie); %> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index cab3d3a32f..a797c2f3fa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -27,7 +27,7 @@ var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; -var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; +var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; var util = require("/app/modules/util.js").util; var responseProcessor = require('utils').response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json index 8c732e33cd..ad95aa01d6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json @@ -1,68 +1,89 @@ { - "appContext" : "/devicemgt/", - "webAgentContext" : "/devicemgt-web-agent/", - "apiContext" : "api", - "httpsURL" : "https://localhost:8243", - "httpURL" : "%http.ip%", - "httpsWebURL" : "%https.ip%", - "wssURL" : "%https.ip%", - "wsURL" : "%http.ip%", - "dashboardserverURL" : "%https.ip%", - "enrollmentDir": "/emm-web-agent/enrollment", - "iOSConfigRoot" : "%https.ip%/ios-enrollment/", - "iOSAPIRoot" : "%https.ip%/ios/", - "dynamicClientRegistrationEndPoint" : "https://localhost:8243/dynamic-client-web/register/", - "adminService":"%https.ip%", - "idPServer":"https://localhost:8243", - "callBackUrl":"%https.ip%/devicemgt_admin", - "adminUser":"admin@carbon.super", - "adminRole":"admin", - "usernameLength":30, - "ssoConfiguration" : { - "enabled" : false, - "issuer" : "devicemgt", - "appName" : "devicemgt", - "identityProviderURL" : "%https.ip%/sso/samlsso.jag", - "responseSigningEnabled" : "true", - "keyStorePassword" : "wso2carbon", - "identityAlias" : "wso2carbon", - "keyStoreName" : "/repository/resources/security/wso2carbon.jks" - }, - "userValidationConfig" : { - "usernameJSRegEx" : "^[\\S]{3,30}$", - "usernameRegExViolationErrorMsg" : "Provided username is invalid.", - "usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.", - "firstnameJSRegEx" : "^[\\S]{3,30}$", - "firstnameRegExViolationErrorMsg" : "Provided first name is invalid.", - "lastnameJSRegEx" : "^[\\S]{3,30}$", - "lastnameRegExViolationErrorMsg" : "Provided last name is invalid.", - "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", - "emailRegExViolationErrorMsg" : "Provided email is invalid." - }, - "groupValidationConfig": { - "groupNameJSRegEx": "^[\\S]{3,30}$", - "groupNameRegExViolationErrorMsg": "Provided group name is invalid.", - "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." - }, - "roleValidationConfig" : { - "rolenameJSRegEx" : "^[\\S]{3,30}$", - "rolenameRegExViolationErrorMsg" : "Provided role name is invalid.", - "rolenameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces." - }, - "generalConfig" : { - "host" : "https://localhost:9443", - "companyName" : "WSO2 Carbon Device Manager", - "browserTitle" : "WSO2 Device Manager", - "copyrightPrefix" : "\u00A9 %date-year%, ", - "copyrightOwner" : "WSO2 Inc.", - "copyrightOwnersSite" : "http://www.wso2.org", - "copyrightSuffix" : " All Rights Reserved." - }, - "scopes" : ["license-add", "license-view", "device-view", "device-info", "device-list", "device-view-own", - "device-modify", "device-search", "operation-install", "operation-view", "operation-modify", "operation-uninstall", - "group-add", "group-share", "group-modify", "group-view", "group-remove", "certificate-modify", "certificate-view", - "configuration-view", "configuration-modify", "policy-view", "policy-modify", "device-notification-view", - "device-notification-modify", "feature-view", "arduino_device", "arduino_user", " android_sense_user", - "virtual_firealarm_user", "raspberrypi_user", "roles-view", "roles-modify", "roles-remove", "roles-add", - "user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"] + "appContext": "/emm/", + "webAgentContext" : "/emm-web-agent/", + "apiContext": "api", + "httpsURL" : "%https.ip%", + "httpURL" : "%http.ip%", + "httpsWebURL" : "%https.ip%", + "wssURL" : "%https.ip%", + "wsURL" : "%http.ip%", + "dashboardServerURL" : "%https.ip%", + "enrollmentDir": "/emm-web-agent/enrollment", + "iOSConfigRoot" : "%https.ip%/ios-enrollment/", + "iOSAPIRoot" : "%https.ip%/ios/", + "adminService": "%https.ip%", + "oauthProvider": { + "appRegistration": { + "appType": "webapp", + "clientName": "emm", + "owner": "admin@carbon.super", + "dynamicClientAppRegistrationServiceURL": "%https.ip%/dynamic-client-web/register", + "apiManagerClientAppRegistrationServiceURL": "%https.ip%/api-application-registration/register/tenants", + "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer", + "tokenScope": "admin", + "callbackUrl": "%https.ip%/api/device-mgt/v1.0" + }, + "tokenServiceURL": "%https.ip%/oauth2/token" + }, + "adminUser":"admin@carbon.super", + "adminRole":"admin", + "usernameLength":30, + "pageSize":10, + "ssoConfiguration" : { + "enabled" : false, + "issuer" : "devicemgt", + "appName" : "devicemgt", + "identityProviderURL" : "%https.ip%/sso/samlsso.jag", + "responseSigningEnabled" : "true", + "keyStorePassword" : "wso2carbon", + "identityAlias" : "wso2carbon", + "keyStoreName" : "/repository/resources/security/wso2carbon.jks" + }, + "userValidationConfig" : { + "usernameJSRegEx" : "^[\\S]{3,30}$", + "usernameRegExViolationErrorMsg" : "Provided username is invalid.", + "usernameHelpMsg" : "Should be in minimum 3 characters long and do not include any whitespaces.", + "firstnameJSRegEx" : "^[\\S]{3,30}$", + "firstnameRegExViolationErrorMsg" : "Provided first name is invalid.", + "lastnameJSRegEx" : "^[\\S]{3,30}$", + "lastnameRegExViolationErrorMsg" : "Provided last name is invalid.", + "emailJSRegEx" : "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/", + "emailRegExViolationErrorMsg" : "Provided email is invalid." + }, + "groupValidationConfig": { + "groupNameJSRegEx": "^[\\S]{3,30}$", + "groupNameRegExViolationErrorMsg": "Provided group name is invalid.", + "groupNameHelpMsg": "Should be in minimum 3 characters long and should not include any whitespaces." + }, + "roleValidationConfig" : { + "roleNameJSRegEx" : "^[\\S]{3,30}$", + "roleNameRegExViolationErrorMsg" : "Provided role name is invalid.", + "roleNameHelpMsg" : "should be in minimum 3 characters long and do not include any whitespaces." + }, + "generalConfig" : { + "host" : "https://localhost:9443", + "companyName" : "WSO2 Carbon Device Manager", + "browserTitle" : "WSO2 Device Manager", + "copyrightPrefix" : "\u00A9 %date-year%, ", + "copyrightOwner" : "WSO2 Inc.", + "copyrightOwnersSite" : "http://www.wso2.org", + "copyrightSuffix" : " All Rights Reserved." + }, + "scopes" : [ + "license-add", "license-view", "device-view", + "device-info", "device-list", "device-view-own", "device-modify", "device-search", + "operation-install", "operation-view", "operation-modify", "operation-uninstall", + "group-add", "group-share", "group-modify", "group-view", "group-remove", + "certificate-modify", "certificate-view", + "configuration-view", "configuration-modify", + "policy-view", "policy-modify", + "device-notification-view", "device-notification-modify", + "feature-view", + "roles-view", "roles-modify", "roles-remove", "roles-add", + "user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add" + ], + "isOAuthEnabled" : true, + "backendRestEndpoints" : { + "deviceMgt" : "/api/device-mgt/v1.0" + } } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index 464093343d..d6f24bd913 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -23,7 +23,7 @@ deviceModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var ArrayList = Packages.java.util.ArrayList; var Properties = Packages.java.util.Properties; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 61bfe9f4b7..06b8dcbf3d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -24,7 +24,7 @@ var groupModule = {}; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var utility = require("/app/modules/utility.js").utility; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js index d191b1868d..cc88752ada 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js @@ -26,7 +26,7 @@ //var invokerRequestWrapper = function () { // // var constants = require("/modules/constants.js"); -// var serviceInvokers = require("/modules/backend-service-invoker.js").backendServiceInvoker; +// var serviceInvokers = require("/modules/token-protected-service-invokers.js").backendServiceInvoker; // // var publicWrappers = []; // diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 429a6b9c1c..d282333644 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -24,7 +24,7 @@ var onFail; var constants = require("/app/modules/constants.js"); onSuccess = function (context) { var utility = require("/app/modules/utility.js").utility; - var apiWrapperUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; + var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; if (context.input.samlToken) { apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); } else { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index 981a58f5ce..dac693543b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -21,7 +21,7 @@ var operationModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"];; + var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js index a46ce90b7c..60e53b3ae3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js @@ -26,7 +26,7 @@ policyModule = function () { var constants = require('/app/modules/constants.js'); var utility = require("/app/modules/utility.js")["utility"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js similarity index 92% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js index 02df5fb3a1..8883cd6eed 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/api-wrapper-util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js @@ -17,11 +17,10 @@ */ /** - * ---------------------------------------------------------------------------- - * Following module includes invokers - * at Jaggery Layer for calling Backend Services, protected by OAuth Tokens. - * These Services include both REST and SOAP Services. - * ---------------------------------------------------------------------------- + * ----------------------------------------------------- + * Following module includes handlers + * at Jaggery Layer for handling OAuth tokens. + * ----------------------------------------------------- */ var handlers = function () { var log = new Log("/app/modules/token-handlers.js"); @@ -39,19 +38,20 @@ var handlers = function () { "client credentials to session context. No username is found as " + "input - setUpEncodedTenantBasedClientCredentials(x)"); } else { - var dynamicClientCredentials = tokenUtil.getDynamicClientCredentials(); + var dynamicClientCredentials = tokenUtil.getDynamicClientAppCredentials(); if (!dynamicClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + "dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)"); } else { - var jwtToken = tokenUtil.getTokenWithJWTGrantType(dynamicClientCredentials); + var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientCredentials); if (!jwtToken) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + "a jwt token - setUpEncodedTenantBasedClientCredentials(x)"); } else { - var tenantBasedClientCredentials = tokenUtil.getTenantBasedAppCredentials(username, jwtToken); + var tenantBasedClientCredentials = tokenUtil. + getTenantBasedClientAppCredentials(username, jwtToken); if (!tenantBasedClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " + "based client credentials to session context as the server is unable " + @@ -89,7 +89,7 @@ var handlers = function () { stringOfScopes += entry + " "; }); accessTokenPair = tokenUtil. - getTokenWithPasswordGrantType(username, + getAccessTokenByPasswordGrantType(username, encodeURIComponent(password), encodedClientCredentials, stringOfScopes); if (!accessTokenPair) { throw new Error("{/app/modules/token-handlers.js} Could not set up access " + @@ -119,7 +119,7 @@ var handlers = function () { var accessTokenPair; // accessTokenPair will include current access token as well as current refresh token accessTokenPair = tokenUtil. - getTokenWithSAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); + getAccessTokenBySAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); if (!accessTokenPair) { throw new Error("{/app/modules/token-handlers.js} Could not set up access token " + "pair by password grant type. Error in token " + @@ -141,7 +141,7 @@ var handlers = function () { "token pair, encoded client credentials or both input are not found under " + "session context - refreshToken()"); } else { - var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair, encodedClientCredentials); + var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); if (!newAccessTokenPair) { log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " + "session context with new access token pair - refreshToken()"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js index 5fd0277d5d..f4688327c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/backend-service-invoker.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js @@ -24,7 +24,7 @@ * ---------------------------------------------------------------------------- */ var invokers = function () { - var log = new Log("/app/modules/backend-service-invoker.js"); + var log = new Log("/app/modules/token-protected-service-invokers.js"); var publicXMLHTTPInvokers = {}; var publicHTTPClientInvokers = {}; @@ -38,7 +38,7 @@ var invokers = function () { var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var userModule = require("/app/modules/user.js")["userModule"]; - var tokenUtil = require("/app/modules/api-wrapper-util.js")["handlers"]; + var tokenUtil = require("/app/modules/token-handlers.js")["handlers"]; /** * This method reads the token pair from the session and return the access token. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index b2c840aae8..0cf67c3213 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -25,7 +25,7 @@ var userModule = function () { var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js")["utility"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/backend-service-invoker.js")["invokers"]; + var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; /* Initializing user manager */ var carbon = require("carbon"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js index d1afc795d3..f9b6bb77b7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js @@ -1,226 +1,285 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var util = function () { var log = new Log("/app/modules/util.js"); - var module = {}; + + var privateMethods = {}; + var publicMethods = {}; + var Base64 = Packages.org.apache.commons.codec.binary.Base64; var String = Packages.java.lang.String; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var carbon = require('carbon'); + var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + + var adminUser = deviceMgtProps["adminUser"]; + var constants = require("/app/modules/constants.js"); - var adminUser = devicemgtProps["adminUser"]; - var clientName = devicemgtProps["clientName"]; + var carbon = require("carbon"); - module.getDynamicClientCredentials = function () { - var payload = { - "callbackUrl": devicemgtProps.callBackUrl, - "clientName": clientName, - "tokenScope": "admin", - "owner": adminUser, - "applicationType": "webapp", - "grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer", - "saasApp" :true - }; - var xhr = new XMLHttpRequest(); - var tokenEndpoint = devicemgtProps.dynamicClientRegistrationEndPoint; - xhr.open("POST", tokenEndpoint, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.send(payload); - var clientData = {}; - if (xhr.status == 201) { - var data = parse(xhr.responseText); - clientData.clientId = data.client_id; - clientData.clientSecret = data.client_secret; - - } else if (xhr.status == 400) { - throw "Invalid client meta data"; - } else { - throw "Error in obtaining client id and secret"; - } - return clientData; - }; - - /** - * Encode the payload in Base64 - * @param payload - * @returns {Packages.java.lang.String} - */ - module.encode = function (payload) { + publicMethods.encode = function (payload) { return new String(Base64.encodeBase64(new String(payload).getBytes())); - } + }; - module.decode = function (payload) { + publicMethods.decode = function (payload) { return new String(Base64.decodeBase64(new String(payload).getBytes())); - } + }; + + publicMethods.getDynamicClientAppCredentials = function () { + // setting up dynamic client application properties + var dcAppProperties = { + "applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"], + "clientName": deviceMgtProps["oauthProvider"]["appRegistration"]["clientName"], + "owner": deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], + "tokenScope": deviceMgtProps["oauthProvider"]["appRegistration"]["tokenScope"], + "grantType": deviceMgtProps["oauthProvider"]["appRegistration"]["grantType"], + "callbackUrl": deviceMgtProps["oauthProvider"]["appRegistration"]["callbackUrl"], + "saasApp" : true + }; + // calling dynamic client app registration service endpoint + var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] + ["dynamicClientAppRegistrationServiceURL"]; + var requestPayload = dcAppProperties; - /** - * Get an AccessToken pair based on username and password - * @param username - * @param password - * @param clientId - * @param clientSecret - * @param scope - * @returns {{accessToken: "", refreshToken: ""}} - */ - module.getTokenWithPasswordGrantType = function (username, password, encodedClientKeys, scope) { var xhr = new XMLHttpRequest(); - var tokenEndpoint = devicemgtProps.idPServer; - xhr.open("POST", tokenEndpoint, false); - xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientKeys); - xhr.send("grant_type=password&username=" + username + "&password=" + password + "&scope=" + scope); - delete password, delete clientSecret, delete encodedClientKeys; - var tokenPair = {}; - if (xhr.status == 200) { - var data = parse(xhr.responseText); - tokenPair.refreshToken = data.refresh_token; - tokenPair.accessToken = data.access_token; - } else if (xhr.status == 403) { - log.error("Error in obtaining token with Password grant type"); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.send(stringify(requestPayload)); + + var dynamicClientCredentials = {}; + if (xhr["status"] == 201 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + dynamicClientCredentials["clientId"] = responsePayload["client_id"]; + dynamicClientCredentials["clientSecret"] = responsePayload["client_secret"]; + } else if (xhr["status"] == 400) { + log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + + "Bad request. Invalid data provided as dynamic client application properties."); + dynamicClientCredentials = null; + } else { + log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + + "Error in retrieving dynamic client credentials."); + dynamicClientCredentials = null; + } + // returning dynamic client credentials + return dynamicClientCredentials; + }; + + publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientCredentials, scopes) { + if (!username || !password || !encodedClientCredentials || !scopes) { + log.error("{/app/modules/util.js} Error in retrieving access token by password " + + "grant type. No username, password, encoded client credentials or scopes are " + + "found - getAccessTokenByPasswordGrantType(a, b, c, d)"); return null; } else { - log.error("Error in obtaining token with Password grant type"); - return null; - } - return tokenPair; - }; - module.getTokenWithSAMLGrantType = function (assertion, clientKeys, scope) { + // calling oauth provider token service endpoint + var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"]; + var requestPayload = "grant_type=password&username=" + + username + "&password=" + password + "&scope=" + scopes; - var assertionXML = module.decode(assertion) ; - var encodedExtractedAssertion; - var extractedAssertion; - //TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem to add formatting - //which causes signature verification to fail. - var assertionStartMarker = " Date: Fri, 29 Jul 2016 14:51:37 +0530 Subject: [PATCH 18/76] Removing obsolete UI modules --- .../jaggeryapps/devicemgt/api/token.jag | 27 ----- .../app/modules/invoker-request-wrapper.js | 98 ------------------- .../devicemgt/app/modules/serverAddress.js | 74 -------------- 3 files changed, 199 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/serverAddress.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag deleted file mode 100644 index 557d4f5a77..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/token.jag +++ /dev/null @@ -1,27 +0,0 @@ -<% -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - @Deprecated - new - */ - -// var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; -// var tokenCookie = apiWrapperUtil.refreshToken(); -// print(tokenCookie); -%> \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js deleted file mode 100644 index cc88752ada..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/invoker-request-wrapper.js +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - @Deprecated - new - */ - -/** - * This invokerRequestWrapper contains the wrappers for invoker util requests. - */ -//var invokerRequestWrapper = function () { -// -// var constants = require("/modules/constants.js"); -// var serviceInvokers = require("/modules/token-protected-service-invokers.js").backendServiceInvoker; -// -// var publicWrappers = []; -// -// publicWrappers.initiate = function (method, url, payload) { -// switch (method) { -// case constants.HTTP_GET: -// var response = serviceInvokers.XMLHttp.get(url, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_POST: -// var response = serviceInvokers.XMLHttp.post(url, payload, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_PUT: -// var response = serviceInvokers.XMLHttp.put(url, payload, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// case constants.HTTP_DELETE: -// var response = serviceInvokers.XMLHttp.delete(url, function (responsePayload) { -// var response = {}; -// response.content = responsePayload["responseContent"]; -// response.status = "success"; -// return response; -// }, -// function (responsePayload) { -// var response = {}; -// response.content = responsePayload; -// response.status = "error"; -// return response; -// }); -// return response; -// break; -// } -// } -// -//}(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/serverAddress.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/serverAddress.js deleted file mode 100644 index 7f8ec0aa76..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/serverAddress.js +++ /dev/null @@ -1,74 +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. - */ - -/* - @Deprecated - new - */ - -//var serverAddress = function () { -// var log = new Log("serverAddress.js"); -// var process = require("process"), -// host = process.getProperty('server.host'), -// ip = process.getProperty('carbon.local.ip'); -// var publicMethods = {}; -// publicMethods.getHTTPSAddress = function () { -// var port = process.getProperty('mgt.transport.https.proxyPort'); -// if (!port) { -// port = process.getProperty('mgt.transport.https.port'); -// } -// if (host === "localhost") { -// return "https://" + ip + ":" + port; -// } else { -// return "https://" + host + ":" + port; -// } -// }; -// publicMethods.getHPPTAddress = function () { -// var port = process.getProperty('mgt.transport.http.proxyPort'); -// if (!port) { -// port = process.getProperty('mgt.transport.http.port'); -// } -// if (host === "localhost") { -// return "http://" + ip + ":" + port; -// } else { -// return "http://" + host + ":" + port; -// } -// }; -// publicMethods.getWSSAddress = function () { -// var port = process.getProperty('mgt.transport.https.proxyPort'); -// if (!port) { -// port = process.getProperty('mgt.transport.https.port'); -// } -// if (host === "localhost") { -// return "wss://" + ip + ":" + port; -// } else { -// return "wss://" + host + ":" + port; -// } -// }; -// publicMethods.getWSAddress = function () { -// var port = process.getProperty('mgt.transport.http.proxyPort'); -// if (!port) { -// port = process.getProperty('mgt.transport.http.port'); -// } -// if (host === "localhost") { -// return "ws://" + ip + ":" + port; -// } else { -// return "ws://" + host + ":" + port; -// } -// }; -// return publicMethods; -//}(); \ No newline at end of file From a4c5aa59517ef410329b5308c6d229d96feb773f Mon Sep 17 00:00:00 2001 From: dilanua Date: Fri, 29 Jul 2016 15:15:02 +0530 Subject: [PATCH 19/76] Refactoring OAuth utilities at UI Layer --- .../devicemgt/app/modules/token-handlers.js | 9 +++++---- .../jaggeryapps/devicemgt/app/modules/util.js | 12 +++++------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js index 8883cd6eed..4aa17fb54b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js @@ -38,13 +38,13 @@ var handlers = function () { "client credentials to session context. No username is found as " + "input - setUpEncodedTenantBasedClientCredentials(x)"); } else { - var dynamicClientCredentials = tokenUtil.getDynamicClientAppCredentials(); - if (!dynamicClientCredentials) { + var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(); + if (!dynamicClientAppCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + "dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)"); } else { - var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientCredentials); + var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials); if (!jwtToken) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + @@ -141,7 +141,8 @@ var handlers = function () { "token pair, encoded client credentials or both input are not found under " + "session context - refreshToken()"); } else { - var newAccessTokenPair = tokenUtil.refreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); + var newAccessTokenPair = tokenUtil. + getNewAccessTokenByRefreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); if (!newAccessTokenPair) { log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " + "session context with new access token pair - refreshToken()"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js index f9b6bb77b7..2236c44ddd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js @@ -24,10 +24,8 @@ var util = function () { var Base64 = Packages.org.apache.commons.codec.binary.Base64; var String = Packages.java.lang.String; + var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; - - var adminUser = deviceMgtProps["adminUser"]; - var constants = require("/app/modules/constants.js"); var carbon = require("carbon"); @@ -225,7 +223,7 @@ var util = function () { "username - getTenantBasedClientAppCredentials(x, y)"); return null; } else { - var cachedTenantBasedClientAppCredentials = publicMethods. + var cachedTenantBasedClientAppCredentials = privateMethods. getCachedTenantBasedClientAppCredentials(tenantDomain); if (cachedTenantBasedClientAppCredentials) { return cachedTenantBasedClientAppCredentials; @@ -247,7 +245,7 @@ var util = function () { var tenantBasedClientAppCredentials = {}; tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"]; tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; - publicMethods. + privateMethods. setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); return tenantBasedClientAppCredentials; } else { @@ -260,7 +258,7 @@ var util = function () { } }; - publicMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientCredentials) { + privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientCredentials) { var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); if (!cachedTenantBasedClientAppCredentialsMap) { cachedTenantBasedClientAppCredentialsMap = {}; @@ -271,7 +269,7 @@ var util = function () { } }; - publicMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) { + privateMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) { var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); if (!cachedTenantBasedClientAppCredentialsMap || !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { From 70074e2f3e77a71626c495b0faeaed94e0f0c62c Mon Sep 17 00:00:00 2001 From: dilanua Date: Fri, 29 Jul 2016 15:37:27 +0530 Subject: [PATCH 20/76] Refactoring OAuth utilities at UI Layer --- .../devicemgt/app/modules/token-handlers.js | 14 ++--- .../token-protected-service-invokers.js | 2 +- .../jaggeryapps/devicemgt/app/modules/util.js | 56 +++++++++---------- 3 files changed, 36 insertions(+), 36 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js index 4aa17fb54b..5d1097a2ec 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js @@ -132,22 +132,22 @@ var handlers = function () { } }; - publicMethods.refreshToken = function () { + publicMethods.refreshAccessToken = function () { var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); // accessTokenPair includes current access token as well as current refresh token var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!accessTokenPair || !encodedClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Error in refreshing tokens. Either the access " + "token pair, encoded client credentials or both input are not found under " + - "session context - refreshToken()"); + "session context - refreshAccessToken()"); } else { - var newAccessTokenPair = tokenUtil. + var newTokenPair = tokenUtil. getNewAccessTokenByRefreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); - if (!newAccessTokenPair) { - log.error("{/app/modules/token-handlers.js} Error in refreshing tokens. Unable to update " + - "session context with new access token pair - refreshToken()"); + if (!newTokenPair) { + log.error("{/app/modules/token-handlers.js} Error in refreshing access token. Unable to update " + + "session context with new access token pair - refreshAccessToken()"); } else { - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newAccessTokenPair)); + session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newTokenPair)); } } }; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js index f4688327c7..f1d4b33946 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js @@ -103,7 +103,7 @@ var invokers = function () { if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { - tokenUtil.refreshToken(); + tokenUtil.refreshAccessToken(); return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count); } else { return responseCallback(xmlHttpRequest); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js index 2236c44ddd..c9328d8cbd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js @@ -58,28 +58,28 @@ var util = function () { xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(stringify(requestPayload)); - var dynamicClientCredentials = {}; + var dynamicClientAppCredentials = {}; if (xhr["status"] == 201 && xhr["responseText"]) { var responsePayload = parse(xhr["responseText"]); - dynamicClientCredentials["clientId"] = responsePayload["client_id"]; - dynamicClientCredentials["clientSecret"] = responsePayload["client_secret"]; + dynamicClientAppCredentials["clientId"] = responsePayload["client_id"]; + dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; } else if (xhr["status"] == 400) { log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + "Bad request. Invalid data provided as dynamic client application properties."); - dynamicClientCredentials = null; + dynamicClientAppCredentials = null; } else { log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + "Error in retrieving dynamic client credentials."); - dynamicClientCredentials = null; + dynamicClientAppCredentials = null; } // returning dynamic client credentials - return dynamicClientCredentials; + return dynamicClientAppCredentials; }; - publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientCredentials, scopes) { - if (!username || !password || !encodedClientCredentials || !scopes) { + publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) { + if (!username || !password || !encodedClientAppCredentials || !scopes) { log.error("{/app/modules/util.js} Error in retrieving access token by password " + - "grant type. No username, password, encoded client credentials or scopes are " + + "grant type. No username, password, encoded client app credentials or scopes are " + "found - getAccessTokenByPasswordGrantType(a, b, c, d)"); return null; } else { @@ -91,7 +91,7 @@ var util = function () { var xhr = new XMLHttpRequest(); xhr.open("POST", requestURL, false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials); + xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); xhr.send(requestPayload); if (xhr["status"] == 200 && xhr["responseText"]) { @@ -108,10 +108,10 @@ var util = function () { } }; - publicMethods.getAccessTokenBySAMLGrantType = function (assertion, encodedClientCredentials, scopes) { - if (!assertion || !encodedClientCredentials || !scopes) { + publicMethods.getAccessTokenBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) { + if (!assertion || !encodedClientAppCredentials || !scopes) { log.error("{/app/modules/util.js} Error in retrieving access token by saml " + - "grant type. No assertion, encoded client credentials or scopes are " + + "grant type. No assertion, encoded client app credentials or scopes are " + "found - getAccessTokenBySAMLGrantType(x, y, z)"); return null; } else { @@ -143,7 +143,7 @@ var util = function () { var xhr = new XMLHttpRequest(); xhr.open("POST", requestURL, false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials); + xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); xhr.send(requestPayload); if (xhr["status"] == 200 && xhr["responseText"]) { @@ -161,10 +161,10 @@ var util = function () { } }; - publicMethods.getNewAccessTokenByRefreshToken = function (refreshToken, encodedClientCredentials, scopes) { - if (!refreshToken || !encodedClientCredentials) { + publicMethods.getNewAccessTokenByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) { + if (!refreshToken || !encodedClientAppCredentials) { log.error("{/app/modules/util.js} Error in retrieving new access token by current " + - "refresh token. No refresh token or encoded client credentials are " + + "refresh token. No refresh token or encoded client app credentials are " + "found - getNewAccessTokenByRefreshToken(x, y, z)"); return null; } else { @@ -177,7 +177,7 @@ var util = function () { var xhr = new XMLHttpRequest(); xhr.open("POST", requestURL, false); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - xhr.setRequestHeader("Authorization", "Basic " + encodedClientCredentials); + xhr.setRequestHeader("Authorization", "Basic " + encodedClientAppCredentials); xhr.send(requestPayload); if (xhr["status"] == 200 && xhr["responseText"]) { @@ -194,10 +194,10 @@ var util = function () { } }; - publicMethods.getAccessTokenByJWTGrantType = function (clientCredentials) { - if (!clientCredentials) { - log.error("{/app/modules/util.js} Error in retrieving new access token by current refresh " + - "token. No client credentials are found as input - getAccessTokenByJWTGrantType(x)"); + publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) { + if (!clientAppCredentials) { + log.error("{/app/modules/util.js} Error in retrieving new access token by current refresh token. " + + "No client app credentials are found as input - getAccessTokenByJWTGrantType(x)"); return null; } else { var JWTClientManagerServicePackagePath = @@ -205,15 +205,15 @@ var util = function () { var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath); var jwtClient = JWTClientManagerService.getJWTClient(); // returning access token by JWT grant type - return jwtClient.getAccessToken(clientCredentials["clientId"], clientCredentials["clientSecret"], + return jwtClient.getAccessToken(clientAppCredentials["clientId"], clientAppCredentials["clientSecret"], deviceMgtProps["oauthProvider"]["appRegistration"]["owner"], null)["accessToken"]; } }; publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) { if (!username || !jwtToken) { - log.error("{/app/modules/util.js} Error in retrieving tenant based client application credentials. " + - "No username or jwt token is found as input - getTenantBasedClientAppCredentials(x, y)"); + log.error("{/app/modules/util.js} Error in retrieving tenant based client app " + + "credentials. No username or jwt token is found as input - getTenantBasedClientAppCredentials(x, y)"); return null; } else { var tenantDomain = carbon.server.tenantDomain({username: username}); @@ -258,14 +258,14 @@ var util = function () { } }; - privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientCredentials) { + privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientAppCredentials) { var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); if (!cachedTenantBasedClientAppCredentialsMap) { cachedTenantBasedClientAppCredentialsMap = {}; - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientCredentials; + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap); } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientCredentials; + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; } }; From b86be8375c67b9a25465e92e890b634e93dc1963 Mon Sep 17 00:00:00 2001 From: dilanua Date: Fri, 29 Jul 2016 15:41:43 +0530 Subject: [PATCH 21/76] Refactoring OAuth utilities at UI Layer --- .../devicemgt/app/modules/token-handlers.js | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js index 5d1097a2ec..097732c059 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js @@ -32,30 +32,30 @@ var handlers = function () { var privateMethods = {}; var publicMethods = {}; - privateMethods.setUpEncodedTenantBasedClientCredentials = function (username) { + privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) { if (!username) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context. No username is found as " + - "input - setUpEncodedTenantBasedClientCredentials(x)"); + "input - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(); if (!dynamicClientAppCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + - "dynamic client credentials - setUpEncodedTenantBasedClientCredentials(x)"); + "dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials); if (!jwtToken) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + - "a jwt token - setUpEncodedTenantBasedClientCredentials(x)"); + "a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var tenantBasedClientCredentials = tokenUtil. getTenantBasedClientAppCredentials(username, jwtToken); if (!tenantBasedClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " + "based client credentials to session context as the server is unable " + - "to obtain such credentials - setUpEncodedTenantBasedClientCredentials(x)"); + "to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var encodedTenantBasedClientCredentials = tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" + @@ -74,7 +74,7 @@ var handlers = function () { "password grant type. Either username, password or both are missing as " + "input - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { - privateMethods.setUpEncodedTenantBasedClientCredentials(username); + privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!encodedClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + @@ -109,7 +109,7 @@ var handlers = function () { "saml grant type. Either username, samlToken or both are missing as " + "input - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { - privateMethods.setUpEncodedTenantBasedClientCredentials(username); + privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!encodedClientCredentials) { throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair " + From 032b5d129ab3aa85f1127d0035d06c41f6ce2fc7 Mon Sep 17 00:00:00 2001 From: dilanua Date: Fri, 29 Jul 2016 16:48:20 +0530 Subject: [PATCH 22/76] Adding OAUTH module to UI --- .../devicemgt/api/data-tables-invoker-api.jag | 2 +- .../jaggeryapps/devicemgt/api/device-api.jag | 2 +- .../jaggeryapps/devicemgt/api/group-api.jag | 2 +- .../jaggeryapps/devicemgt/api/invoker-api.jag | 2 +- .../devicemgt/api/operation-api.jag | 2 +- .../jaggeryapps/devicemgt/api/user-api.jag | 4 +-- .../devicemgt/app/modules/device.js | 2 +- .../devicemgt/app/modules/group.js | 2 +- .../devicemgt/app/modules/login.js | 2 +- .../app/modules/{ => oauth}/token-handlers.js | 28 +++++++++---------- .../token-protected-service-invokers.js | 4 +-- .../devicemgt/app/modules/{ => oauth}/util.js | 28 +++++++++---------- .../devicemgt/app/modules/operation.js | 2 +- .../devicemgt/app/modules/policy.js | 2 +- .../jaggeryapps/devicemgt/app/modules/user.js | 2 +- 15 files changed, 43 insertions(+), 43 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => oauth}/token-handlers.js (83%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => oauth}/token-protected-service-invokers.js (99%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => oauth}/util.js (90%) 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 59c142ff2c..6777383200 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 @@ -23,7 +23,7 @@ var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; function appendQueryParam (url, queryParam , value) { if (url.indexOf("?") > 0) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index a1d496f174..74ba1290d4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -26,7 +26,7 @@ var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; -var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag index 46ac2913f5..cfce1f0409 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -24,7 +24,7 @@ var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); var result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 29da7a76b9..741bf1ed53 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -24,7 +24,7 @@ var uriMatcher = new URIMatcher(String(uri)); var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; -var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; if (uriMatcher.match("/{context}/api/invoker/execute/")) { var restAPIRequestDetails = request.getContent(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index a08a662588..99fa61a9f9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -22,7 +22,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/operation-api.jag"); -var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; +var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; if (uriMatcher.match("/{context}/api/operation/paginate")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index a797c2f3fa..24aad8ece9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -27,8 +27,8 @@ var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; -var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; -var util = require("/app/modules/util.js").util; +var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; +var util = require("/app/modules/oauth/util.js").util; var responseProcessor = require('utils').response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index d6f24bd913..085b9b7ea1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -23,7 +23,7 @@ deviceModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var ArrayList = Packages.java.util.ArrayList; var Properties = Packages.java.util.Properties; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 06b8dcbf3d..549d0d8787 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -24,7 +24,7 @@ var groupModule = {}; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var utility = require("/app/modules/utility.js").utility; - var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var groupServiceEndpoint = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/groups"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index d282333644..9c11436e2d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -24,7 +24,7 @@ var onFail; var constants = require("/app/modules/constants.js"); onSuccess = function (context) { var utility = require("/app/modules/utility.js").utility; - var apiWrapperUtil = require("/app/modules/token-handlers.js")["handlers"]; + var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; if (context.input.samlToken) { apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); } else { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js similarity index 83% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 097732c059..030b1cd11d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -23,9 +23,9 @@ * ----------------------------------------------------- */ var handlers = function () { - var log = new Log("/app/modules/token-handlers.js"); + var log = new Log("/app/modules/oauth/token-handlers.js"); - var tokenUtil = require("/app/modules/util.js")["util"]; + var tokenUtil = require("/app/modules/oauth/util.js")["util"]; var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; @@ -34,26 +34,26 @@ var handlers = function () { privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) { if (!username) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context. No username is found as " + "input - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(); if (!dynamicClientAppCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + "dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials); if (!jwtToken) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant based " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + "a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var tenantBasedClientCredentials = tokenUtil. getTenantBasedClientAppCredentials(username, jwtToken); if (!tenantBasedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up encoded tenant " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " + "based client credentials to session context as the server is unable " + "to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { @@ -70,14 +70,14 @@ var handlers = function () { publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) { if (!username || !password) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + "password grant type. Either username, password or both are missing as " + "input - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + "password grant type. Encoded client credentials are " + "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { @@ -92,7 +92,7 @@ var handlers = function () { getAccessTokenByPasswordGrantType(username, encodeURIComponent(password), encodedClientCredentials, stringOfScopes); if (!accessTokenPair) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access " + "token pair by password grant type. Error in token " + "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { @@ -105,14 +105,14 @@ var handlers = function () { publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) { if (!username || !samlToken) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair by " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + "saml grant type. Either username, samlToken or both are missing as " + "input - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token pair " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " + "by saml grant type. Encoded client credentials are " + "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { @@ -121,7 +121,7 @@ var handlers = function () { accessTokenPair = tokenUtil. getAccessTokenBySAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); if (!accessTokenPair) { - throw new Error("{/app/modules/token-handlers.js} Could not set up access token " + + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token " + "pair by password grant type. Error in token " + "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); } else { @@ -137,14 +137,14 @@ var handlers = function () { // accessTokenPair includes current access token as well as current refresh token var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); if (!accessTokenPair || !encodedClientCredentials) { - throw new Error("{/app/modules/token-handlers.js} Error in refreshing tokens. Either the access " + + throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the access " + "token pair, encoded client credentials or both input are not found under " + "session context - refreshAccessToken()"); } else { var newTokenPair = tokenUtil. getNewAccessTokenByRefreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); if (!newTokenPair) { - log.error("{/app/modules/token-handlers.js} Error in refreshing access token. Unable to update " + + log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing access token. Unable to update " + "session context with new access token pair - refreshAccessToken()"); } else { session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newTokenPair)); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index f1d4b33946..0ff97f851e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -24,7 +24,7 @@ * ---------------------------------------------------------------------------- */ var invokers = function () { - var log = new Log("/app/modules/token-protected-service-invokers.js"); + var log = new Log("/app/modules/oauth/token-protected-service-invokers.js"); var publicXMLHTTPInvokers = {}; var publicHTTPClientInvokers = {}; @@ -38,7 +38,7 @@ var invokers = function () { var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var userModule = require("/app/modules/user.js")["userModule"]; - var tokenUtil = require("/app/modules/token-handlers.js")["handlers"]; + var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; /** * This method reads the token pair from the session and return the access token. diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js similarity index 90% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js index c9328d8cbd..3776857960 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js @@ -17,7 +17,7 @@ */ var util = function () { - var log = new Log("/app/modules/util.js"); + var log = new Log("/app/modules/oauth/util.js"); var privateMethods = {}; var publicMethods = {}; @@ -64,11 +64,11 @@ var util = function () { dynamicClientAppCredentials["clientId"] = responsePayload["client_id"]; dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; } else if (xhr["status"] == 400) { - log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + + log.error("{/app/modules/oauth/util.js - getDynamicClientAppCredentials()} " + "Bad request. Invalid data provided as dynamic client application properties."); dynamicClientAppCredentials = null; } else { - log.error("{/app/modules/util.js - getDynamicClientAppCredentials()} " + + log.error("{/app/modules/oauth/util.js - getDynamicClientAppCredentials()} " + "Error in retrieving dynamic client credentials."); dynamicClientAppCredentials = null; } @@ -78,7 +78,7 @@ var util = function () { publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) { if (!username || !password || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/util.js} Error in retrieving access token by password " + + log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + "grant type. No username, password, encoded client app credentials or scopes are " + "found - getAccessTokenByPasswordGrantType(a, b, c, d)"); return null; @@ -101,7 +101,7 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/util.js} Error in retrieving access token by password " + + log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + "grant type - getAccessTokenByPasswordGrantType(a, b, c, d)"); return null; } @@ -110,7 +110,7 @@ var util = function () { publicMethods.getAccessTokenBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) { if (!assertion || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/util.js} Error in retrieving access token by saml " + + log.error("{/app/modules/oauth/util.js} Error in retrieving access token by saml " + "grant type. No assertion, encoded client app credentials or scopes are " + "found - getAccessTokenBySAMLGrantType(x, y, z)"); return null; @@ -127,7 +127,7 @@ var util = function () { var extractedAssertion; if (assertionStartIndex == -1 || assertionEndIndex == -1) { - log.error("{/app/modules/util.js} Error in retrieving access token by saml grant type. " + + log.error("{/app/modules/oauth/util.js} Error in retrieving access token by saml grant type. " + "Issue in assertion format - getAccessTokenBySAMLGrantType(x, y, z)"); return null; } else { @@ -153,7 +153,7 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/util.js} Error in retrieving access token by password " + + log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + "grant type - getAccessTokenBySAMLGrantType(x, y, z)"); return null; } @@ -163,7 +163,7 @@ var util = function () { publicMethods.getNewAccessTokenByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) { if (!refreshToken || !encodedClientAppCredentials) { - log.error("{/app/modules/util.js} Error in retrieving new access token by current " + + log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by current " + "refresh token. No refresh token or encoded client app credentials are " + "found - getNewAccessTokenByRefreshToken(x, y, z)"); return null; @@ -187,7 +187,7 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/util.js} Error in retrieving new access token by " + + log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by " + "current refresh token - getNewAccessTokenByRefreshToken(x, y, z)"); return null; } @@ -196,7 +196,7 @@ var util = function () { publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) { if (!clientAppCredentials) { - log.error("{/app/modules/util.js} Error in retrieving new access token by current refresh token. " + + log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by current refresh token. " + "No client app credentials are found as input - getAccessTokenByJWTGrantType(x)"); return null; } else { @@ -212,13 +212,13 @@ var util = function () { publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) { if (!username || !jwtToken) { - log.error("{/app/modules/util.js} Error in retrieving tenant based client app " + + log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client app " + "credentials. No username or jwt token is found as input - getTenantBasedClientAppCredentials(x, y)"); return null; } else { var tenantDomain = carbon.server.tenantDomain({username: username}); if (!tenantDomain) { - log.error("{/app/modules/util.js} Error in retrieving tenant based client application " + + log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client application " + "credentials. Unable to obtain a valid tenant domain for provided " + "username - getTenantBasedClientAppCredentials(x, y)"); return null; @@ -249,7 +249,7 @@ var util = function () { setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); return tenantBasedClientAppCredentials; } else { - log.error("{/app/modules/util.js} Error in retrieving tenant based client " + + log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client " + "application credentials from API Manager - getTenantBasedClientAppCredentials(x, y)"); return null; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index dac693543b..3b1e11a9c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -21,7 +21,7 @@ var operationModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"];; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js index 60e53b3ae3..0fbe5a2116 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js @@ -26,7 +26,7 @@ policyModule = function () { var constants = require('/app/modules/constants.js'); var utility = require("/app/modules/utility.js")["utility"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index 0cf67c3213..2a28f5fddf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -25,7 +25,7 @@ var userModule = function () { var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js")["utility"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/token-protected-service-invokers.js")["invokers"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; /* Initializing user manager */ var carbon = require("carbon"); From 7017f6e32b9fab6ecc4bf984bfcfe3f74b36c406 Mon Sep 17 00:00:00 2001 From: dilanua Date: Sat, 30 Jul 2016 13:52:44 +0530 Subject: [PATCH 23/76] Updating OAuth module dependants --- .../main/resources/jaggeryapps/devicemgt/api/user-api.jag | 8 +++----- .../jaggeryapps/devicemgt/app/modules/operation.js | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index 24aad8ece9..a9665ac04c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -46,10 +46,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPair("password", { - "username": username, - "password": password - }); + apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(username, password); }, function () { response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()}); }); @@ -68,7 +65,8 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPair("password", {"username": username, "password": password}); + + apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(username, password); var permissions = userModule.getUIPermissions(); if (permissions.VIEW_DASHBOARD) { response.sendRedirect(constants.WEB_APP_CONTEXT); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index 3b1e11a9c6..98890b9a19 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -21,7 +21,7 @@ var operationModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; var privateMethods = {}; From 020f35cb4e9d3abe0b70797ff9cf345ca5854918 Mon Sep 17 00:00:00 2001 From: dilanua Date: Sat, 30 Jul 2016 19:47:34 +0530 Subject: [PATCH 24/76] Updating OAuth UI Module --- .../jaggeryapps/devicemgt/api/user-api.jag | 4 +- .../devicemgt/app/modules/constants.js | 4 +- .../devicemgt/app/modules/login.js | 4 +- .../app/modules/oauth/token-handlers.js | 193 +++++++++--------- .../oauth/token-protected-service-invokers.js | 24 +-- 5 files changed, 115 insertions(+), 114 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index a9665ac04c..1d04e761af 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -46,7 +46,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { if (log.isDebugEnabled()) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(username, password); + apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password); }, function () { response = responseProcessor.buildSuccessResponse(response, 200, {'sessionId': session.getId()}); }); @@ -66,7 +66,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { log.debug("User Logged In : " + user); } - apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(username, password); + apiWrapperUtil.setupTokenPairByPasswordGrantType(username, password); var permissions = userModule.getUIPermissions(); if (permissions.VIEW_DASHBOARD) { response.sendRedirect(constants.WEB_APP_CONTEXT); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js index 890a7e500e..f1ebedd948 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js @@ -59,8 +59,8 @@ var USER_STORE_CONFIG_ADMIN_SERVICE_END_POINT = var SOAP_VERSION = 1.2; var WEB_SERVICE_ADDRESSING_VERSION = 1.0; -var ACCESS_TOKEN_PAIR_IDENTIFIER = "accessTokenPair"; -var ENCODED_CLIENT_KEYS_IDENTIFIER = "encodedClientKey"; +var TOKEN_PAIR = "tokenPair"; +var ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS = "encodedTenantBasedClientAppCredentials"; var CONTENT_TYPE_IDENTIFIER = "Content-Type"; var CONTENT_DISPOSITION_IDENTIFIER = "Content-Disposition"; var APPLICATION_JSON = "application/json"; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index 9c11436e2d..c383e1e817 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -26,9 +26,9 @@ var onFail; var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; if (context.input.samlToken) { - apiWrapperUtil.setupAccessTokenPairBySamlGrantType(context.input.username, context.input.samlToken); + apiWrapperUtil.setupTokenPairBySamlGrantType(context.input.username, context.input.samlToken); } else { - apiWrapperUtil.setupAccessTokenPairByPasswordGrantType(context.input.username, context.input.password); + apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password); } var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var carbonServer = require("carbon").server; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 030b1cd11d..867c1db8da 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -29,128 +29,129 @@ var handlers = function () { var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; - var privateMethods = {}; var publicMethods = {}; + var privateMethods = {}; + + publicMethods.setupTokenPairByPasswordGrantType = function (username, password) { + if (!username || !password) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + + "password grant type. Either username of logged in user, password or both are missing " + + "as input - setupTokenPairByPasswordGrantType(x, y)"); + } else { + privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); + var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]); + if (!encodedClientAppCredentials) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + + "password grant type. Encoded client credentials are " + + "missing - setupTokenPairByPasswordGrantType(x, y)"); + } else { + var tokenPair; + // tokenPair will include current access token as well as current refresh token + var arrayOfScopes = devicemgtProps["scopes"]; + var stringOfScopes = ""; + arrayOfScopes.forEach(function (entry) { + stringOfScopes += entry + " "; + }); + tokenPair = tokenUtil. + getAccessTokenByPasswordGrantType(username, + encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes); + if (!tokenPair) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " + + "token pair by password grant type. Error in token " + + "retrieval - setupTokenPairByPasswordGrantType(x, y)"); + } else { + // setting up access token pair into session context as a string + session.put(constants["TOKEN_PAIR"], stringify(tokenPair)); + } + } + } + }; + + publicMethods.setupTokenPairBySamlGrantType = function (username, samlToken) { + if (!username || !samlToken) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + + "saml grant type. Either username of logged in user, samlToken or both are missing " + + "as input - setupTokenPairByPasswordGrantType(x, y)"); + } else { + privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); + var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]); + if (!encodedClientAppCredentials) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " + + "by saml grant type. Encoded client credentials are " + + "missing - setupTokenPairByPasswordGrantType(x, y)"); + } else { + var tokenPair; + // accessTokenPair will include current access token as well as current refresh token + tokenPair = tokenUtil. + getAccessTokenBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION"); + if (!tokenPair) { + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " + + "pair by password grant type. Error in token " + + "retrieval - setupTokenPairByPasswordGrantType(x, y)"); + } else { + // setting up access token pair into session context as a string + session.put(constants["TOKEN_PAIR"], stringify(tokenPair)); + } + } + } + }; + + publicMethods.refreshTokenPair = function () { + var currentTokenPair = parse(session.get(constants["TOKEN_PAIR"])); + // currentTokenPair includes current access token as well as current refresh token + var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]); + if (!currentTokenPair || !encodedClientAppCredentials) { + throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the " + + "token pair, encoded client app credentials or both input are not found under " + + "session context - refreshTokenPair()"); + } else { + var newTokenPair = tokenUtil. + getNewAccessTokenByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials); + if (!newTokenPair) { + log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " + + "Unable to update session context with new access token pair - refreshTokenPair()"); + } else { + session.put(constants["TOKEN_PAIR"], stringify(newTokenPair)); + } + } + }; privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) { if (!username) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + - "client credentials to session context. No username is found as " + - "input - setUpEncodedTenantBasedClientAppCredentials(x)"); + "client credentials to session context. No username of logged in user is found as " + + "input - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(); if (!dynamicClientAppCredentials) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + - "dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); + "dynamic client credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { var jwtToken = tokenUtil.getAccessTokenByJWTGrantType(dynamicClientAppCredentials); if (!jwtToken) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context as the server is unable to obtain " + - "a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)"); + "a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { - var tenantBasedClientCredentials = tokenUtil. + var tenantBasedClientAppCredentials = tokenUtil. getTenantBasedClientAppCredentials(username, jwtToken); - if (!tenantBasedClientCredentials) { + if (!tenantBasedClientAppCredentials) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " + "based client credentials to session context as the server is unable " + - "to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); + "to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); } else { - var encodedTenantBasedClientCredentials = - tokenUtil.encode(tenantBasedClientCredentials["clientId"] + ":" + - tenantBasedClientCredentials["clientSecret"]); + var encodedTenantBasedClientAppCredentials = + tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" + + tenantBasedClientAppCredentials["clientSecret"]); // setting up encoded tenant based client credentials to session context. - session.put(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"], encodedTenantBasedClientCredentials); + session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"], + encodedTenantBasedClientAppCredentials); } } } } }; - publicMethods.setupAccessTokenPairByPasswordGrantType = function (username, password) { - if (!username || !password) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + - "password grant type. Either username, password or both are missing as " + - "input - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!encodedClientCredentials) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + - "password grant type. Encoded client credentials are " + - "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - var accessTokenPair; - // accessTokenPair will include current access token as well as current refresh token - var arrayOfScopes = devicemgtProps["scopes"]; - var stringOfScopes = ""; - arrayOfScopes.forEach(function (entry) { - stringOfScopes += entry + " "; - }); - accessTokenPair = tokenUtil. - getAccessTokenByPasswordGrantType(username, - encodeURIComponent(password), encodedClientCredentials, stringOfScopes); - if (!accessTokenPair) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access " + - "token pair by password grant type. Error in token " + - "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - // setting up access token pair into session context as a string - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); - } - } - } - }; - - publicMethods.setupAccessTokenPairBySamlGrantType = function (username, samlToken) { - if (!username || !samlToken) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + - "saml grant type. Either username, samlToken or both are missing as " + - "input - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - privateMethods.setUpEncodedTenantBasedClientAppCredentials(username); - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!encodedClientCredentials) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair " + - "by saml grant type. Encoded client credentials are " + - "missing - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - var accessTokenPair; - // accessTokenPair will include current access token as well as current refresh token - accessTokenPair = tokenUtil. - getAccessTokenBySAMLGrantType(samlToken, encodedClientCredentials, "PRODUCTION"); - if (!accessTokenPair) { - throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token " + - "pair by password grant type. Error in token " + - "retrieval - setupAccessTokenPairByPasswordGrantType(x, y)"); - } else { - // setting up access token pair into session context as a string - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(accessTokenPair)); - } - } - } - }; - - publicMethods.refreshAccessToken = function () { - var accessTokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); - // accessTokenPair includes current access token as well as current refresh token - var encodedClientCredentials = session.get(constants["ENCODED_CLIENT_KEYS_IDENTIFIER"]); - if (!accessTokenPair || !encodedClientCredentials) { - throw new Error("{/app/modules/oauth/token-handlers.js} Error in refreshing tokens. Either the access " + - "token pair, encoded client credentials or both input are not found under " + - "session context - refreshAccessToken()"); - } else { - var newTokenPair = tokenUtil. - getNewAccessTokenByRefreshToken(accessTokenPair["refreshToken"], encodedClientCredentials); - if (!newTokenPair) { - log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing access token. Unable to update " + - "session context with new access token pair - refreshAccessToken()"); - } else { - session.put(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"], stringify(newTokenPair)); - } - } - }; - return publicMethods; }(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index 0ff97f851e..2b9a3d09c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -42,10 +42,10 @@ var invokers = function () { /** * This method reads the token pair from the session and return the access token. - * If the token pair s not set in the session this will send a redirect to the login page. + * If the token pair is not set in the session, this will return null. */ privateMethods.getAccessToken = function () { - var tokenPair = parse(session.get(constants["ACCESS_TOKEN_PAIR_IDENTIFIER"])); + var tokenPair = parse(session.get(constants["TOKEN_PAIR"])); if (tokenPair) { return tokenPair["accessToken"]; } else { @@ -103,7 +103,7 @@ var invokers = function () { if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { - tokenUtil.refreshAccessToken(); + tokenUtil.refreshTokenPair(); return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, ++count); } else { return responseCallback(xmlHttpRequest); @@ -122,7 +122,7 @@ var invokers = function () { }; /** - * This method invokes return initiateXMLHttpRequest for get calls + * This method invokes return initiateXMLHttpRequest for get calls. * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ @@ -132,7 +132,7 @@ var invokers = function () { }; /** - * This method invokes return initiateXMLHttpRequest for post calls + * This method invokes return initiateXMLHttpRequest for post calls. * @param endpoint Backend REST API url. * @param requestPayload payload/data if exists which is needed to be send. * @param responseCallback a function to be called with response retrieved. @@ -142,7 +142,7 @@ var invokers = function () { }; /** - * This method invokes return initiateXMLHttpRequest for put calls + * This method invokes return initiateXMLHttpRequest for put calls. * @param endpoint Backend REST API url. * @param requestPayload payload/data if exists which is needed to be send. * @param responseCallback a function to be called with response retrieved. @@ -152,7 +152,7 @@ var invokers = function () { }; /** - * This method invokes return initiateXMLHttpRequest for delete calls + * This method invokes return initiateXMLHttpRequest for delete calls. * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ @@ -214,7 +214,7 @@ var invokers = function () { }; /** - * This method invokes return initiateWSRequest for soap calls + * This method invokes return initiateWSRequest for soap calls. * @param action describes particular soap action. * @param requestPayload SOAP request payload which is needed to be send. * @param endpoint service end point to be triggered. @@ -303,7 +303,7 @@ var invokers = function () { }; /** - * This method invokes return initiateHTTPClientRequest for get calls + * This method invokes return initiateHTTPClientRequest for get calls. * @param url target url. * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. @@ -315,7 +315,7 @@ var invokers = function () { }; /** - * This method invokes return initiateHTTPClientRequest for post calls + * This method invokes return initiateHTTPClientRequest for post calls. * @param url target url. * @param payload payload/data which need to be send. * @param successCallback a function to be called if the respond if successful. @@ -327,7 +327,7 @@ var invokers = function () { }; /** - * This method invokes return initiateHTTPClientRequest for put calls + * This method invokes return initiateHTTPClientRequest for put calls. * @param url target url. * @param payload payload/data which need to be send. * @param successCallback a function to be called if the respond if successful. @@ -339,7 +339,7 @@ var invokers = function () { }; /** - * This method invokes return initiateHTTPClientRequest for delete calls + * This method invokes return initiateHTTPClientRequest for delete calls. * @param url target url. * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. From bc4192280c57fd094f1eb38e5ec5551ce81cc5b8 Mon Sep 17 00:00:00 2001 From: dilanua Date: Sat, 30 Jul 2016 20:38:32 +0530 Subject: [PATCH 25/76] Updating OAuth UI Module --- .../jaggeryapps/devicemgt/api/user-api.jag | 2 +- .../oauth/{util.js => token-handler-utils.js} | 79 ++++++++++--------- .../app/modules/oauth/token-handlers.js | 10 +-- 3 files changed, 47 insertions(+), 44 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/{util.js => token-handler-utils.js} (78%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index 1d04e761af..b8f495aa7c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -28,7 +28,7 @@ var userModule = require("/app/modules/user.js").userModule; var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; -var util = require("/app/modules/oauth/util.js").util; +var util = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var responseProcessor = require('utils').response; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js similarity index 78% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js index 3776857960..1ed0291e37 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/util.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -16,19 +16,19 @@ * under the License. */ -var util = function () { - var log = new Log("/app/modules/oauth/util.js"); - - var privateMethods = {}; - var publicMethods = {}; - - var Base64 = Packages.org.apache.commons.codec.binary.Base64; - var String = Packages.java.lang.String; +var utils = function () { + var log = new Log("/app/modules/oauth/token-handler-utils.js"); var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var carbon = require("carbon"); + var Base64 = Packages.org.apache.commons.codec.binary.Base64; + var String = Packages.java.lang.String; + + var publicMethods = {}; + var privateMethods = {}; + publicMethods.encode = function (payload) { return new String(Base64.encodeBase64(new String(payload).getBytes())); }; @@ -64,11 +64,11 @@ var util = function () { dynamicClientAppCredentials["clientId"] = responsePayload["client_id"]; dynamicClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; } else if (xhr["status"] == 400) { - log.error("{/app/modules/oauth/util.js - getDynamicClientAppCredentials()} " + + log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + "Bad request. Invalid data provided as dynamic client application properties."); dynamicClientAppCredentials = null; } else { - log.error("{/app/modules/oauth/util.js - getDynamicClientAppCredentials()} " + + log.error("{/app/modules/oauth/token-handler-utils.js - getDynamicClientAppCredentials()} " + "Error in retrieving dynamic client credentials."); dynamicClientAppCredentials = null; } @@ -76,11 +76,11 @@ var util = function () { return dynamicClientAppCredentials; }; - publicMethods.getAccessTokenByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) { + publicMethods.getTokenPairByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) { if (!username || !password || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + "grant type. No username, password, encoded client app credentials or scopes are " + - "found - getAccessTokenByPasswordGrantType(a, b, c, d)"); + "found - getTokenPairByPasswordGrantType(a, b, c, d)"); return null; } else { // calling oauth provider token service endpoint @@ -101,18 +101,18 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + - "grant type - getAccessTokenByPasswordGrantType(a, b, c, d)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " + + "by password grant type - getTokenPairByPasswordGrantType(a, b, c, d)"); return null; } } }; - publicMethods.getAccessTokenBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) { + publicMethods.getTokenPairBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) { if (!assertion || !encodedClientAppCredentials || !scopes) { - log.error("{/app/modules/oauth/util.js} Error in retrieving access token by saml " + + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + "grant type. No assertion, encoded client app credentials or scopes are " + - "found - getAccessTokenBySAMLGrantType(x, y, z)"); + "found - getTokenPairBySAMLGrantType(x, y, z)"); return null; } else { var assertionXML = publicMethods.decode(assertion); @@ -127,8 +127,8 @@ var util = function () { var extractedAssertion; if (assertionStartIndex == -1 || assertionEndIndex == -1) { - log.error("{/app/modules/oauth/util.js} Error in retrieving access token by saml grant type. " + - "Issue in assertion format - getAccessTokenBySAMLGrantType(x, y, z)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access " + + "token by saml grant type. Issue in assertion format - getTokenPairBySAMLGrantType(x, y, z)"); return null; } else { extractedAssertion = assertionXML. @@ -153,19 +153,19 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/oauth/util.js} Error in retrieving access token by password " + - "grant type - getAccessTokenBySAMLGrantType(x, y, z)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " + + "by password grant type - getTokenPairBySAMLGrantType(x, y, z)"); return null; } } } }; - publicMethods.getNewAccessTokenByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) { + publicMethods.getNewTokenPairByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) { if (!refreshToken || !encodedClientAppCredentials) { - log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by current " + - "refresh token. No refresh token or encoded client app credentials are " + - "found - getNewAccessTokenByRefreshToken(x, y, z)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " + + "by current refresh token. No refresh token or encoded client app credentials are " + + "found - getNewTokenPairByRefreshToken(x, y, z)"); return null; } else { var requestURL = deviceMgtProps["oauthProvider"]["tokenServiceURL"]; @@ -187,8 +187,8 @@ var util = function () { tokenPair["refreshToken"] = responsePayload["refresh_token"]; return tokenPair; } else { - log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by " + - "current refresh token - getNewAccessTokenByRefreshToken(x, y, z)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token by " + + "current refresh token - getNewTokenPairByRefreshToken(x, y, z)"); return null; } } @@ -196,8 +196,9 @@ var util = function () { publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) { if (!clientAppCredentials) { - log.error("{/app/modules/oauth/util.js} Error in retrieving new access token by current refresh token. " + - "No client app credentials are found as input - getAccessTokenByJWTGrantType(x)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " + + "by current refresh token. No client app credentials are found " + + "as input - getAccessTokenByJWTGrantType(x)"); return null; } else { var JWTClientManagerServicePackagePath = @@ -212,15 +213,16 @@ var util = function () { publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) { if (!username || !jwtToken) { - log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client app " + - "credentials. No username or jwt token is found as input - getTenantBasedClientAppCredentials(x, y)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client app credentials. No username or jwt token is found " + + "as input - getTenantBasedClientAppCredentials(x, y)"); return null; } else { var tenantDomain = carbon.server.tenantDomain({username: username}); if (!tenantDomain) { - log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client application " + - "credentials. Unable to obtain a valid tenant domain for provided " + - "username - getTenantBasedClientAppCredentials(x, y)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials. Unable to obtain a valid tenant domain for provided " + + "username - getTenantBasedClientAppCredentials(x, y)"); return null; } else { var cachedTenantBasedClientAppCredentials = privateMethods. @@ -232,7 +234,7 @@ var util = function () { var applicationName = "webapp_" + tenantDomain; var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] ["apiManagerClientAppRegistrationServiceURL"] + - "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; + "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; var xhr = new XMLHttpRequest(); xhr.open("POST", requestURL, false); @@ -249,8 +251,9 @@ var util = function () { setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); return tenantBasedClientAppCredentials; } else { - log.error("{/app/modules/oauth/util.js} Error in retrieving tenant based client " + - "application credentials from API Manager - getTenantBasedClientAppCredentials(x, y)"); + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials from API " + + "Manager - getTenantBasedClientAppCredentials(x, y)"); return null; } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 867c1db8da..64b0c1894a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -25,7 +25,7 @@ var handlers = function () { var log = new Log("/app/modules/oauth/token-handlers.js"); - var tokenUtil = require("/app/modules/oauth/util.js")["util"]; + var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; @@ -53,8 +53,8 @@ var handlers = function () { stringOfScopes += entry + " "; }); tokenPair = tokenUtil. - getAccessTokenByPasswordGrantType(username, - encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes); + getTokenPairByPasswordGrantType(username, + encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes); if (!tokenPair) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " + "token pair by password grant type. Error in token " + @@ -83,7 +83,7 @@ var handlers = function () { var tokenPair; // accessTokenPair will include current access token as well as current refresh token tokenPair = tokenUtil. - getAccessTokenBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION"); + getTokenPairBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION"); if (!tokenPair) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " + "pair by password grant type. Error in token " + @@ -106,7 +106,7 @@ var handlers = function () { "session context - refreshTokenPair()"); } else { var newTokenPair = tokenUtil. - getNewAccessTokenByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials); + getNewTokenPairByRefreshToken(currentTokenPair["refreshToken"], encodedClientAppCredentials); if (!newTokenPair) { log.error("{/app/modules/oauth/token-handlers.js} Error in refreshing token pair. " + "Unable to update session context with new access token pair - refreshTokenPair()"); From 303f16e747b744f8a5f894a21c1cce166f36e63b Mon Sep 17 00:00:00 2001 From: dilanua Date: Sun, 31 Jul 2016 11:15:40 +0530 Subject: [PATCH 26/76] Deprecating obsolete UI functions - device.js --- .../devicemgt/app/modules/device.js | 404 +++++++++--------- 1 file changed, 202 insertions(+), 202 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index 085b9b7ea1..cb640d4537 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -25,18 +25,18 @@ deviceModule = function () { var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; - var ArrayList = Packages.java.util.ArrayList; - var Properties = Packages.java.util.Properties; - var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier; - var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; - var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation; - var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; - var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; +// var ArrayList = Packages.java.util.ArrayList; +// var Properties = Packages.java.util.Properties; +// var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier; +// var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; +// var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation; +// var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; +// var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation; var publicMethods = {}; var privateMethods = {}; - var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; +// var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; privateMethods.validateAndReturn = function (value) { return (value == undefined || value == null) ? constants.UNSPECIFIED : value; @@ -45,57 +45,57 @@ deviceModule = function () { /* @Deprecated */ - publicMethods.listDevices = function () { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var devices = deviceManagementService.getAllDevices(); - var deviceList = []; - var i, device, propertiesList, deviceObject; - for (i = 0; i < devices.size(); i++) { - device = devices.get(i); - propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); - - deviceObject = {}; - deviceObject[constants.DEVICE_IDENTIFIER] = - privateMethods.validateAndReturn(device.getDeviceIdentifier()); - deviceObject[constants.DEVICE_NAME] = - privateMethods.validateAndReturn(device.getName()); - deviceObject[constants.DEVICE_OWNERSHIP] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); - deviceObject[constants.DEVICE_OWNER] = - privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); - deviceObject[constants.DEVICE_TYPE] = - privateMethods.validateAndReturn(device.getType()); - deviceObject[constants.DEVICE_PROPERTIES] = {}; - if (device.getType() == constants.PLATFORM_IOS) { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; - } else { - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); - } - deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = - privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); - - deviceList.push(deviceObject); - } - return deviceList; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; +// publicMethods.listDevices = function () { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var devices = deviceManagementService.getAllDevices(); +// var deviceList = []; +// var i, device, propertiesList, deviceObject; +// for (i = 0; i < devices.size(); i++) { +// device = devices.get(i); +// propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties()); +// +// deviceObject = {}; +// deviceObject[constants.DEVICE_IDENTIFIER] = +// privateMethods.validateAndReturn(device.getDeviceIdentifier()); +// deviceObject[constants.DEVICE_NAME] = +// privateMethods.validateAndReturn(device.getName()); +// deviceObject[constants.DEVICE_OWNERSHIP] = +// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership()); +// deviceObject[constants.DEVICE_OWNER] = +// privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner()); +// deviceObject[constants.DEVICE_TYPE] = +// privateMethods.validateAndReturn(device.getType()); +// deviceObject[constants.DEVICE_PROPERTIES] = {}; +// if (device.getType() == constants.PLATFORM_IOS) { +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT)); +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE; +// } else { +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL)); +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR)); +// } +// deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] = +// privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION)); +// +// deviceList.push(deviceObject); +// } +// return deviceList; +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; /* @Deprecated @@ -103,105 +103,105 @@ deviceModule = function () { /* Get the supported features by the device type */ - publicMethods.getFeatures = function (deviceType) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var features = deviceManagementService.getFeatureManager(deviceType).getFeatures(); - var featuresConverted = {}; - if (features) { - var i, feature, featureObject; - for (i = 0; i < features.size(); i++) { - feature = features.get(i); - featureObject = {}; - featureObject[constants.FEATURE_NAME] = feature.getName(); - featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription(); - featuresConverted[feature.getName()] = featureObject; - } - } - return featuresConverted; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; +// publicMethods.getFeatures = function (deviceType) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var features = deviceManagementService.getFeatureManager(deviceType).getFeatures(); +// var featuresConverted = {}; +// if (features) { +// var i, feature, featureObject; +// for (i = 0; i < features.size(); i++) { +// feature = features.get(i); +// featureObject = {}; +// featureObject[constants.FEATURE_NAME] = feature.getName(); +// featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription(); +// featuresConverted[feature.getName()] = featureObject; +// } +// } +// return featuresConverted; +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; /* @Deprecated */ - publicMethods.performOperation = function (devices, operation) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var operationInstance; - if (operation.type == "COMMAND") { - operationInstance = new CommandOperation(); - } else if (operation.type == "CONFIG") { - operationInstance = new ConfigOperation(); - } else { - operationInstance = new SimpleOperation(); - } - operationInstance.setCode(operation.featureName); - var props = new Properties(); - var i, object; - for (i = 0; i < operation.properties.length; i++) { - object = properties[i]; - props.setProperty(object.key, object.value); - } - operationInstance.setProperties(props); - var deviceList = new ArrayList(); - var j, device, deviceIdentifier; - for (j = 0; j < devices.length; i++) { - device = devices[j]; - deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(device.id); - deviceIdentifier.setType(device.type); - deviceList.add(deviceIdentifier); - } - deviceManagementService.addOperation(operationInstance, deviceList); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; +// publicMethods.performOperation = function (devices, operation) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var operationInstance; +// if (operation.type == "COMMAND") { +// operationInstance = new CommandOperation(); +// } else if (operation.type == "CONFIG") { +// operationInstance = new ConfigOperation(); +// } else { +// operationInstance = new SimpleOperation(); +// } +// operationInstance.setCode(operation.featureName); +// var props = new Properties(); +// var i, object; +// for (i = 0; i < operation.properties.length; i++) { +// object = properties[i]; +// props.setProperty(object.key, object.value); +// } +// operationInstance.setProperties(props); +// var deviceList = new ArrayList(); +// var j, device, deviceIdentifier; +// for (j = 0; j < devices.length; i++) { +// device = devices[j]; +// deviceIdentifier = new DeviceIdentifier(); +// deviceIdentifier.setId(device.id); +// deviceIdentifier.setType(device.type); +// deviceList.add(deviceIdentifier); +// } +// deviceManagementService.addOperation(operationInstance, deviceList); +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; /* @Deprecated */ - privateMethods.getDevice = function (type, deviceId) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var deviceManagementService = utility.getDeviceManagementService(); - var deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setType(type); - deviceIdentifier.setId(deviceId); - return deviceManagementService.getDevice(deviceIdentifier); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; +// privateMethods.getDevice = function (type, deviceId) { +// var carbonUser = session.get(constants.USER_SESSION_KEY); +// var utility = require('/app/modules/utility.js').utility; +// if (!carbonUser) { +// log.error("User object was not found in the session"); +// throw constants.ERRORS.USER_NOT_FOUND; +// } +// try { +// utility.startTenantFlow(carbonUser); +// var deviceManagementService = utility.getDeviceManagementService(); +// var deviceIdentifier = new DeviceIdentifier(); +// deviceIdentifier.setType(type); +// deviceIdentifier.setId(deviceId); +// return deviceManagementService.getDevice(deviceIdentifier); +// } catch (e) { +// throw e; +// } finally { +// utility.endTenantFlow(); +// } +// }; /* @Updated @@ -218,37 +218,37 @@ deviceModule = function () { var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/view?type=" + deviceType + "&id=" + deviceId; return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - var device = responsePayload.responseContent; - if (device) { - var propertiesList = device["properties"]; - var properties = {}; - if (propertiesList){ - for (var i = 0; i < propertiesList.length; i++) { - properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; - } + url, function (responsePayload) { + var device = responsePayload.responseContent; + if (device) { + var propertiesList = device["properties"]; + var properties = {}; + if (propertiesList){ + for (var i = 0; i < propertiesList.length; i++) { + properties[propertiesList[i]["name"]] = propertiesList[i]["value"]; } - var deviceObject = {}; - deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; - deviceObject[constants["DEVICE_NAME"]] = device["name"]; - deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; - deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; - deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; - deviceObject[constants["DEVICE_TYPE"]] = device["type"]; - if (device["type"] == constants["PLATFORM_IOS"]) { - properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; - delete properties[constants["DEVICE_PRODUCT"]]; - properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; - } - deviceObject[constants["DEVICE_PROPERTIES"]] = properties; - return deviceObject; } - }, - function (responsePayload) { - var response = {}; - response["status"] = "error"; - return response; + var deviceObject = {}; + deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"]; + deviceObject[constants["DEVICE_NAME"]] = device["name"]; + deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"]; + deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"]; + deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"]; + deviceObject[constants["DEVICE_TYPE"]] = device["type"]; + if (device["type"] == constants["PLATFORM_IOS"]) { + properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]]; + delete properties[constants["DEVICE_PRODUCT"]]; + properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"]; + } + deviceObject[constants["DEVICE_PROPERTIES"]] = properties; + return deviceObject; } + }, + function (responsePayload) { + var response = {}; + response["status"] = "error"; + return response; + } ); } catch (e) { throw e; @@ -268,19 +268,19 @@ deviceModule = function () { url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/count"; } else if (uiPermissions.LIST_OWN_DEVICES) { url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + carbonUser.username - + "/count"; + + "/count"; } else { log.error("Access denied for user: " + carbonUser.username); return -1; } return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - return responsePayload; - }, - function (responsePayload) { - log.error(responsePayload); - return -1; - } + url, function (responsePayload) { + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } ); } else { log.error("User object was not found in the session"); @@ -291,13 +291,13 @@ deviceModule = function () { publicMethods.getDeviceTypes = function () { var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/types"; return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - return responsePayload; - }, - function (responsePayload) { - log.error(responsePayload); - return -1; - } + url, function (responsePayload) { + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } ); }; @@ -328,16 +328,16 @@ deviceModule = function () { publicMethods.getDevices = function (userName) { var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/devices/user/" + userName; return serviceInvokers.XMLHttp.get( - url, function (responsePayload) { - for (var i = 0; i < responsePayload.length; i++) { - responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type); - } - return responsePayload; - }, - function (responsePayload) { - log.error(responsePayload); - return -1; + url, function (responsePayload) { + for (var i = 0; i < responsePayload.length; i++) { + responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type); } + return responsePayload; + }, + function (responsePayload) { + log.error(responsePayload); + return -1; + } ); }; return publicMethods; From bbff93adcc13599b1a406c82392aa355f1f1e5e4 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 1 Aug 2016 18:50:47 +0530 Subject: [PATCH 27/76] Updating token-handler-utils with suppressed warnings for java packg imports --- .../app/modules/oauth/token-handler-utils.js | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js index 1ed0291e37..dc2655233f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -19,22 +19,26 @@ var utils = function () { var log = new Log("/app/modules/oauth/token-handler-utils.js"); - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var carbon = require("carbon"); + //noinspection JSUnresolvedVariable var Base64 = Packages.org.apache.commons.codec.binary.Base64; + //noinspection JSUnresolvedVariable var String = Packages.java.lang.String; var publicMethods = {}; var privateMethods = {}; publicMethods.encode = function (payload) { - return new String(Base64.encodeBase64(new String(payload).getBytes())); + //noinspection JSUnresolvedFunction + return String(Base64.encodeBase64(String(payload).getBytes())); }; publicMethods.decode = function (payload) { - return new String(Base64.decodeBase64(new String(payload).getBytes())); + //noinspection JSUnresolvedFunction + return String(Base64.decodeBase64(String(payload).getBytes())); }; publicMethods.getDynamicClientAppCredentials = function () { @@ -117,8 +121,8 @@ var utils = function () { } else { var assertionXML = publicMethods.decode(assertion); /* - TODO: make assertion extraction with proper parsing. Since Jaggery XML parser seem - to add formatting which causes signature verification to fail. + TODO: make assertion extraction with proper parsing. + Since Jaggery XML parser seem to add formatting which causes signature verification to fail. */ var assertionStartMarker = " Date: Mon, 1 Aug 2016 19:06:04 +0530 Subject: [PATCH 28/76] Adding conf-reader to UI modules --- .../jaggeryapps/devicemgt/api/data-tables-invoker-api.jag | 2 +- .../resources/jaggeryapps/devicemgt/api/device-api.jag | 2 +- .../resources/jaggeryapps/devicemgt/api/group-api.jag | 2 +- .../resources/jaggeryapps/devicemgt/api/invoker-api.jag | 2 +- .../resources/jaggeryapps/devicemgt/api/operation-api.jag | 2 +- .../main/resources/jaggeryapps/devicemgt/api/user-api.jag | 2 +- .../app/{conf/reader => modules/conf-reader}/main.js | 8 +++++--- .../app/{conf/reader => modules/conf-reader}/pinch.min.js | 0 .../resources/jaggeryapps/devicemgt/app/modules/device.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/group.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/init.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/login.js | 2 +- .../devicemgt/app/modules/oauth/token-handlers.js | 2 +- .../app/modules/oauth/token-protected-service-invokers.js | 2 +- .../jaggeryapps/devicemgt/app/modules/operation.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/policy.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/user.js | 2 +- .../jaggeryapps/devicemgt/app/modules/utility.js | 2 +- .../devicemgt/app/pages/cdmf.page.dashboard/dashboard.js | 2 +- .../devicemgt/app/pages/cdmf.page.group.create/create.js | 2 +- .../devicemgt/app/pages/cdmf.page.user.create/create.js | 2 +- .../devicemgt/app/pages/cdmf.page.user.edit/edit.js | 2 +- .../devicemgt/app/pages/cdmf.page.users/users.js | 2 +- .../app/units/cdmf.unit.device.type.view/view.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.create/create.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.edit/edit.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.listing/listing.js | 2 +- .../app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js | 2 +- 28 files changed, 31 insertions(+), 29 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/{conf/reader => modules/conf-reader}/main.js (85%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/{conf/reader => modules/conf-reader}/pinch.min.js (100%) 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 6777383200..ce0dbd1d41 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag @@ -22,7 +22,7 @@ var log = new Log("api/data-tables-invoker-api.jag"); var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; function appendQueryParam (url, queryParam , value) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 74ba1290d4..937d396885 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -24,7 +24,7 @@ var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag index cfce1f0409..2ba4ebba9e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/group-api.jag @@ -23,7 +23,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js").utility; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag index 741bf1ed53..3e410ee2c5 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/invoker-api.jag @@ -23,7 +23,7 @@ var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var constants = require("/app/modules/constants.js"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; if (uriMatcher.match("/{context}/api/invoker/execute/")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag index 99fa61a9f9..c6dca89321 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/operation-api.jag @@ -23,7 +23,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/operation-api.jag"); var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (uriMatcher.match("/{context}/api/operation/paginate")) { var deviceType = request.getParameter("deviceType"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index b8f495aa7c..3c11d19fde 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -23,7 +23,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/user-api.jag"); var constants = require("/app/modules/constants.js"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var userModule = require("/app/modules/user.js").userModule; var deviceModule = require("/app/modules/device.js").deviceModule; var utility = require("/app/modules/utility.js").utility; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js similarity index 85% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js index ec5b6642f2..f81849fe3b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/main.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js @@ -17,16 +17,18 @@ */ var conf = function () { - var conf = application.get("UI_CONF"); + var conf = application.get("CONF"); if (!conf) { conf = require("/app/conf/config.json"); - var pinch = require("/app/conf/reader/pinch.min.js")["pinch"]; + var pinch = require("/app/modules/conf-reader/pinch.min.js")["pinch"]; var server = require("carbon")["server"]; pinch(conf, /^/, function (path, key, value) { if ((typeof value === "string") && value.indexOf("%https.ip%") > -1) { + //noinspection JSUnresolvedFunction return value.replace("%https.ip%", server.address("https")); } else if ((typeof value === "string") && value.indexOf("%http.ip%") > -1) { + //noinspection JSUnresolvedFunction return value.replace("%http.ip%", server.address("http")); } else if ((typeof value === "string") && value.indexOf("%date-year%") > -1) { var year = new Date().getFullYear(); @@ -35,7 +37,7 @@ var conf = function () { return value; } ); - application.put("UI_CONF", conf); + application.put("CONF", conf); } return conf; }(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/pinch.min.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/pinch.min.js similarity index 100% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/reader/pinch.min.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/pinch.min.js diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js index cb640d4537..071154584d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js @@ -22,7 +22,7 @@ deviceModule = function () { var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; // var ArrayList = Packages.java.util.ArrayList; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js index 549d0d8787..c2567cec29 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js @@ -22,7 +22,7 @@ var groupModule = {}; var userModule = require("/app/modules/user.js").userModule; var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var utility = require("/app/modules/utility.js").utility; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index 35c902dbab..8e86f44ab8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -17,7 +17,7 @@ */ var carbonModule = require("carbon"); -var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; +var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var carbonServer = new carbonModule.server.Server({ tenanted: true, url: devicemgtProps["httpsURL"] + "/admin" diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js index c383e1e817..87f840d3ce 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/login.js @@ -30,7 +30,7 @@ var onFail; } else { apiWrapperUtil.setupTokenPairByPasswordGrantType(context.input.username, context.input.password); } - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var carbonServer = require("carbon").server; (new carbonServer.Server({url: devicemgtProps["adminService"]})) .login(context.input.username, context.input.password); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 64b0c1894a..4943a2d823 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -27,7 +27,7 @@ var handlers = function () { var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"]; var constants = require("/app/modules/constants.js"); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var publicMethods = {}; var privateMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index 2b9a3d09c9..d94ea02f48 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -35,7 +35,7 @@ var invokers = function () { var TOKEN_EXPIRED = "Access token expired"; var TOKEN_INVALID = "Invalid input. Access token validation failed"; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var userModule = require("/app/modules/user.js")["userModule"]; var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js index 98890b9a19..9f75d4eb17 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js @@ -20,7 +20,7 @@ var operationModule = function () { var log = new Log("/app/modules/operation.js"); var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js index 0fbe5a2116..998e6722d1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js @@ -25,7 +25,7 @@ policyModule = function () { var constants = require('/app/modules/constants.js'); var utility = require("/app/modules/utility.js")["utility"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var publicMethods = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js index 2a28f5fddf..29a7de7365 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js @@ -24,7 +24,7 @@ var userModule = function () { var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js")["utility"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; /* Initializing user manager */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js index b63edc3a2a..f5dd896bc4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js @@ -20,7 +20,7 @@ var utility; utility = function () { var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var log = new Log("/app/modules/utility.js"); var JavaClass = Packages.java.lang.Class; var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js index a3b0875812..8681882f2e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js @@ -21,7 +21,7 @@ function onRequest(context) { var user = session.get(constants.USER_SESSION_KEY); var userModule = require("/app/modules/user.js").userModule; var permissions = userModule.getUIPermissions(); - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (!permissions.VIEW_DASHBOARD) { response.sendRedirect(constants.WEB_APP_CONTEXT + "/devices"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js index ebfda4568b..350d245d1f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.create/create.js @@ -23,7 +23,7 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var page = {}; page["groupNameJSRegEx"] = devicemgtProps.groupValidationConfig.groupNameJSRegEx; page["groupNameRegExViolationErrorMsg"] = devicemgtProps.groupValidationConfig.groupNameRegExViolationErrorMsg; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js index 70e9089a5f..cbd0564b15 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js @@ -26,7 +26,7 @@ function onRequest(context) { //var log = new Log("/app/pages/cdmf.page.user.create server-side js"); var userModule = require("/app/modules/user.js")["userModule"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var page = {}; var response = userModule.getRolesByUserStore(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js index 8f94c2902b..7037721ad9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js @@ -20,7 +20,7 @@ function onRequest(context) { var userModule = require("/app/modules/user.js").userModule; var userName = request.getParameter("username"); var user = userModule.getUser(userName)["content"]; - var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; if (user) { var title; if (user.firstname || user.lastname) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js index 98ddb20716..df93724633 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 @@ -29,7 +29,7 @@ function onRequest(context) { var page = {}; var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; page["adminUser"] = deviceMgtProps["adminUser"]; page["permissions"] = userModule.getUIPermissions(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js index 9cf038f561..f003d47581 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js @@ -30,7 +30,7 @@ function onRequest (context) { var userModule = require("/app/modules/user.js").userModule; var constants = require("/app/modules/constants.js"); var permissions = userModule.getUIPermissions(); - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; context.permissions = permissions; context["enrollmentURL"] = deviceMgtProps.enrollmentURL; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js index db293c3bf6..9e00dc32aa 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js @@ -24,7 +24,7 @@ */ function onRequest(context) { var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var response = userModule.getRoles(); if (response["status"] == "success") { context["roles"] = response["content"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js index 5e24261bd2..01a08da69f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js @@ -24,7 +24,7 @@ */ function onRequest(context) { var userModule = require("/app/modules/user.js")["userModule"]; - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var isMatched = uriMatcher.match("/{context}/role/edit/{rolename}"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js index 681883aae3..c5c67d1029 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js @@ -30,7 +30,7 @@ function onRequest(context) { if (userModule.isAuthorized("/permission/admin/device-mgt/roles/remove")) { context["removePermitted"] = true; } - var deviceMgtProps = require("/app/conf/reader/main.js")["conf"]; + var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; context["appContext"] = deviceMgtProps.appContext; context["adminRole"] = deviceMgtProps.adminRole; return context; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js index 89213cf587..3f4ede1774 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js @@ -28,7 +28,7 @@ function onRequest(context) { } }); var userModule = require("/app/modules/user.js")["userModule"]; - var mdmProps = require('/app/conf/reader/main.js')["conf"]; + var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var uiPermissions = userModule.getUIPermissions(); context["permissions"] = uiPermissions; From 89cebcdb9e68139a5d23d33b7b9ec816e5578148 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 1 Aug 2016 19:28:05 +0530 Subject: [PATCH 29/76] Updating UI oauth module with suppressed warnings for verified, but unresolved variables and functions --- .../app/modules/oauth/token-handler-utils.js | 158 +++++++++--------- .../app/modules/oauth/token-handlers.js | 8 +- .../oauth/token-protected-service-invokers.js | 54 ++++-- 3 files changed, 120 insertions(+), 100 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js index dc2655233f..180438518f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js @@ -31,17 +31,17 @@ var utils = function () { var publicMethods = {}; var privateMethods = {}; - publicMethods.encode = function (payload) { + publicMethods["encode"] = function (payload) { //noinspection JSUnresolvedFunction return String(Base64.encodeBase64(String(payload).getBytes())); }; - publicMethods.decode = function (payload) { + publicMethods["decode"] = function (payload) { //noinspection JSUnresolvedFunction return String(Base64.decodeBase64(String(payload).getBytes())); }; - publicMethods.getDynamicClientAppCredentials = function () { + publicMethods["getDynamicClientAppCredentials"] = function () { // setting up dynamic client application properties var dcAppProperties = { "applicationType": deviceMgtProps["oauthProvider"]["appRegistration"]["appType"], @@ -80,7 +80,79 @@ var utils = function () { return dynamicClientAppCredentials; }; - publicMethods.getTokenPairByPasswordGrantType = function (username, password, encodedClientAppCredentials, scopes) { + publicMethods["getTenantBasedClientAppCredentials"] = function (username, jwtToken) { + if (!username || !jwtToken) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client app credentials. No username or jwt token is found " + + "as input - getTenantBasedClientAppCredentials(x, y)"); + return null; + } else { + //noinspection JSUnresolvedFunction, JSUnresolvedVariable + var tenantDomain = carbon.server.tenantDomain({username: username}); + if (!tenantDomain) { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials. Unable to obtain a valid tenant domain for provided " + + "username - getTenantBasedClientAppCredentials(x, y)"); + return null; + } else { + var cachedTenantBasedClientAppCredentials = privateMethods. + getCachedTenantBasedClientAppCredentials(tenantDomain); + if (cachedTenantBasedClientAppCredentials) { + return cachedTenantBasedClientAppCredentials; + } else { + // register a tenant based client app at API Manager + var applicationName = "webapp_" + tenantDomain; + var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] + ["apiManagerClientAppRegistrationServiceURL"] + + "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; + + var xhr = new XMLHttpRequest(); + xhr.open("POST", requestURL, false); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.setRequestHeader("Authorization", "Bearer " + jwtToken); + xhr.send(); + + if (xhr["status"] == 201 && xhr["responseText"]) { + var responsePayload = parse(xhr["responseText"]); + var tenantBasedClientAppCredentials = {}; + tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"]; + tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; + privateMethods. + setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); + return tenantBasedClientAppCredentials; + } else { + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + + "based client application credentials from API " + + "Manager - getTenantBasedClientAppCredentials(x, y)"); + return null; + } + } + } + } + }; + + privateMethods["setCachedTenantBasedClientAppCredentials"] = function (tenantDomain, clientAppCredentials) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); + if (!cachedTenantBasedClientAppCredentialsMap) { + cachedTenantBasedClientAppCredentialsMap = {}; + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap); + } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; + } + }; + + privateMethods["getCachedTenantBasedClientAppCredentials"] = function (tenantDomain) { + var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); + if (!cachedTenantBasedClientAppCredentialsMap || + !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { + return null; + } else { + return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; + } + }; + + publicMethods["getTokenPairByPasswordGrantType"] = function (username, password, encodedClientAppCredentials, scopes) { if (!username || !password || !encodedClientAppCredentials || !scopes) { log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by password " + "grant type. No username, password, encoded client app credentials or scopes are " + @@ -112,7 +184,7 @@ var utils = function () { } }; - publicMethods.getTokenPairBySAMLGrantType = function (assertion, encodedClientAppCredentials, scopes) { + publicMethods["getTokenPairBySAMLGrantType"] = function (assertion, encodedClientAppCredentials, scopes) { if (!assertion || !encodedClientAppCredentials || !scopes) { log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token by saml " + "grant type. No assertion, encoded client app credentials or scopes are " + @@ -165,7 +237,7 @@ var utils = function () { } }; - publicMethods.getNewTokenPairByRefreshToken = function (refreshToken, encodedClientAppCredentials, scopes) { + publicMethods["getNewTokenPairByRefreshToken"] = function (refreshToken, encodedClientAppCredentials, scopes) { if (!refreshToken || !encodedClientAppCredentials) { log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " + "by current refresh token. No refresh token or encoded client app credentials are " + @@ -198,7 +270,7 @@ var utils = function () { } }; - publicMethods.getAccessTokenByJWTGrantType = function (clientAppCredentials) { + publicMethods["getAccessTokenByJWTGrantType"] = function (clientAppCredentials) { if (!clientAppCredentials) { log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new access token " + "by current refresh token. No client app credentials are found " + @@ -217,77 +289,5 @@ var utils = function () { } }; - publicMethods.getTenantBasedClientAppCredentials = function (username, jwtToken) { - if (!username || !jwtToken) { - log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client app credentials. No username or jwt token is found " + - "as input - getTenantBasedClientAppCredentials(x, y)"); - return null; - } else { - //noinspection JSUnresolvedFunction, JSUnresolvedVariable - var tenantDomain = carbon.server.tenantDomain({username: username}); - if (!tenantDomain) { - log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials. Unable to obtain a valid tenant domain for provided " + - "username - getTenantBasedClientAppCredentials(x, y)"); - return null; - } else { - var cachedTenantBasedClientAppCredentials = privateMethods. - getCachedTenantBasedClientAppCredentials(tenantDomain); - if (cachedTenantBasedClientAppCredentials) { - return cachedTenantBasedClientAppCredentials; - } else { - // register a tenant based client app at API Manager - var applicationName = "webapp_" + tenantDomain; - var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] - ["apiManagerClientAppRegistrationServiceURL"] + - "?tenantDomain=" + tenantDomain + "&applicationName=" + applicationName; - - var xhr = new XMLHttpRequest(); - xhr.open("POST", requestURL, false); - xhr.setRequestHeader("Content-Type", "application/json"); - xhr.setRequestHeader("Authorization", "Bearer " + jwtToken); - xhr.send(); - - if (xhr["status"] == 201 && xhr["responseText"]) { - var responsePayload = parse(xhr["responseText"]); - var tenantBasedClientAppCredentials = {}; - tenantBasedClientAppCredentials["clientId"] = responsePayload["client_id"]; - tenantBasedClientAppCredentials["clientSecret"] = responsePayload["client_secret"]; - privateMethods. - setCachedTenantBasedClientAppCredentials(tenantDomain, tenantBasedClientAppCredentials); - return tenantBasedClientAppCredentials; - } else { - log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + - "based client application credentials from API " + - "Manager - getTenantBasedClientAppCredentials(x, y)"); - return null; - } - } - } - } - }; - - privateMethods.setCachedTenantBasedClientAppCredentials = function (tenantDomain, clientAppCredentials) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); - if (!cachedTenantBasedClientAppCredentialsMap) { - cachedTenantBasedClientAppCredentialsMap = {}; - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - application.put(constants["CACHED_CREDENTIALS"], cachedTenantBasedClientAppCredentialsMap); - } else if (!cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - cachedTenantBasedClientAppCredentialsMap[tenantDomain] = clientAppCredentials; - } - }; - - privateMethods.getCachedTenantBasedClientAppCredentials = function (tenantDomain) { - var cachedTenantBasedClientAppCredentialsMap = application.get(constants["CACHED_CREDENTIALS"]); - if (!cachedTenantBasedClientAppCredentialsMap || - !cachedTenantBasedClientAppCredentialsMap[tenantDomain]) { - return null; - } else { - return cachedTenantBasedClientAppCredentialsMap[tenantDomain]; - } - }; - return publicMethods; }(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js index 4943a2d823..af8a7e6674 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js @@ -32,7 +32,7 @@ var handlers = function () { var publicMethods = {}; var privateMethods = {}; - publicMethods.setupTokenPairByPasswordGrantType = function (username, password) { + publicMethods["setupTokenPairByPasswordGrantType"] = function (username, password) { if (!username || !password) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + "password grant type. Either username of logged in user, password or both are missing " + @@ -67,7 +67,7 @@ var handlers = function () { } }; - publicMethods.setupTokenPairBySamlGrantType = function (username, samlToken) { + publicMethods["setupTokenPairBySamlGrantType"] = function (username, samlToken) { if (!username || !samlToken) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up access token pair by " + "saml grant type. Either username of logged in user, samlToken or both are missing " + @@ -96,7 +96,7 @@ var handlers = function () { } }; - publicMethods.refreshTokenPair = function () { + publicMethods["refreshTokenPair"] = function () { var currentTokenPair = parse(session.get(constants["TOKEN_PAIR"])); // currentTokenPair includes current access token as well as current refresh token var encodedClientAppCredentials = session.get(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"]); @@ -116,7 +116,7 @@ var handlers = function () { } }; - privateMethods.setUpEncodedTenantBasedClientAppCredentials = function (username) { + privateMethods["setUpEncodedTenantBasedClientAppCredentials"] = function (username) { if (!username) { throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + "client credentials to session context. No username of logged in user is found as " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index d94ea02f48..9c217a52dd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -67,7 +67,7 @@ var invokers = function () { * @param responseCallback a function to be called with response retrieved. * @param count a counter which hold the number of recursive execution */ - privateMethods.execute = function (httpMethod, requestPayload, endpoint, responseCallback, count) { + privateMethods["execute"] = function (httpMethod, requestPayload, endpoint, responseCallback, count) { var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.open(httpMethod, endpoint); @@ -81,8 +81,8 @@ var invokers = function () { response.sendRedirect(devicemgtProps["appContext"] + "login"); }); } else { - xmlHttpRequest. - setRequestHeader(constants["AUTHORIZATION_HEADER"], constants["BEARER_PREFIX"] + accessToken); + xmlHttpRequest.setRequestHeader(constants["AUTHORIZATION_HEADER"], + constants["BEARER_PREFIX"] + accessToken); } } @@ -99,7 +99,6 @@ var invokers = function () { log.info("Request payload if any : " + stringify(requestPayload)); log.info("Response status : " + xmlHttpRequest.status); log.info("Response payload if any : " + xmlHttpRequest.responseText); - //log.info("Response headers : " + xmlHttpRequest.getAllResponseHeaders()); if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { @@ -117,7 +116,7 @@ var invokers = function () { * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ - privateMethods.initiateXMLHTTPRequest = function (httpMethod, requestPayload, endpoint, responseCallback) { + privateMethods["initiateXMLHTTPRequest"] = function (httpMethod, requestPayload, endpoint, responseCallback) { return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0); }; @@ -126,7 +125,7 @@ var invokers = function () { * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ - publicXMLHTTPInvokers.get = function (endpoint, responseCallback) { + publicXMLHTTPInvokers["get"] = function (endpoint, responseCallback) { var requestPayload = null; return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback); }; @@ -137,7 +136,7 @@ var invokers = function () { * @param requestPayload payload/data if exists which is needed to be send. * @param responseCallback a function to be called with response retrieved. */ - publicXMLHTTPInvokers.post = function (endpoint, requestPayload, responseCallback) { + publicXMLHTTPInvokers["post"] = function (endpoint, requestPayload, responseCallback) { return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback); }; @@ -147,7 +146,7 @@ var invokers = function () { * @param requestPayload payload/data if exists which is needed to be send. * @param responseCallback a function to be called with response retrieved. */ - publicXMLHTTPInvokers.put = function (endpoint, requestPayload, responseCallback) { + publicXMLHTTPInvokers["put"] = function (endpoint, requestPayload, responseCallback) { return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback); }; @@ -156,7 +155,7 @@ var invokers = function () { * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ - publicXMLHTTPInvokers.delete = function (endpoint, responseCallback) { + publicXMLHTTPInvokers["delete"] = function (endpoint, responseCallback) { var requestPayload = null; return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, responseCallback); }; @@ -176,8 +175,10 @@ var invokers = function () { * @param errorCallback a function to be called if en error is reserved. * @param soapVersion soapVersion which need to used. */ - privateMethods.initiateWSRequest = function (action, endpoint, successCallback, errorCallback, soapVersion, payload) { + privateMethods["initiateWSRequest"] = function (action, endpoint, successCallback, + errorCallback, soapVersion, payload) { var ws = require("ws"); + //noinspection JSUnresolvedFunction var wsRequest = new ws.WSRequest(); var options = []; if (devicemgtProps["isOAuthEnabled"]) { @@ -222,8 +223,10 @@ var invokers = function () { * @param errorCallback a function to be called if en error is reserved. * @param soapVersion soapVersion which need to used. */ - publicWSInvokers.soapRequest = function (action, requestPayload, endpoint, successCallback, errorCallback, soapVersion) { - return privateMethods.initiateWSRequest(action, endpoint, successCallback, errorCallback, soapVersion, requestPayload); + publicWSInvokers["soapRequest"] = function (action, requestPayload, endpoint, + successCallback, errorCallback, soapVersion) { + return privateMethods.initiateWSRequest(action, endpoint, successCallback, + errorCallback, soapVersion, requestPayload); }; /** @@ -240,37 +243,46 @@ var invokers = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - privateMethods.initiateHTTPClientRequest = function (method, url, successCallback, errorCallback, payload) { + privateMethods["initiateHTTPClientRequest"] = function (method, url, successCallback, errorCallback, payload) { + //noinspection JSUnresolvedVariable var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; var httpMethodObject; switch (method) { case constants["HTTP_GET"]: + //noinspection JSUnresolvedVariable var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod; httpMethodObject = new GetMethod(url); break; case constants["HTTP_POST"]: + //noinspection JSUnresolvedVariable var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod; httpMethodObject = new PostMethod(url); break; case constants["HTTP_PUT"]: + //noinspection JSUnresolvedVariable var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod; httpMethodObject = new PutMethod(url); break; case constants["HTTP_DELETE"]: + //noinspection JSUnresolvedVariable var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod; httpMethodObject = new DeleteMethod(url); break; default: + //noinspection JSUnresolvedFunction throw new IllegalArgumentException("Invalid HTTP request method: " + method); } + //noinspection JSUnresolvedVariable var Header = Packages.org.apache.commons.httpclient.Header; var header = new Header(); header.setName(constants["CONTENT_TYPE_IDENTIFIER"]); header.setValue(constants["APPLICATION_JSON"]); + //noinspection JSUnresolvedFunction httpMethodObject.addRequestHeader(header); header = new Header(); header.setName(constants["ACCEPT_IDENTIFIER"]); header.setValue(constants["APPLICATION_JSON"]); + //noinspection JSUnresolvedFunction httpMethodObject.addRequestHeader(header); if (devicemgtProps["isOAuthEnabled"]) { @@ -279,25 +291,33 @@ var invokers = function () { header = new Header(); header.setName(constants["AUTHORIZATION_HEADER"]); header.setValue(constants["BEARER_PREFIX"] + accessToken); + //noinspection JSUnresolvedFunction httpMethodObject.addRequestHeader(header); } else { response.sendRedirect(devicemgtProps["appContext"] + "login"); } } + //noinspection JSUnresolvedFunction var stringRequestEntity = new StringRequestEntity(stringify(payload)); + //noinspection JSUnresolvedFunction httpMethodObject.setRequestEntity(stringRequestEntity); var client = new HttpClient(); try { + //noinspection JSUnresolvedFunction client.executeMethod(httpMethodObject); + //noinspection JSUnresolvedFunction var status = httpMethodObject.getStatusCode(); if (status == 200) { + //noinspection JSUnresolvedFunction return successCallback(httpMethodObject.getResponseBody()); } else { + //noinspection JSUnresolvedFunction return errorCallback(httpMethodObject.getResponseBody()); } } catch (e) { return errorCallback(response); } finally { + //noinspection JSUnresolvedFunction method.releaseConnection(); } }; @@ -308,7 +328,7 @@ var invokers = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.get = function (url, successCallback, errorCallback) { + publicHTTPClientInvokers["get"] = function (url, successCallback, errorCallback) { var requestPayload = null; return privateMethods. initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload); @@ -321,7 +341,7 @@ var invokers = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.post = function (url, payload, successCallback, errorCallback) { + publicHTTPClientInvokers["post"] = function (url, payload, successCallback, errorCallback) { return privateMethods. initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, payload); }; @@ -333,7 +353,7 @@ var invokers = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.put = function (url, payload, successCallback, errorCallback) { + publicHTTPClientInvokers["put"] = function (url, payload, successCallback, errorCallback) { return privateMethods. initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, payload); }; @@ -344,7 +364,7 @@ var invokers = function () { * @param successCallback a function to be called if the respond if successful. * @param errorCallback a function to be called if en error is reserved. */ - publicHTTPClientInvokers.delete = function (url, successCallback, errorCallback) { + publicHTTPClientInvokers["delete"] = function (url, successCallback, errorCallback) { var requestPayload = null; return privateMethods. initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, requestPayload); From ec7f8ccd1fda8312e1c5b94b54b09d69b12b638d Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 1 Aug 2016 20:28:39 +0530 Subject: [PATCH 30/76] disabling testing info logs at token-protected-service-invokers.js --- .../app/modules/oauth/token-protected-service-invokers.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index 9c217a52dd..4994e160bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -95,10 +95,10 @@ var invokers = function () { log.debug("Service Invoker-URL: " + endpoint); log.debug("Service Invoker-Method: " + httpMethod); - log.info("Request : " + httpMethod + " " + endpoint); - log.info("Request payload if any : " + stringify(requestPayload)); - log.info("Response status : " + xmlHttpRequest.status); - log.info("Response payload if any : " + xmlHttpRequest.responseText); +// log.info("Request : " + httpMethod + " " + endpoint); +// log.info("Request payload if any : " + stringify(requestPayload)); +// log.info("Response status : " + xmlHttpRequest.status); +// log.info("Response payload if any : " + xmlHttpRequest.responseText); if (xmlHttpRequest.status == 401 && (xmlHttpRequest.responseText == TOKEN_EXPIRED || xmlHttpRequest.responseText == TOKEN_INVALID ) && count < 5) { From 6cc1bb088cabc2023823078eee7d9a8a56646338 Mon Sep 17 00:00:00 2001 From: harshanl Date: Mon, 1 Aug 2016 20:29:21 +0530 Subject: [PATCH 31/76] Fixed EMM-1447, EMM-1424 --- .../impl/ActivityProviderServiceImpl.java | 2 +- .../impl/DeviceManagementServiceImpl.java | 4 +- .../NotificationManagementServiceImpl.java | 1 + .../impl/PolicyManagementServiceImpl.java | 1 + .../impl/RoleManagementServiceImpl.java | 1 + .../impl/UserManagementServiceImpl.java | 2 + .../DeviceManagementAdminServiceImpl.java | 2 + .../impl/util/RequestValidationUtil.java | 14 ++++ .../core/config/DeviceManagementConfig.java | 11 +++ .../pagination/PaginationConfiguration.java | 71 ++++++++++++++++ .../NotificationManagementServiceImpl.java | 3 + .../DeviceManagementProviderServiceImpl.java | 9 ++ .../mgt/core/util/DeviceManagerUtil.java | 84 ++++++++++++++++++- .../src/main/resources/conf/cdm-config.xml | 14 +++- 14 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java index 444854e1e4..b80889f41b 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 @@ -81,7 +81,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService long timestamp = 0; boolean isIfModifiedSinceSet = false; boolean isSinceSet = false; - + RequestValidationUtil.validatePaginationParameters(offset, limit); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { Date ifSinceDate; SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java index 2266f51d4a..2fafc9b129 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 @@ -74,7 +74,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("limit") int limit) { try { // RequestValidationUtil.validateSelectionCriteria(type, user, roleName, ownership, status); - + RequestValidationUtil.validatePaginationParameters(offset, limit); DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; @@ -154,6 +154,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { public Response getDeviceByUser(@QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceList devices = new DeviceList(); @@ -292,6 +293,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { @QueryParam("offset") int offset, @QueryParam("limit") int limit) { OperationList operationsList = new OperationList(); + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; DeviceManagementProviderService dms; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/NotificationManagementServiceImpl.java index c504da33d1..acfe66f043 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 @@ -50,6 +50,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PaginationRequest request = new PaginationRequest(offset, limit); PaginationResult result; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java index 487cdc1517..a47e85e5c1 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 @@ -140,6 +140,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); List policies; List filteredPolicies; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java index e0a832a77c..dab2affc1a 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 @@ -61,6 +61,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { @QueryParam("user-store") String userStore, @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); List filteredRoles; RoleList targetRoles = new RoleList(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index ffad2e8d81..eda434e2f8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java @@ -26,6 +26,7 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo; import org.wso2.carbon.device.mgt.jaxrs.beans.*; import org.wso2.carbon.device.mgt.jaxrs.service.api.UserManagementService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.CredentialManagementResponseBuilder; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; @@ -264,6 +265,7 @@ public class UserManagementServiceImpl implements UserManagementService { log.debug("Getting the list of users with all user-related information"); } List userList, offsetList; + RequestValidationUtil.validatePaginationParameters(offset, limit); String appliedFilter = ((filter == null) || filter.isEmpty() ? "*" : filter); int appliedLimit = (limit <= 0) ? -1 : (limit + offset); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java index 4956583627..26ac8dd8d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java @@ -28,6 +28,7 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService; +import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import javax.ws.rs.*; @@ -50,6 +51,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe @HeaderParam("If-Modified-Since") String ifModifiedSince, @QueryParam("offset") int offset, @QueryParam("limit") int limit) { + RequestValidationUtil.validatePaginationParameters(offset, limit); try { int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/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..3a4c4b5c63 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,6 +19,7 @@ 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.*; @@ -312,4 +313,17 @@ public class RequestValidationUtil { } } + public static void validatePaginationParameters(int offset, int limit) { + if (offset < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter offset is s " + + "negative value.").build()); + } + if (limit < 0) { + throw new InputValidationException( + new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Request parameter limit is a " + + "negative value.").build()); + } + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java index 0891164cb0..20e4eba5c2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java @@ -18,6 +18,7 @@ package org.wso2.carbon.device.mgt.core.config; import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations; +import org.wso2.carbon.device.mgt.core.config.pagination.PaginationConfiguration; import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration; import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration; @@ -37,6 +38,7 @@ public final class DeviceManagementConfig { private TaskConfiguration taskConfiguration; private IdentityConfigurations identityConfigurations; private PolicyConfiguration policyConfiguration; + private PaginationConfiguration paginationConfiguration; private List pushNotificationProviders; @@ -87,5 +89,14 @@ public final class DeviceManagementConfig { this.pushNotificationProviders = pushNotificationProviders; } + @XmlElement(name = "PaginationConfiguration", required = true) + public PaginationConfiguration getPaginationConfiguration() { + return paginationConfiguration; + } + + public void setPaginationConfiguration(PaginationConfiguration paginationConfiguration) { + this.paginationConfiguration = paginationConfiguration; + } + } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java new file mode 100644 index 0000000000..f60f33d98f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/pagination/PaginationConfiguration.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.config.pagination; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * This class represents the information related to Pagination configuration. + */ +@XmlRootElement(name = "PaginationConfiguration") +public class PaginationConfiguration { + + private int deviceListPageSize; + private int operationListPageSize; + private int notificationListPageSize; + private int activityListPageSize; + + public int getDeviceListPageSize() { + return deviceListPageSize; + } + + @XmlElement(name = "DeviceListPageSize", required = true) + public void setDeviceListPageSize(int deviceListPageSize) { + this.deviceListPageSize = deviceListPageSize; + } + + public int getOperationListPageSize() { + return operationListPageSize; + } + + @XmlElement(name = "OperationListPageSize", required = true) + public void setOperationListPageSize(int operationListPageSize) { + this.operationListPageSize = operationListPageSize; + } + + public int getNotificationListPageSize() { + return notificationListPageSize; + } + + @XmlElement(name = "NotificationListPageSize", required = true) + public void setNotificationListPageSize(int notificationListPageSize) { + this.notificationListPageSize = notificationListPageSize; + } + + public int getActivityListPageSize() { + return activityListPageSize; + } + + @XmlElement(name = "ActivityListPageSize", required = true) + public void setActivityListPageSize(int activityListPageSize) { + this.activityListPageSize = activityListPageSize; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java index 59692da94d..88883a4e26 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java @@ -35,6 +35,7 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationDAO; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; +import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import java.sql.SQLException; import java.util.ArrayList; @@ -177,6 +178,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement public PaginationResult getAllNotifications(PaginationRequest request) throws NotificationManagementException { PaginationResult paginationResult = new PaginationResult(); List notifications = new ArrayList<>(); + request = DeviceManagerUtil.validateNotificationListPageSize(request); int count =0; try { NotificationManagementDAOFactory.openConnection(); @@ -199,6 +201,7 @@ public class NotificationManagementServiceImpl implements NotificationManagement PaginationRequest request) throws NotificationManagementException{ PaginationResult paginationResult = new PaginationResult(); List notifications = new ArrayList<>(); + request = DeviceManagerUtil.validateNotificationListPageSize(request); int count =0; try { NotificationManagementDAOFactory.openConnection(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java index 314a26c392..73533f36fd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java @@ -508,6 +508,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int count = 0; int tenantId = this.getTenantId(); String deviceType = request.getDeviceType(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevices(request, tenantId); @@ -569,6 +570,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allDevices = new ArrayList<>(); int count = 0; int tenantId = this.getTenantId(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevices(request, tenantId); @@ -1031,6 +1033,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public PaginationResult getOperations(DeviceIdentifier deviceId, PaginationRequest request) throws OperationManagementException { + request = DeviceManagerUtil.validateOperationListPageSize(request); return pluginRepository.getOperationManager(deviceId.getType(), this.getTenantId()) .getOperations(deviceId, request); } @@ -1091,6 +1094,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv @Override public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementException { + limit = DeviceManagerUtil.validateActivityListPageSize(limit); return DeviceManagementDataHolder.getInstance().getOperationManager().getActivitiesUpdatedAfter(timestamp, limit, offset); } @@ -1176,6 +1180,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv String username = request.getOwner(); List devices = new ArrayList<>(); List userDevices = new ArrayList<>(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); userDevices = deviceDAO.getDevicesOfUser(request, tenantId); @@ -1253,6 +1258,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv int deviceCount = 0; int tenantId = this.getTenantId(); String ownerShip = request.getOwnership(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByOwnership(request, tenantId); @@ -1412,6 +1418,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv public List getDevicesByNameAndType(String deviceName, String type, int offset, int limit) throws DeviceManagementException { List devices = new ArrayList<>(); List allDevices; + limit = DeviceManagerUtil.validateDeviceListPageSize(limit); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByNameAndType(deviceName, type, this.getTenantId(), offset, limit); @@ -1474,6 +1481,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List devices = new ArrayList<>(); List allDevices = new ArrayList<>(); String deviceName = request.getDeviceName(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByName(request, tenantId); @@ -1636,6 +1644,7 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv List allDevices = new ArrayList<>(); int tenantId = this.getTenantId(); String status = request.getStatus(); + request = DeviceManagerUtil.validateDeviceListPageSize(request); try { DeviceManagementDAOFactory.openConnection(); allDevices = deviceDAO.getDevicesByStatus(request, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java index a9d472d498..2e338943b8 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java @@ -21,10 +21,11 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.wso2.carbon.base.MultitenantConstants; -import org.wso2.carbon.device.mgt.common.Device; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.DeviceManagementException; -import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.*; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; +import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; +import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; @@ -241,4 +242,79 @@ public final class DeviceManagerUtil { } } + public static int validateActivityListPageSize(int limit) throws OperationManagementException { + if (limit == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + return deviceManagementConfig.getPaginationConfiguration().getActivityListPageSize(); + } else { + throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return limit; + } + + public static PaginationRequest validateOperationListPageSize(PaginationRequest paginationRequest) throws + OperationManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getOperationListPageSize()); + } else { + throw new OperationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static PaginationRequest validateNotificationListPageSize(PaginationRequest paginationRequest) throws + NotificationManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getNotificationListPageSize()); + } else { + throw new NotificationManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static PaginationRequest validateDeviceListPageSize(PaginationRequest paginationRequest) throws + DeviceManagementException { + if (paginationRequest.getRowCount() == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + paginationRequest.setRowCount(deviceManagementConfig.getPaginationConfiguration(). + getDeviceListPageSize()); + } else { + throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return paginationRequest; + } + + public static int validateDeviceListPageSize(int limit) throws DeviceManagementException { + if (limit == 0) { + DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance(). + getDeviceManagementConfig(); + if (deviceManagementConfig != null) { + return deviceManagementConfig.getPaginationConfiguration().getDeviceListPageSize(); + } else { + throw new DeviceManagementException("Device-Mgt configuration has not initialized. Please check the " + + "cdm-config.xml file."); + } + } + return limit; + } } diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml index 416495b061..bf6e3787b1 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/conf/cdm-config.xml @@ -27,8 +27,8 @@ org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm.GCMBasedPushNotificationProvider - org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt.MQTTBasedPushNotificationProvider - org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp.XMPPBasedPushNotificationProvider + + https://localhost:9443 @@ -37,14 +37,14 @@ org.wso2.carbon.policy.mgt - false + true 60000 5 8 20 - false + true 600000 org.wso2.carbon.device.mgt.core.task.impl.DeviceDetailsRetrieverTask @@ -62,5 +62,11 @@ + + 20 + 20 + 20 + 20 + From e125871de0cb4216da341a16257c643d5415f427 Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 1 Aug 2016 22:42:53 +0530 Subject: [PATCH 32/76] Adding business-controllers to UI Modules --- .../resources/jaggeryapps/devicemgt/api/device-api.jag | 4 ++-- .../resources/jaggeryapps/devicemgt/api/policy-api.jag | 2 +- .../main/resources/jaggeryapps/devicemgt/api/user-api.jag | 4 ++-- .../app/modules/{ => business-controllers}/device.js | 4 ++-- .../app/modules/{ => business-controllers}/group.js | 4 ++-- .../app/modules/{ => business-controllers}/operation.js | 2 +- .../app/modules/{ => business-controllers}/policy.js | 2 +- .../app/modules/{ => business-controllers}/user.js | 2 +- .../resources/jaggeryapps/devicemgt/app/modules/init.js | 2 +- .../app/modules/oauth/token-protected-service-invokers.js | 2 +- .../devicemgt/app/pages/cdmf.page.dashboard/dashboard.js | 8 ++++---- .../devicemgt/app/pages/cdmf.page.devices/devices.js | 6 +++--- .../app/pages/cdmf.page.group.analytics/analytics.js | 2 +- .../devicemgt/app/pages/cdmf.page.groups/groups.js | 4 ++-- .../devicemgt/app/pages/cdmf.page.policies/policies.js | 4 ++-- .../devicemgt/app/pages/cdmf.page.user.create/create.js | 2 +- .../devicemgt/app/pages/cdmf.page.user.edit/edit.js | 2 +- .../devicemgt/app/pages/cdmf.page.user.view/view.js | 4 ++-- .../app/units/cdmf.unit.device.type.view/view.js | 2 +- .../app/units/cdmf.unit.device.types.listing/listing.js | 2 +- .../devicemgt/app/units/cdmf.unit.device.view/view.js | 2 +- .../app/units/cdmf.unit.notification.listing/listing.js | 2 +- .../cdmf.unit.platform.configuration/configuration.js | 4 ++-- .../devicemgt/app/units/cdmf.unit.policy.create/create.js | 2 +- .../app/units/cdmf.unit.policy.priority/priority.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.create/create.js | 2 +- .../units/cdmf.unit.role.edit.permission/permission.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.edit/edit.js | 2 +- .../devicemgt/app/units/cdmf.unit.role.listing/listing.js | 2 +- .../app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js | 2 +- 30 files changed, 43 insertions(+), 43 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => business-controllers}/device.js (98%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => business-controllers}/group.js (94%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => business-controllers}/operation.js (98%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => business-controllers}/policy.js (99%) rename components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/{ => business-controllers}/user.js (99%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag index 937d396885..ecb9806b5d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/device-api.jag @@ -22,10 +22,10 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/device-api.jag"); var constants = require("/app/modules/constants.js"); -var deviceModule = require("/app/modules/device.js").deviceModule; +var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; -var userModule = require("/app/modules/user.js").userModule; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var user = session.get(constants.USER_SESSION_KEY); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag index d2a2630be7..5ae93fdde7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/policy-api.jag @@ -27,7 +27,7 @@ var uriMatcher = new URIMatcher(String(uri)); var log = new Log("api/policy-api.jag"); var constants = require("/modules/constants.js"); -var policyModule = require("/modules/policy.js").policyModule; +var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"]; var result; if (uriMatcher.match("/{context}/api/policies/update")) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag index 3c11d19fde..212a087539 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/user-api.jag @@ -24,8 +24,8 @@ var log = new Log("api/user-api.jag"); var constants = require("/app/modules/constants.js"); var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; -var userModule = require("/app/modules/user.js").userModule; -var deviceModule = require("/app/modules/device.js").deviceModule; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; +var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; var apiWrapperUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; var util = require("/app/modules/oauth/token-handler-utils.js")["utils"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js index 071154584d..4510106bad 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -18,7 +18,7 @@ var deviceModule; deviceModule = function () { - var log = new Log("/app/modules/device.js"); + var log = new Log("/app/modules/business-controllers/device.js"); var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); @@ -261,7 +261,7 @@ deviceModule = function () { publicMethods.getDevicesCount = function () { var carbonUser = session.get(constants.USER_SESSION_KEY); if (carbonUser) { - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var uiPermissions = userModule.getUIPermissions(); var url; if (uiPermissions.LIST_DEVICES) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js similarity index 94% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js index c2567cec29..02b2198b48 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/group.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/group.js @@ -18,9 +18,9 @@ var groupModule = {}; (function (groupModule) { - var log = new Log("/app/modules/group.js"); + var log = new Log("/app/modules/business-controllers/group.js"); - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var utility = require("/app/modules/utility.js").utility; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js similarity index 98% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js index 9f75d4eb17..e96ffcdec1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js @@ -17,7 +17,7 @@ */ var operationModule = function () { - var log = new Log("/app/modules/operation.js"); + var log = new Log("/app/modules/business-controllers/operation.js"); var utility = require('/app/modules/utility.js').utility; var constants = require('/app/modules/constants.js'); var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js index 998e6722d1..6cc38a9bfe 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js @@ -21,7 +21,7 @@ */ var policyModule; policyModule = function () { - var log = new Log("/app/modules/policy.js"); + var log = new Log("/app/modules/business-controllers/policy.js"); var constants = require('/app/modules/constants.js'); var utility = require("/app/modules/utility.js")["utility"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js similarity index 99% rename from components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js rename to components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index 29a7de7365..720cbc4629 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -20,7 +20,7 @@ * This module contains user and roles related functionality. */ var userModule = function () { - var log = new Log("/app/modules/user.js"); + var log = new Log("/app/modules/business-controllers/user.js"); var constants = require("/app/modules/constants.js"); var utility = require("/app/modules/utility.js")["utility"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js index 8e86f44ab8..d9f442cdd4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/init.js @@ -24,7 +24,7 @@ var carbonServer = new carbonModule.server.Server({ }); application.put("carbonServer", carbonServer); -var userModule = require("/app/modules/user.js")["userModule"]; +var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var utility = require("/app/modules/utility.js")["utility"]; var permissions = { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index 4994e160bf..fa71ce1475 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -37,7 +37,7 @@ var invokers = function () { var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var tokenUtil = require("/app/modules/oauth/token-handlers.js")["handlers"]; /** diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js index 8681882f2e..ec98554ce1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.dashboard/dashboard.js @@ -19,7 +19,7 @@ function onRequest(context) { var constants = require("/app/modules/constants.js"); var user = session.get(constants.USER_SESSION_KEY); - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var permissions = userModule.getUIPermissions(); var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; @@ -31,9 +31,9 @@ function onRequest(context) { var page = {}; page.permissions = permissions; page.enrollmentURL = devicemgtProps.enrollmentURL; - var deviceModule = require("/app/modules/device.js").deviceModule; - var groupModule = require("/app/modules/group.js").groupModule; - var policyModule = require("/app/modules/policy.js").policyModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; + var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"]; + var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"]; page.device_count = deviceModule.getDevicesCount(); page.group_count = groupModule.getGroupCount(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js index 085f1f5a69..15c9b131f7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.js @@ -18,8 +18,8 @@ function onRequest(context) { var constants = require("/app/modules/constants.js"); - var userModule = require("/app/modules/user.js").userModule; - var deviceModule = require("/app/modules/device.js").deviceModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var groupName = request.getParameter("groupName"); var groupOwner = request.getParameter("groupOwner"); @@ -42,7 +42,7 @@ function onRequest(context) { page.currentUser = currentUser; var deviceCount = 0; if (groupName && groupOwner) { - var groupModule = require("/app/modules/group.js").groupModule; + var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"]; deviceCount = groupModule.getGroupDeviceCount(groupName, groupOwner); } else { deviceCount = deviceModule.getDevicesCount(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.analytics/analytics.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.analytics/analytics.js index 563660dadb..fe9a550516 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.analytics/analytics.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.group.analytics/analytics.js @@ -18,7 +18,7 @@ function onRequest(context) { var utility = require("/app/modules/utility.js").utility; - var groupModule = require("/app/modules/group.js").groupModule; + var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"]; var groupName = context.uriParams.name; var groupOwner = context.uriParams.owner; var devices = groupModule.getGroupDevices(groupName, groupOwner).data; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.js index 188a8fec1a..532ce661c7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.groups/groups.js @@ -17,8 +17,8 @@ */ function onRequest(context) { - var groupModule = require("/app/modules/group.js").groupModule; - var userModule = require("/app/modules/user.js").userModule; + var groupModule = require("/app/modules/business-controllers/group.js")["groupModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require("/app/modules/constants.js"); var currentUser = session.get(constants.USER_SESSION_KEY); var page = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policies/policies.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policies/policies.js index b21d376f06..3f60618d84 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policies/policies.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policies/policies.js @@ -28,8 +28,8 @@ function onRequest(context) { } }); var page = {}; - var policyModule = require("/app/modules/policy.js")["policyModule"]; - var userModule = require("/app/modules/user.js")["userModule"]; + var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var response = policyModule.getAllPolicies(); if (response["status"] == "success") { var policyListToView = response["content"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js index cbd0564b15..4cba6f75c3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.create/create.js @@ -25,7 +25,7 @@ function onRequest(context) { //var log = new Log("/app/pages/cdmf.page.user.create server-side js"); - 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"]; var page = {}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js index 7037721ad9..a8eab03731 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.edit/edit.js @@ -17,7 +17,7 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var userName = request.getParameter("username"); var user = userModule.getUser(userName)["content"]; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js index 8b41bc8a36..ffb86426bb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js @@ -17,7 +17,7 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var username = request.getParameter("username"); var user = userModule.getUser(username)["content"]; var userModule = require("/app/modules/user.js")["userModule"]; @@ -38,7 +38,7 @@ function onRequest(context) { if (response["status"] == "success") { userRoles = response["content"]; } - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; devices = deviceModule.getDevices(userName); } return {"user": user, "userRoles": userRoles, "devices": devices}; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js index f003d47581..fa599c37a7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.view/view.js @@ -27,7 +27,7 @@ function onRequest (context) { } //For QR Code - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require("/app/modules/constants.js"); var permissions = userModule.getUIPermissions(); var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js index fecc522807..0ae0ed8a48 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.types.listing/listing.js @@ -23,7 +23,7 @@ function onRequest(context) { var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label"; var viewModel = {}; - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var utility = require("/app/modules/utility.js").utility; var deviceTypes = deviceModule.getDeviceTypes(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js index d544e09b58..a3a0037dcb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js @@ -22,7 +22,7 @@ function onRequest(context) { var deviceId = request.getParameter("id"); if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { - var deviceModule = require("/app/modules/device.js").deviceModule; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; var device = deviceModule.viewDevice(deviceType, deviceId); if (device) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js index 50306cbfb3..0086ba8e3e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/listing.js @@ -17,7 +17,7 @@ */ function onRequest(context){ - var userModule = require("/app/modules/user.js").userModule; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var constants = require("/app/modules/constants.js"); var permissions = []; if(userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/notifications/list")){ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js index 749ee92c15..e34720df7b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.platform.configuration/configuration.js @@ -17,8 +17,8 @@ */ function onRequest(context) { - var utility = require("/app/modules/device.js").utility; - var deviceModule = require("/app/modules/device.js").deviceModule; + var utility = require("/app/modules/utility.js").utility; + var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; //get all device types var data = deviceModule.getDeviceTypes(); var deviceTypesArray = []; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js index 3e09ae185d..cf46e20def 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js @@ -21,7 +21,7 @@ function onRequest(context) { var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label"; var utility = require("/app/modules/utility.js").utility; - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var types = {}; types["types"] = []; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js index 7630df258b..2ba2155ac2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.priority/priority.js @@ -27,7 +27,7 @@ function onRequest(context) { return options.fn(this); } }); - var policyModule = require("/app/modules/policy.js")["policyModule"]; + var policyModule = require("/app/modules/business-controllers/group.js")["groupModule"]; var response = policyModule.getAllPolicies(); if (response["status"] == "success") { var policyListToView = response["content"]; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js index 9e00dc32aa..a65fa31e25 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.create/create.js @@ -23,7 +23,7 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var response = userModule.getRoles(); if (response["status"] == "success") { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js index a16f9a38bb..6829dc21e3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit.permission/permission.js @@ -23,7 +23,7 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); var isMatched = uriMatcher.match("/{context}/roles/edit-role-permission/{rolename}"); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js index 01a08da69f..cf54af034e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.edit/edit.js @@ -23,7 +23,7 @@ * @returns {*} A context object that returns the dynamic state of this page to be presented */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var uri = request.getRequestURI(); var uriMatcher = new URIMatcher(String(uri)); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js index c5c67d1029..d908da5d2d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.role.listing/listing.js @@ -17,7 +17,7 @@ */ function onRequest(context) { - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var response = userModule.getUsers(); var users = {}; context["permissions"] = userModule.getUIPermissions(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js index 3f4ede1774..363d9688e6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.navbar.nav-menu/nav-menu.js @@ -27,7 +27,7 @@ function onRequest(context) { return options.fn(this); } }); - var userModule = require("/app/modules/user.js")["userModule"]; + var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; var constants = require("/app/modules/constants.js"); var uiPermissions = userModule.getUIPermissions(); From c7f4bba8bf5bd22b1dc8eae30895967ca39720bb Mon Sep 17 00:00:00 2001 From: dilanua Date: Mon, 1 Aug 2016 22:45:30 +0530 Subject: [PATCH 33/76] Deprecating operation.js module from UI --- .../modules/business-controllers/operation.js | 234 +++++++++--------- 1 file changed, 119 insertions(+), 115 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js index e96ffcdec1..1e479286a9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js @@ -16,119 +16,123 @@ * under the License. */ -var operationModule = function () { - var log = new Log("/app/modules/business-controllers/operation.js"); - var utility = require('/app/modules/utility.js').utility; - var constants = require('/app/modules/constants.js'); - var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; - var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; +/* + @Deprecated New + */ - var publicMethods = {}; - var privateMethods = {}; - - /** - * This method reads the token from the Token client and return the access token. - * If the token pair s not set in the session this will send a redirect to the login page. - */ - function getAccessToken(deviceType, owner, deviceId) { - var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; - var accessTokenClient = new TokenClient(deviceType); - var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); - return accessTokenInfo.getAccess_token(); - } - - privateMethods.getOperationsFromFeatures = function (deviceType, operationType) { - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType; - var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) { - var features = responsePayload; - var featureList = []; - var feature; - for (var i = 0; i < features.length; i++) { - feature = {}; - var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; - if (analyticStreams) { - for (var stream in analyticStreams) { - if (analyticStreams[stream].name == features[i].name) { - feature.ui_unit = analyticStreams[stream].ui_unit; - break; - } - } - } - - feature["operation"] = features[i].code; - feature["name"] = features[i].name; - feature["description"] = features[i].description; - feature["deviceType"] = deviceType; - feature["params"] = []; - var metaData = features[i].metadataEntries; - if (metaData) { - for (var j = 0; j < metaData.length; j++) { - feature["params"].push(metaData[j].value); - } - featureList.push(feature); - } - } - return featureList; - }, function (responsePayload) { - var response = {}; - response["status"] = "error"; - return response; - } - ); - return featuresList; - }; - - publicMethods.getControlOperations = function (deviceType) { - var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation"); - for (var op in operations) { - var iconPath = utility.getOperationIcon(deviceType, operations[op].operation); - if (iconPath) { - operations[op]["icon"] = iconPath; - } - } - return operations; - }; - - publicMethods.getMonitorOperations = function (deviceType) { - return privateMethods.getOperationsFromFeatures(deviceType, "monitor"); - }; - - publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) { - var user = session.get(constants.USER_SESSION_KEY); - var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; - var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + - '","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' + - constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX + - getAccessToken(deviceType, user.username, deviceId) + '"}'; - return post(endPoint, params, JSON.parse(header), "json"); - }; - - publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) { - var user = session.get(constants.USER_SESSION_KEY); - var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; - var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + - '","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' + - constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) + - '"}'; - var result = get(endPoint, {}, JSON.parse(header), "json"); - if (result.data) { - var values = result.data.sensorValue.split(','); - if (operationName == 'gps') { - result.data.map = { - lat: parseFloat(values[0]), - lng: parseFloat(values[1]) - } - } else { - var sqSum = 0; - for (var v in values) { - sqSum += Math.pow(values[v], 2); - } - result.data[operationName] = Math.sqrt(sqSum); - } - delete result.data['sensorValue']; - } - return result; - }; - - return publicMethods; -}(); \ No newline at end of file +//var operationModule = function () { +// var log = new Log("/app/modules/business-controllers/operation.js"); +// var utility = require('/app/modules/utility.js').utility; +// var constants = require('/app/modules/constants.js'); +// var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; +// var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; +// +// var publicMethods = {}; +// var privateMethods = {}; +// +// /** +// * This method reads the token from the Token client and return the access token. +// * If the token pair s not set in the session this will send a redirect to the login page. +// */ +// function getAccessToken(deviceType, owner, deviceId) { +// var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; +// var accessTokenClient = new TokenClient(deviceType); +// var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); +// return accessTokenInfo.getAccess_token(); +// } +// +// privateMethods.getOperationsFromFeatures = function (deviceType, operationType) { +// var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType; +// var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) { +// var features = responsePayload; +// var featureList = []; +// var feature; +// for (var i = 0; i < features.length; i++) { +// feature = {}; +// var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; +// if (analyticStreams) { +// for (var stream in analyticStreams) { +// if (analyticStreams[stream].name == features[i].name) { +// feature.ui_unit = analyticStreams[stream].ui_unit; +// break; +// } +// } +// } +// +// feature["operation"] = features[i].code; +// feature["name"] = features[i].name; +// feature["description"] = features[i].description; +// feature["deviceType"] = deviceType; +// feature["params"] = []; +// var metaData = features[i].metadataEntries; +// if (metaData) { +// for (var j = 0; j < metaData.length; j++) { +// feature["params"].push(metaData[j].value); +// } +// featureList.push(feature); +// } +// } +// return featureList; +// }, function (responsePayload) { +// var response = {}; +// response["status"] = "error"; +// return response; +// } +// ); +// return featuresList; +// }; +// +// publicMethods.getControlOperations = function (deviceType) { +// var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation"); +// for (var op in operations) { +// var iconPath = utility.getOperationIcon(deviceType, operations[op].operation); +// if (iconPath) { +// operations[op]["icon"] = iconPath; +// } +// } +// return operations; +// }; +// +// publicMethods.getMonitorOperations = function (deviceType) { +// return privateMethods.getOperationsFromFeatures(deviceType, "monitor"); +// }; +// +// publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) { +// var user = session.get(constants.USER_SESSION_KEY); +// var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; +// var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + +// '","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' + +// constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX + +// getAccessToken(deviceType, user.username, deviceId) + '"}'; +// return post(endPoint, params, JSON.parse(header), "json"); +// }; +// +// publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) { +// var user = session.get(constants.USER_SESSION_KEY); +// var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; +// var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + +// '","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' + +// constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) + +// '"}'; +// var result = get(endPoint, {}, JSON.parse(header), "json"); +// if (result.data) { +// var values = result.data.sensorValue.split(','); +// if (operationName == 'gps') { +// result.data.map = { +// lat: parseFloat(values[0]), +// lng: parseFloat(values[1]) +// } +// } else { +// var sqSum = 0; +// for (var v in values) { +// sqSum += Math.pow(values[v], 2); +// } +// result.data[operationName] = Math.sqrt(sqSum); +// } +// delete result.data['sensorValue']; +// } +// return result; +// }; +// +// return publicMethods; +//}(); \ No newline at end of file From 9510554f67e26e88a75cbffc6353def7c78b205d Mon Sep 17 00:00:00 2001 From: kamidu Date: Tue, 2 Aug 2016 00:05:23 +0530 Subject: [PATCH 34/76] Fix the notification view internal server error issue --- .../public/js/notification-listing.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js index ba6f47c614..52fd96af33 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.notification.listing/public/js/notification-listing.js @@ -46,7 +46,7 @@ $(document).ready(function () { $("#ast-container").on("click", ".new-notification", function(e){ var notificationId = $(this).data("id"); var redirectUrl = $(this).data("url"); - var getNotificationsAPI = "/devicemgt_admin/notifications/"+notificationId+"/CHECKED"; + var getNotificationsAPI = "/api/device-mgt/v1.0/notifications/"+notificationId+"/CHECKED"; var errorMsgWrapper = "#error-msg"; var errorMsg = "#error-msg span"; invokerUtil.put( @@ -87,7 +87,7 @@ function loadNotifications(){ var deviceListingSrc = deviceListing.attr("src"); var currentUser = deviceListing.data("currentUser"); $.template("notification-listing", deviceListingSrc, function (template) { - var serviceURL = "/devicemgt_admin/notifications"; + var serviceURL = "/api/device-mgt/v1.0/notifications"; var successCallback = function (data) { var viewModel = {}; data = JSON.parse(data); From efcd5272d277a80c0279b8959b7125a408afdfed Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 2 Aug 2016 14:31:12 +0530 Subject: [PATCH 35/76] Fix issues in sql statements --- .../device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java | 4 ++-- .../carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java index 0021c0dc96..45a4b881c4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/ApplicationMappingDAOImpl.java @@ -102,7 +102,7 @@ public class ApplicationMappingDAOImpl implements ApplicationMappingDAO { Connection conn; PreparedStatement stmt = null; try { - String sql = "DELETE DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID = ? AND " + + String sql = "DELETE FROM DM_DEVICE_APPLICATION_MAPPING WHERE DEVICE_ID = ? AND " + "APPLICATION_ID = ? AND TENANT_ID = ?"; conn = this.getConnection(); @@ -114,7 +114,7 @@ public class ApplicationMappingDAOImpl implements ApplicationMappingDAO { stmt.execute(); } } catch (SQLException e) { - throw new DeviceManagementDAOException("Error occurred while adding device application mapping", e); + throw new DeviceManagementDAOException("Error occurred while removing device application mapping", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, null); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java index 1998907b9d..abb9b1f87c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java @@ -129,7 +129,7 @@ public class EnrollmentDAOImpl implements EnrollmentDAO { int status = -1; try { conn = this.getConnection(); - String sql = "DELETE DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; + String sql = "DELETE FROM DM_ENROLMENT WHERE DEVICE_ID = ? AND OWNER = ? AND TENANT_ID = ?"; stmt = conn.prepareStatement(sql, new String[] {"id"}); stmt.setInt(1, deviceId); stmt.setString(2, currentOwner); From b8bf855378bd748201f578bb3ca1357f70168196 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Tue, 2 Aug 2016 15:43:40 +0530 Subject: [PATCH 36/76] Calculating enrollment url when generalConfig.host config exists --- .../jaggeryapps/devicemgt/app/modules/conf-reader/main.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js index f81849fe3b..6731dbd23a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js @@ -37,6 +37,12 @@ var conf = function () { return value; } ); + if (conf.generalConfig.host) { + //TODO: Move enrollment URL into app-conf.json + var enrollmentHost = conf.generalConfig.host.replace(/https:\/\/localhost(:\d+)?/, conf.httpsURL).replace( + /http:\/\/localhost(:\d+)?/, conf.httpURL); + conf.enrollmentUrl = enrollmentHost + conf.enrollmentDir; + } application.put("CONF", conf); } return conf; From 03835bdeb73d996e47cad56b8cd1c1439ccada7b Mon Sep 17 00:00:00 2001 From: harshanl Date: Tue, 2 Aug 2016 17:40:20 +0530 Subject: [PATCH 37/76] Fixed EMM-1449 issue --- .../src/main/resources/dbscripts/cdm/h2.sql | 8 ++++---- .../src/main/resources/dbscripts/cdm/mssql.sql | 16 ++++++++-------- .../src/main/resources/dbscripts/cdm/mysql.sql | 17 +++++++++-------- .../src/main/resources/dbscripts/cdm/oracle.sql | 16 ++++++++-------- .../main/resources/dbscripts/cdm/postgresql.sql | 16 ++++++++-------- 5 files changed, 37 insertions(+), 36 deletions(-) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql index f3f3735e50..82c2eba536 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/h2.sql @@ -134,7 +134,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ID INT NOT NULL AUTO_INCREMENT , PROFILE_NAME VARCHAR(45) NOT NULL , TENANT_ID INT NOT NULL , - DEVICE_TYPE VARCHAR(20) NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , CREATED_TIME DATETIME NOT NULL , UPDATED_TIME DATETIME NOT NULL , PRIMARY KEY (ID) , @@ -195,7 +195,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ID INT(11) NOT NULL , - DEVICE_TYPE VARCHAR(20) NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY @@ -218,7 +218,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ID INT(11) NOT NULL AUTO_INCREMENT, PROFILE_ID INT(11) NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE VARCHAR(20) NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, TENANT_ID INT(11) NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), @@ -339,7 +339,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, - DEVICE_TYPE VARCHAR(20) NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , TENANT_ID INT(11) NOT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index 66ce12dc87..385ac2a135 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -135,13 +135,13 @@ CREATE TABLE DM_PROFILE ( ID INTEGER NOT NULL IDENTITY , PROFILE_NAME VARCHAR(45) NOT NULL , TENANT_ID INTEGER NOT NULL , - DEVICE_TYPE_ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , CREATED_TIME DATETIME2(0) NOT NULL , UPDATED_TIME DATETIME2(0) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE) + REFERENCES DM_DEVICE_TYPE (NAME ) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -196,7 +196,7 @@ CREATE TABLE DM_DEVICE_POLICY ( CREATE TABLE DM_DEVICE_TYPE_POLICY ( ID INTEGER NOT NULL , - DEVICE_TYPE_ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , POLICY_ID INTEGER NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY @@ -205,8 +205,8 @@ CREATE TABLE DM_DEVICE_TYPE_POLICY ( ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE) + REFERENCES DM_DEVICE_TYPE (NAME ) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -219,7 +219,7 @@ CREATE TABLE DM_PROFILE_FEATURES ( ID INTEGER NOT NULL IDENTITY, PROFILE_ID INTEGER NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE_ID INTEGER NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , TENANT_ID INTEGER NOT NULL , CONTENT VARBINARY(max) NULL DEFAULT NULL, PRIMARY KEY (ID), @@ -340,7 +340,7 @@ CREATE TABLE DM_POLICY_COMPLIANCE_STATUS ( CREATE TABLE DM_POLICY_CHANGE_MGT ( ID INTEGER NOT NULL IDENTITY, POLICY_ID INTEGER NOT NULL, - DEVICE_TYPE_ID INTEGER NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) ); diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 1d2013cbc4..098ebc5d98 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -5,6 +5,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (ID) )ENGINE = InnoDB; +CREATE INDEX device_type_name ON DM_DEVICE_TYPE (NAME); CREATE TABLE IF NOT EXISTS DM_DEVICE ( ID INTEGER AUTO_INCREMENT NOT NULL, @@ -117,13 +118,13 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ID INT NOT NULL AUTO_INCREMENT , PROFILE_NAME VARCHAR(45) NOT NULL , TENANT_ID INT NOT NULL , - DEVICE_TYPE_ID INT NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , CREATED_TIME DATETIME NOT NULL , UPDATED_TIME DATETIME NOT NULL , PRIMARY KEY (ID) , CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE) + REFERENCES DM_DEVICE_TYPE (NAME) ON DELETE NO ACTION ON UPDATE NO ACTION )ENGINE = InnoDB; @@ -171,7 +172,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ID INT(11) NOT NULL , - DEVICE_TYPE_ID INT(11) NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY @@ -180,8 +181,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME ) ON DELETE NO ACTION ON UPDATE NO ACTION )ENGINE = InnoDB; @@ -191,7 +192,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ID INT(11) NOT NULL AUTO_INCREMENT, PROFILE_ID INT(11) NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , TENANT_ID INT(11) NOT NULL , CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), @@ -308,7 +309,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID INT NOT NULL AUTO_INCREMENT, POLICY_ID INT NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , TENANT_ID INT(11) NOT NULL, PRIMARY KEY (ID) )ENGINE = InnoDB; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql index 18ed9c2abe..0b1256d5ee 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/oracle.sql @@ -250,13 +250,13 @@ CREATE TABLE DM_PROFILE ( ID NUMBER(10) NOT NULL , PROFILE_NAME VARCHAR2(45) NOT NULL , TENANT_ID NUMBER(10) NOT NULL , - DEVICE_TYPE_ID NUMBER(10) NOT NULL , + DEVICE_TYPE VARCHAR2(300) NOT NULL , CREATED_TIME TIMESTAMP(0) NOT NULL , UPDATED_TIME TIMESTAMP(0) NOT NULL , CONSTRAINT PK_DM_PROFILE PRIMARY KEY (ID) , CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME ) ) / -- Generate ID using sequence and trigger @@ -338,15 +338,15 @@ WHEN (NEW.ID IS NULL) CREATE TABLE DM_DEVICE_TYPE_POLICY ( ID NUMBER(10) NOT NULL , - DEVICE_TYPE_ID NUMBER(10) NOT NULL , + DEVICE_TYPE VARCHAR2(300) NOT NULL , POLICY_ID NUMBER(10) NOT NULL , CONSTRAINT PK_DEV_TYPE_POLICY PRIMARY KEY (ID) , CONSTRAINT FK_DEV_TYPE_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID ), CONSTRAINT FK_DEV_TYPE_POLICY_DEV_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME ) ) / @@ -355,7 +355,7 @@ CREATE TABLE DM_PROFILE_FEATURES ( ID NUMBER(10) NOT NULL, PROFILE_ID NUMBER(10) NOT NULL, FEATURE_CODE VARCHAR2(100) NOT NULL, - DEVICE_TYPE_ID NUMBER(10) NOT NULL, + DEVICE_TYPE VARCHAR2(300) NOT NULL , TENANT_ID NUMBER(10) NOT NULL , CONTENT BLOB DEFAULT NULL NULL, CONSTRAINT PK_DM_PROF_DM_POLICY_FEATURES PRIMARY KEY (ID), @@ -566,7 +566,7 @@ WHEN (NEW.ID IS NULL) CREATE TABLE DM_POLICY_CHANGE_MGT ( ID NUMBER(10) NOT NULL, POLICY_ID NUMBER(10) NOT NULL, - DEVICE_TYPE_ID NUMBER(10) NOT NULL, + DEVICE_TYPE VARCHAR2(300) NOT NULL, TENANT_ID NUMBER(10) NOT NULL, CONSTRAINT PK_DM_POLICY_CHANGE_MGT PRIMARY KEY (ID) ) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index 2da059d3a7..dc3c6229f2 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -103,12 +103,12 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE ( ID BIGSERIAL NOT NULL PRIMARY KEY, PROFILE_NAME VARCHAR(45) NOT NULL , TENANT_ID INTEGER NOT NULL , - DEVICE_TYPE_ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , CREATED_TIME TIMESTAMP NOT NULL , UPDATED_TIME TIMESTAMP NOT NULL , CONSTRAINT DM_PROFILE_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME ) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -151,7 +151,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ID INTEGER NOT NULL, - DEVICE_TYPE_ID INTEGER NOT NULL , + DEVICE_TYPE VARCHAR(300) NOT NULL , POLICY_ID INTEGER NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY @@ -160,8 +160,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME ) ON DELETE NO ACTION ON UPDATE NO ACTION ); @@ -170,7 +170,7 @@ CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( ID BIGSERIAL NOT NULL PRIMARY KEY, PROFILE_ID INTEGER NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE_ID INT NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , TENANT_ID INTEGER NOT NULL , CONTENT BYTEA NULL DEFAULT NULL, CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES @@ -272,7 +272,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID BIGSERIAL NOT NULL PRIMARY KEY, POLICY_ID INTEGER NOT NULL, - DEVICE_TYPE_ID INTEGER NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, TENANT_ID INTEGER NOT NULL ); From 2ec9f68135eaaae156219cfdaaf48f827fdf09c6 Mon Sep 17 00:00:00 2001 From: dilanua Date: Tue, 2 Aug 2016 18:47:14 +0530 Subject: [PATCH 38/76] Removing the deprecation of operation.js as it seems to have one dependancy to plugins --- .../modules/business-controllers/operation.js | 234 +++++++++--------- 1 file changed, 115 insertions(+), 119 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js index 1e479286a9..e96ffcdec1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/operation.js @@ -16,123 +16,119 @@ * under the License. */ -/* - @Deprecated New - */ +var operationModule = function () { + var log = new Log("/app/modules/business-controllers/operation.js"); + var utility = require('/app/modules/utility.js').utility; + var constants = require('/app/modules/constants.js'); + var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; + var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; -//var operationModule = function () { -// var log = new Log("/app/modules/business-controllers/operation.js"); -// var utility = require('/app/modules/utility.js').utility; -// var constants = require('/app/modules/constants.js'); -// var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; -// var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; -// -// var publicMethods = {}; -// var privateMethods = {}; -// -// /** -// * This method reads the token from the Token client and return the access token. -// * If the token pair s not set in the session this will send a redirect to the login page. -// */ -// function getAccessToken(deviceType, owner, deviceId) { -// var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; -// var accessTokenClient = new TokenClient(deviceType); -// var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); -// return accessTokenInfo.getAccess_token(); -// } -// -// privateMethods.getOperationsFromFeatures = function (deviceType, operationType) { -// var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType; -// var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) { -// var features = responsePayload; -// var featureList = []; -// var feature; -// for (var i = 0; i < features.length; i++) { -// feature = {}; -// var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; -// if (analyticStreams) { -// for (var stream in analyticStreams) { -// if (analyticStreams[stream].name == features[i].name) { -// feature.ui_unit = analyticStreams[stream].ui_unit; -// break; -// } -// } -// } -// -// feature["operation"] = features[i].code; -// feature["name"] = features[i].name; -// feature["description"] = features[i].description; -// feature["deviceType"] = deviceType; -// feature["params"] = []; -// var metaData = features[i].metadataEntries; -// if (metaData) { -// for (var j = 0; j < metaData.length; j++) { -// feature["params"].push(metaData[j].value); -// } -// featureList.push(feature); -// } -// } -// return featureList; -// }, function (responsePayload) { -// var response = {}; -// response["status"] = "error"; -// return response; -// } -// ); -// return featuresList; -// }; -// -// publicMethods.getControlOperations = function (deviceType) { -// var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation"); -// for (var op in operations) { -// var iconPath = utility.getOperationIcon(deviceType, operations[op].operation); -// if (iconPath) { -// operations[op]["icon"] = iconPath; -// } -// } -// return operations; -// }; -// -// publicMethods.getMonitorOperations = function (deviceType) { -// return privateMethods.getOperationsFromFeatures(deviceType, "monitor"); -// }; -// -// publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) { -// var user = session.get(constants.USER_SESSION_KEY); -// var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; -// var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + -// '","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' + -// constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX + -// getAccessToken(deviceType, user.username, deviceId) + '"}'; -// return post(endPoint, params, JSON.parse(header), "json"); -// }; -// -// publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) { -// var user = session.get(constants.USER_SESSION_KEY); -// var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; -// var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + -// '","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' + -// constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) + -// '"}'; -// var result = get(endPoint, {}, JSON.parse(header), "json"); -// if (result.data) { -// var values = result.data.sensorValue.split(','); -// if (operationName == 'gps') { -// result.data.map = { -// lat: parseFloat(values[0]), -// lng: parseFloat(values[1]) -// } -// } else { -// var sqSum = 0; -// for (var v in values) { -// sqSum += Math.pow(values[v], 2); -// } -// result.data[operationName] = Math.sqrt(sqSum); -// } -// delete result.data['sensorValue']; -// } -// return result; -// }; -// -// return publicMethods; -//}(); \ No newline at end of file + var publicMethods = {}; + var privateMethods = {}; + + /** + * This method reads the token from the Token client and return the access token. + * If the token pair s not set in the session this will send a redirect to the login page. + */ + function getAccessToken(deviceType, owner, deviceId) { + var TokenClient = Packages.org.wso2.carbon.device.mgt.iot.apimgt.TokenClient; + var accessTokenClient = new TokenClient(deviceType); + var accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + return accessTokenInfo.getAccess_token(); + } + + privateMethods.getOperationsFromFeatures = function (deviceType, operationType) { + var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/features/" + deviceType; + var featuresList = serviceInvokers.XMLHttp.get(url, function (responsePayload) { + var features = responsePayload; + var featureList = []; + var feature; + for (var i = 0; i < features.length; i++) { + feature = {}; + var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"]; + if (analyticStreams) { + for (var stream in analyticStreams) { + if (analyticStreams[stream].name == features[i].name) { + feature.ui_unit = analyticStreams[stream].ui_unit; + break; + } + } + } + + feature["operation"] = features[i].code; + feature["name"] = features[i].name; + feature["description"] = features[i].description; + feature["deviceType"] = deviceType; + feature["params"] = []; + var metaData = features[i].metadataEntries; + if (metaData) { + for (var j = 0; j < metaData.length; j++) { + feature["params"].push(metaData[j].value); + } + featureList.push(feature); + } + } + return featureList; + }, function (responsePayload) { + var response = {}; + response["status"] = "error"; + return response; + } + ); + return featuresList; + }; + + publicMethods.getControlOperations = function (deviceType) { + var operations = privateMethods.getOperationsFromFeatures(deviceType, "operation"); + for (var op in operations) { + var iconPath = utility.getOperationIcon(deviceType, operations[op].operation); + if (iconPath) { + operations[op]["icon"] = iconPath; + } + } + return operations; + }; + + publicMethods.getMonitorOperations = function (deviceType) { + return privateMethods.getOperationsFromFeatures(deviceType, "monitor"); + }; + + publicMethods.handlePOSTOperation = function (deviceType, operation, deviceId, params) { + var user = session.get(constants.USER_SESSION_KEY); + var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; + var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + + '","protocol":"mqtt", "sessionId":"' + session.getId() + '", "' + + constants.AUTHORIZATION_HEADER + '":"' + constants.BEARER_PREFIX + + getAccessToken(deviceType, user.username, deviceId) + '"}'; + return post(endPoint, params, JSON.parse(header), "json"); + }; + + publicMethods.handleGETOperation = function (deviceType, operation, operationName, deviceId) { + var user = session.get(constants.USER_SESSION_KEY); + var endPoint = devicemgtProps["httpsURL"] + '/' + deviceType + "/controller/" + operation; + var header = '{"owner":"' + user.username + '","deviceId":"' + deviceId + + '","protocol":"mqtt", "' + constants.AUTHORIZATION_HEADER + '":"' + + constants.BEARER_PREFIX + getAccessToken(deviceType, user.username, deviceId) + + '"}'; + var result = get(endPoint, {}, JSON.parse(header), "json"); + if (result.data) { + var values = result.data.sensorValue.split(','); + if (operationName == 'gps') { + result.data.map = { + lat: parseFloat(values[0]), + lng: parseFloat(values[1]) + } + } else { + var sqSum = 0; + for (var v in values) { + sqSum += Math.pow(values[v], 2); + } + result.data[operationName] = Math.sqrt(sqSum); + } + delete result.data['sensorValue']; + } + return result; + }; + + return publicMethods; +}(); \ No newline at end of file From 160d8c2feb795174e67d593a13032dd45b24d410 Mon Sep 17 00:00:00 2001 From: kamidu Date: Tue, 2 Aug 2016 18:51:31 +0530 Subject: [PATCH 39/76] Fix the policy create wizard ui issues --- .../modules/business-controllers/policy.js | 293 +++++------------- .../units/cdmf.unit.policy.create/create.js | 10 +- 2 files changed, 91 insertions(+), 212 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js index 6cc38a9bfe..f569accf61 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/policy.js @@ -1,24 +1,21 @@ /* - * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -/* - @Refactored - */ var policyModule; policyModule = function () { var log = new Log("/app/modules/business-controllers/policy.js"); @@ -31,118 +28,90 @@ policyModule = function () { var publicMethods = {}; var privateMethods = {}; - privateMethods.handleGetAllPoliciesError = function (responsePayload) { + privateMethods.handleGetAllPoliciesResponse = function (backendResponse) { var response = {}; - response.status = "error"; - /* responsePayload == "Scope validation failed" - Here the response.context("Scope validation failed") is used other then response.status(401). - Reason for this is IDP return 401 as the status in 4 different situations such as, - 1. UnAuthorized. - 2. Scope Validation Failed. - 3. Permission Denied. - 4. Access Token Expired. - 5. Access Token Invalid. - In these cases in order to identify the correct situation we have to compare the unique value from status and - context which is context. - */ - if (responsePayload == "Scope validation failed") { - response.content = "Permission Denied"; - } else { - response.content = responsePayload; - } - return response; - }; + if (backendResponse.status == 200 && backendResponse.responseText) { + var isUpdated = false; + var policyListFromRestEndpoint = parse(backendResponse.responseText)["policies"]; - privateMethods.handleGetAllPoliciesSuccess = function (responsePayload) { - var isUpdated = false; - var policyListFromRestEndpoint = responsePayload["responseContent"]; - var policyListToView = []; - var i, policyObjectFromRestEndpoint, policyObjectToView; - for (i = 0; i < policyListFromRestEndpoint.length; i++) { - // get list object - policyObjectFromRestEndpoint = policyListFromRestEndpoint[i]; - // populate list object values to view-object - policyObjectToView = {}; - policyObjectToView["id"] = policyObjectFromRestEndpoint["id"]; - policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; - policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; - policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]["name"]; - policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); - policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; - policyObjectToView["roles"] = privateMethods. - getElementsInAString(policyObjectFromRestEndpoint["roles"]); - policyObjectToView["users"] = privateMethods. - getElementsInAString(policyObjectFromRestEndpoint["users"]); - policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"]; + var policyListToView = []; + var i, policyObjectFromRestEndpoint, policyObjectToView; + for (i = 0; i < policyListFromRestEndpoint.length; i++) { + // get list object + policyObjectFromRestEndpoint = policyListFromRestEndpoint[i]; + // populate list object values to view-object + policyObjectToView = {}; + policyObjectToView["id"] = policyObjectFromRestEndpoint["id"]; + policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; + policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; + policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]; + policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; - if (policyObjectFromRestEndpoint["active"] == true && policyObjectFromRestEndpoint["updated"] == true) { - policyObjectToView["status"] = "Active/Updated"; - isUpdated = true; - } else if (policyObjectFromRestEndpoint["active"] == true && - policyObjectFromRestEndpoint["updated"] == false) { - policyObjectToView["status"] = "Active"; - } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == true) { - policyObjectToView["status"] = "Inactive/Updated"; - isUpdated = true; - } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == false) { - policyObjectToView["status"] = "Inactive"; - } - // push view-objects to list - policyListToView.push(policyObjectToView); - } - // generate response - var response = {}; - response.updated = isUpdated; - response.status = "success"; - response.content = policyListToView; - return response; - }; + var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length; + var assignedUserCount = policyObjectFromRestEndpoint["users"].length; - publicMethods.addPolicy = function (policyName, deviceType, policyDefinition, policyDescription, - deviceId) { - var carbonUser = session.get(constants["USER_SESSION_KEY"]); - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants["ERRORS"]["USER_NOT_FOUND"]; - } - if (policyName && deviceType) { - var queName = "WSO2IoTServer/" + carbonUser.username + "/" + deviceType; - var deviceQueName; - if (deviceId) { - deviceQueName = queName + "/" + deviceId; - privateMethods.publish(deviceQueName, policyName, deviceType, policyDefinition); - } else { - var deviceManagementService = utility.getDeviceManagementService(); - var devices = deviceManagementService.getDevicesOfUser(carbonUser.username); - var device; - for (var i = 0; i < devices.size(); i++) { - device = devices.get(i); - deviceId = device.getDeviceIdentifier(); - deviceQueName = queName + "/" + deviceId; - privateMethods.publish(deviceQueName, policyName, deviceType, policyDefinition); + if (assignedRoleCount == 0) { + policyObjectToView["roles"] = "None"; + } else if (assignedRoleCount == 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0]; + } else if (assignedRoleCount > 1) { + policyObjectToView["roles"] = policyObjectFromRestEndpoint["roles"][0] + ", ..."; } + + if (assignedUserCount == 0) { + policyObjectToView["users"] = "None"; + } else if (assignedUserCount == 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0]; + } else if (assignedUserCount > 1) { + policyObjectToView["users"] = policyObjectFromRestEndpoint["users"][0] + ", ..."; + } + + policyObjectToView["compliance"] = policyObjectFromRestEndpoint["compliance"]; + + if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Active/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == true && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Active"; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == true) { + policyObjectToView["status"] = "Inactive/Updated"; + isUpdated = true; + } else if (policyObjectFromRestEndpoint["active"] == false && + policyObjectFromRestEndpoint["updated"] == false) { + policyObjectToView["status"] = "Inactive"; + } + // push view-objects to list + policyListToView.push(policyObjectToView); } - return true; + // generate response + response.updated = isUpdated; + response.status = "success"; + response.content = policyListToView; + + return response; + } else { + response.status = "error"; + /* backendResponse.responseText == "Scope validation failed" + Here the response.context("Scope validation failed") is used other then response.status(401). + Reason for this is IDP return 401 as the status in 4 different situations such as, + 1. UnAuthorized. + 2. Scope Validation Failed. + 3. Permission Denied. + 4. Access Token Expired. + 5. Access Token Invalid. + In these cases in order to identify the correct situation we have to compare the unique value from status and + context which is context. + */ + if (backendResponse.responseText == "Scope validation failed") { + response.content = "Permission Denied"; + } else { + response.content = backendResponse.responseText; + } + return response; } - return false; - }; - - privateMethods.publish = function (queName, policyName, deviceType, policyDefinition) { - var configurationService = utility.getConfigurationService(); - var mqttEndPointDeviceConfig = configurationService.getControlQueue(constants.MQTT_QUEUE_CONFIG_NAME); - var mqttBrokerURL = mqttEndPointDeviceConfig.getServerURL(); - var mqttBrokerPort = mqttEndPointDeviceConfig.getPort(); - var mqttQueueEndpoint = mqttBrokerURL + ":" + mqttBrokerPort; - - var mqttsenderClass = Packages.org.wso2.carbon.device.mgt.iot.mqtt.PolicyPush; - var mqttsender = new mqttsenderClass(); - - var policyPayload = "POLICY:" + policyDefinition; - var result = mqttsender.pushToMQTT(queName, policyPayload, mqttQueueEndpoint, "MQTT_Agent"); - mqttsender = null; - return result; }; /* @@ -155,9 +124,9 @@ policyModule = function () { throw constants["ERRORS"]["USER_NOT_FOUND"]; } try { - var url = devicemgtProps["httpsURL"] + constants.ADMIN_SERVICE_CONTEXT + "/policies"; - return serviceInvokers.XMLHttp. - get(url, privateMethods.handleGetAllPoliciesSuccess, privateMethods.handleGetAllPoliciesError); + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/policies?offset=0&limit=100"; + return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse); } catch (e) { throw e; } @@ -178,97 +147,5 @@ policyModule = function () { return elementsInAString; }; - /* - @Deprecated - */ - publicMethods.getProfiles = function () { - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var policyManagementService = utility.getPolicyManagementService(); - var policyAdminPoint = policyManagementService.getPAP(); - var profiles = policyAdminPoint.getProfiles(); - var profileList = []; - var i, profile, profileObject; - for (i = 0; i < profiles.size(); i++) { - profile = profiles.get(i); - profileObject = {}; - profileObject.name = profile.getProfileName(); - profileObject.id = profile.getProfileId(); - profileList.push(profileObject); - } - return profileList; - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Deprecated - */ - publicMethods.updatePolicyPriorities = function (payload) { - var carbonUser = session.get(constants.USER_SESSION_KEY); - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var policyManagementService = utility.getPolicyManagementService(); - var policyAdminPoint = policyManagementService.getPAP(); - var policyCount = payload.length; - var policyList = new java.util.ArrayList(); - var i, policyObject; - for (i = 0; i < policyCount; i++) { - policyObject = new Policy(); - policyObject.setId(payload[i].id); - policyObject.setPriorityId(payload[i].priority); - policyList.add(policyObject); - } - policyAdminPoint.updatePolicyPriorities(policyList); - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - - /* - @Deprecated - */ - publicMethods.deletePolicy = function (policyId) { - var isDeleted; - var carbonUser = session.get(constants.USER_SESSION_KEY); - var utility = require('/app/modules/utility.js').utility; - if (!carbonUser) { - log.error("User object was not found in the session"); - throw constants.ERRORS.USER_NOT_FOUND; - } - try { - utility.startTenantFlow(carbonUser); - var policyManagementService = utility.getPolicyManagementService(); - var policyAdminPoint = policyManagementService.getPAP(); - isDeleted = policyAdminPoint.deletePolicy(policyId); - if (isDeleted) { - // http status code 200 refers to - success. - return 200; - } else { - // http status code 409 refers to - conflict. - return 409; - } - } catch (e) { - throw e; - } finally { - utility.endTenantFlow(); - } - }; - return publicMethods; -}(); +}(); \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js index cf46e20def..28142c13eb 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js @@ -28,7 +28,9 @@ function onRequest(context) { var typesListResponse = userModule.getPlatforms(); if (typesListResponse["status"] == "success") { for (var type in typesListResponse["content"]) { - var deviceType = typesListResponse["content"][type]["name"]; + var content = {}; + var deviceType = typesListResponse["content"]["deviceTypes"][type]; + content["name"] = deviceType; var configs = utility.getDeviceTypeConfig(deviceType); var deviceTypeLabel = deviceType; if (configs && configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) { @@ -36,9 +38,9 @@ function onRequest(context) { } var policyWizard = new File("/app/units/" + utility.getTenantedDeviceUnitName(deviceType, "policy-wizard")); if(policyWizard.isExists()){ - typesListResponse["content"][type]["icon"] = utility.getDeviceThumb(deviceType); - typesListResponse["content"][type]["label"] = deviceTypeLabel; - types["types"].push(typesListResponse["content"][type]); + content["icon"] = utility.getDeviceThumb(deviceType); + content["label"] = deviceTypeLabel; + types["types"].push(content); } } } From d315e739e46aade0eb6542f7e0bcd2aa2f3a20a1 Mon Sep 17 00:00:00 2001 From: madhawap Date: Tue, 2 Aug 2016 19:04:28 +0530 Subject: [PATCH 40/76] fix for the iOS device operations blocker --- .../device/mgt/common/DeviceTypeIdentifier.java | 4 ++-- .../mgt/core/DeviceManagementPluginRepository.java | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java index 1eb5e28e46..1849a97c0d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceTypeIdentifier.java @@ -29,12 +29,12 @@ public class DeviceTypeIdentifier implements Serializable { private static final int DEFAULT_SHARE_WITH_ALL_TENANTS_ID = -1; public DeviceTypeIdentifier(String deviceType, int tenantId) { - this.deviceType = deviceType; + this.deviceType = deviceType.toLowerCase(); this.tenantId = tenantId; } public DeviceTypeIdentifier(String deviceType) { - this.deviceType = deviceType; + this.deviceType = deviceType.toLowerCase(); this.tenantId = DEFAULT_SHARE_WITH_ALL_TENANTS_ID; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index d55f553920..e117242a92 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -52,7 +52,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceType = provider.getType(); + String deviceType = provider.getType().toLowerCase(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); String tenantDomain = provisioningConfig.getProviderTenantDomain(); @@ -87,7 +87,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis } public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException { - String deviceTypeName = provider.getType(); + String deviceTypeName = provider.getType().toLowerCase(); DeviceTypeIdentifier deviceTypeIdentifier; ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); if (provisioningConfig.isSharedWithAllTenants()) { @@ -103,10 +103,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public DeviceManagementService getDeviceManagementService(String type, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type, tenantId); + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase(), tenantId); DeviceManagementService provider = providers.get(deviceTypeIdentifier); if (provider == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(type); + deviceTypeIdentifier = new DeviceTypeIdentifier(type.toLowerCase()); provider = providers.get(deviceTypeIdentifier); } return provider; @@ -153,10 +153,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis public OperationManager getOperationManager(String deviceType, int tenantId) { //Priority need to be given to the tenant before public. - DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType, tenantId); + DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase(), tenantId); OperationManager operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); if (operationManager == null) { - deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType); + deviceTypeIdentifier = new DeviceTypeIdentifier(deviceType.toLowerCase()); operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier); } return operationManager; From 5bd879545baa5d01524260742a9cc96265160a8c Mon Sep 17 00:00:00 2001 From: madhawap Date: Tue, 2 Aug 2016 19:45:39 +0530 Subject: [PATCH 41/76] fix for the iOS device operations blocker --- .../device/mgt/core/DeviceManagementPluginRepository.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java index e117242a92..504d29d5f1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementPluginRepository.java @@ -164,14 +164,15 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis @Override public void notifyObserver() { + String deviceTypeName; synchronized (providers) { for (DeviceManagementService provider : providers.values()) { try { provider.init(); - + deviceTypeName = provider.getType().toLowerCase(); ProvisioningConfig provisioningConfig = provider.getProvisioningConfig(); int tenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain()); - DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provisioningConfig.isSharedWithAllTenants()); + DeviceManagerUtil.registerDeviceType(deviceTypeName, tenantId, provisioningConfig.isSharedWithAllTenants()); registerPushNotificationStrategy(provider); //TODO: //This is a temporory fix. From ed4c762bfd3f61f19af4936b333a8d68beda21c5 Mon Sep 17 00:00:00 2001 From: mharindu Date: Thu, 4 Aug 2016 17:46:46 +0530 Subject: [PATCH 42/76] 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 32fb410da40d7942199b182e41a7acfe91507569 Mon Sep 17 00:00:00 2001 From: madhawap Date: Thu, 4 Aug 2016 18:15:45 +0530 Subject: [PATCH 43/76] mysql db script related changes --- .../resources/dbscripts/cdm/certs/mssql.sql | 6 +- .../main/resources/dbscripts/cdm/mssql.sql | 567 +++++++++--------- 2 files changed, 299 insertions(+), 274 deletions(-) diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql index 888ee030c8..6c377c68f6 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql @@ -1,7 +1,7 @@ -CREATE TABLE DM_DEVICE_CERTIFICATE ( - ID INTEGER IDENTITY NOT NULL, +CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( + ID INTEGER auto_increment NOT NULL, SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE VARBINARY(max) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, TENANT_ID INTEGER DEFAULT 0, USERNAME VARCHAR(500) DEFAULT NULL, PRIMARY KEY (ID) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql index 385ac2a135..85cf0b078b 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mssql.sql @@ -1,183 +1,165 @@ -CREATE TABLE DM_DEVICE_TYPE ( - ID INTEGER IDENTITY NOT NULL, - NAME VARCHAR(300) DEFAULT NULL, - PROVIDER_TENANT_ID INTEGER DEFAULT 0, - SHARED_WITH_ALL_TENANTS INTEGER NOT NULL DEFAULT 0, - PRIMARY KEY (ID) -); -CREATE TABLE DM_GROUP ( - ID INTEGER IDENTITY NOT NULL, - GROUP_NAME VARCHAR(100) DEFAULT NULL, - DESCRIPTION VARCHAR(max) DEFAULT NULL, - DATE_OF_CREATE BIGINT DEFAULT NULL, - DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, - OWNER VARCHAR(45) DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID) -); -CREATE TABLE DM_DEVICE ( - ID INTEGER identity NOT NULL, - DESCRIPTION VARCHAR(max) DEFAULT NULL, +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( + ID INT AUTO_INCREMENT NOT NULL, + NAME VARCHAR(300) DEFAULT NULL, + PROVIDER_TENANT_ID INTEGER DEFAULT 0, + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, + PRIMARY KEY (ID) +)ENGINE = InnoDB; +CREATE INDEX device_type_name ON DM_DEVICE_TYPE (NAME); + +CREATE TABLE IF NOT EXISTS DM_DEVICE ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DESCRIPTION TEXT DEFAULT NULL, NAME VARCHAR(100) DEFAULT NULL, - DEVICE_TYPE_ID INTEGER DEFAULT NULL, + DEVICE_TYPE_ID INT(11) DEFAULT NULL, DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL, LAST_UPDATED_TIMESTAMP TIMESTAMP NOT NULL, TENANT_ID INTEGER DEFAULT 0, PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID ) - REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); + CONSTRAINT fk_DM_DEVICE_DM_DEVICE_TYPE2 FOREIGN KEY (DEVICE_TYPE_ID) + REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uk_DM_DEVICE UNIQUE (NAME, DEVICE_TYPE_ID, DEVICE_IDENTIFICATION, TENANT_ID) +)ENGINE = InnoDB; -CREATE TABLE DM_DEVICE_GROUP_MAP ( - ID INTEGER IDENTITY NOT NULL, - DEVICE_ID INTEGER DEFAULT NULL, - GROUP_ID INTEGER DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - PRIMARY KEY (ID), - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) - REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, - CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) - REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); -CREATE TABLE DM_OPERATION ( - ID INTEGER IDENTITY NOT NULL, +CREATE TABLE IF NOT EXISTS DM_OPERATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, TYPE VARCHAR(50) NOT NULL, - CREATED_TIMESTAMP DATETIME2(0) NOT NULL, - RECEIVED_TIMESTAMP DATETIME2(0) NULL, + CREATED_TIMESTAMP TIMESTAMP NOT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, OPERATION_CODE VARCHAR(1000) NOT NULL, PRIMARY KEY (ID) -); +)ENGINE = InnoDB; -CREATE TABLE DM_CONFIG_OPERATION ( + +CREATE TABLE IF NOT EXISTS DM_CONFIG_OPERATION ( OPERATION_ID INTEGER NOT NULL, - OPERATION_CONFIG VARBINARY(max) DEFAULT NULL, + OPERATION_CONFIG BLOB DEFAULT NULL, PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_config FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT FK_DM_OPERATION_CONFIG FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_COMMAND_OPERATION ( + +CREATE TABLE IF NOT EXISTS DM_COMMAND_OPERATION ( OPERATION_ID INTEGER NOT NULL, - ENABLED BIT NOT NULL DEFAULT 'FALSE', + ENABLED BOOLEAN NOT NULL DEFAULT FALSE, PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_command FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT FK_DM_OPERATION_COMMAND FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_POLICY_OPERATION ( + +CREATE TABLE IF NOT EXISTS DM_POLICY_OPERATION ( OPERATION_ID INTEGER NOT NULL, ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS VARBINARY(max) DEFAULT NULL, + OPERATION_DETAILS BLOB DEFAULT NULL, PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_policy FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT FK_DM_OPERATION_POLICY FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_PROFILE_OPERATION ( + +CREATE TABLE IF NOT EXISTS DM_PROFILE_OPERATION ( OPERATION_ID INTEGER NOT NULL, ENABLED INTEGER NOT NULL DEFAULT 0, - OPERATION_DETAILS VARBINARY(max) DEFAULT NULL, + OPERATION_DETAILS BLOB DEFAULT NULL, PRIMARY KEY (OPERATION_ID), - CONSTRAINT fk_dm_operation_profile FOREIGN KEY (OPERATION_ID) REFERENCES + CONSTRAINT FK_DM_OPERATION_PROFILE FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_ENROLMENT ( - ID INTEGER IDENTITY NOT NULL, + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, OWNER VARCHAR(50) NOT NULL, OWNERSHIP VARCHAR(45) DEFAULT NULL, STATUS VARCHAR(50) NULL, - DATE_OF_ENROLMENT DATETIME2(0) DEFAULT NULL, - DATE_OF_LAST_UPDATE DATETIME2(0) DEFAULT NULL, - TENANT_ID INTEGER NOT NULL, + DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, + TENANT_ID INT NOT NULL, PRIMARY KEY (ID), - CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES - DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); + CONSTRAINT FK_DM_DEVICE_ENROLMENT FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT uk_dm_device_enrolment UNIQUE (DEVICE_ID, OWNER, OWNERSHIP, TENANT_ID) +)ENGINE = InnoDB; -CREATE TABLE DM_ENROLMENT_OP_MAPPING ( - ID INTEGER IDENTITY NOT NULL, + +CREATE TABLE IF NOT EXISTS DM_ENROLMENT_OP_MAPPING ( + ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, STATUS VARCHAR(50) NULL, - CREATED_TIMESTAMP INTEGER NOT NULL, - UPDATED_TIMESTAMP INTEGER NOT NULL, + CREATED_TIMESTAMP INT NOT NULL, + UPDATED_TIMESTAMP INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_mapping_device FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_mapping_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_DEVICE_OPERATION_RESPONSE ( - ID INTEGER IDENTITY NOT NULL, + +CREATE TABLE IF NOT EXISTS DM_DEVICE_OPERATION_RESPONSE ( + ID INTEGER AUTO_INCREMENT NOT NULL, ENROLMENT_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, - OPERATION_RESPONSE VARBINARY(max) DEFAULT NULL, - RECEIVED_TIMESTAMP DATETIME2(0) NULL, + OPERATION_RESPONSE BLOB DEFAULT NULL, + RECEIVED_TIMESTAMP TIMESTAMP NULL, PRIMARY KEY (ID), CONSTRAINT fk_dm_device_operation_response_enrollment FOREIGN KEY (ENROLMENT_ID) REFERENCES DM_ENROLMENT (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_device_operation_response_operation FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -- POLICY RELATED TABLES -- - - - -CREATE TABLE DM_PROFILE ( - ID INTEGER NOT NULL IDENTITY , +CREATE TABLE IF NOT EXISTS DM_PROFILE ( + ID INT NOT NULL AUTO_INCREMENT , PROFILE_NAME VARCHAR(45) NOT NULL , - TENANT_ID INTEGER NOT NULL , + TENANT_ID INT NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - CREATED_TIME DATETIME2(0) NOT NULL , - UPDATED_TIME DATETIME2(0) NOT NULL , + CREATED_TIME DATETIME NOT NULL , + UPDATED_TIME DATETIME NOT NULL , PRIMARY KEY (ID) , CONSTRAINT DM_PROFILE_DEVICE_TYPE FOREIGN KEY (DEVICE_TYPE) - REFERENCES DM_DEVICE_TYPE (NAME ) + REFERENCES DM_DEVICE_TYPE (NAME) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - - -CREATE TABLE DM_POLICY ( - ID INTEGER NOT NULL IDENTITY , +CREATE TABLE IF NOT EXISTS DM_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , NAME VARCHAR(45) DEFAULT NULL , DESCRIPTION VARCHAR(1000) NULL, - TENANT_ID INTEGER NOT NULL , - PROFILE_ID INTEGER NOT NULL , + TENANT_ID INT(11) NOT NULL , + PROFILE_ID INT(11) NOT NULL , OWNERSHIP_TYPE VARCHAR(45) NULL, COMPLIANCE VARCHAR(100) NULL, - PRIORITY INTEGER NOT NULL, - ACTIVE INTEGER NOT NULL, - UPDATED INTEGER NULL, + PRIORITY INT NOT NULL, + ACTIVE INT(2) NOT NULL, + UPDATED INT(1) NULL, PRIMARY KEY (ID) , CONSTRAINT FK_DM_PROFILE_DM_POLICY FOREIGN KEY (PROFILE_ID ) REFERENCES DM_PROFILE (ID ) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - -CREATE TABLE DM_DEVICE_POLICY ( - ID INTEGER NOT NULL IDENTITY , - DEVICE_ID INTEGER NOT NULL , - ENROLMENT_ID INTEGER NOT NULL, - DEVICE VARBINARY(max) NOT NULL, - POLICY_ID INTEGER NOT NULL , +CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , + DEVICE_ID INT(11) NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + DEVICE BLOB NOT NULL, + POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_POLICY_DEVICE_POLICY FOREIGN KEY (POLICY_ID ) @@ -189,15 +171,13 @@ CREATE TABLE DM_DEVICE_POLICY ( REFERENCES DM_DEVICE (ID ) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - -CREATE TABLE DM_DEVICE_TYPE_POLICY ( - ID INTEGER NOT NULL , +CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE_POLICY ( + ID INT(11) NOT NULL , DEVICE_TYPE VARCHAR(300) NOT NULL , - POLICY_ID INTEGER NOT NULL , + POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DEVICE_TYPE_POLICY FOREIGN KEY (POLICY_ID ) @@ -205,52 +185,45 @@ CREATE TABLE DM_DEVICE_TYPE_POLICY ( ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT FK_DEVICE_TYPE_POLICY_DEVICE_TYPE - FOREIGN KEY (DEVICE_TYPE) - REFERENCES DM_DEVICE_TYPE (NAME ) + FOREIGN KEY (DEVICE_TYPE ) + REFERENCES DM_DEVICE_TYPE (NAME) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - - -CREATE TABLE DM_PROFILE_FEATURES ( - ID INTEGER NOT NULL IDENTITY, - PROFILE_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_PROFILE_FEATURES ( + ID INT(11) NOT NULL AUTO_INCREMENT, + PROFILE_ID INT(11) NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL , - TENANT_ID INTEGER NOT NULL , - CONTENT VARBINARY(max) NULL DEFAULT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, + TENANT_ID INT(11) NOT NULL , + CONTENT BLOB NULL DEFAULT NULL, PRIMARY KEY (ID), CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES FOREIGN KEY (PROFILE_ID) REFERENCES DM_PROFILE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - -CREATE TABLE DM_ROLE_POLICY ( - ID INTEGER NOT NULL IDENTITY , +CREATE TABLE IF NOT EXISTS DM_ROLE_POLICY ( + ID INT(11) NOT NULL AUTO_INCREMENT , ROLE_NAME VARCHAR(45) NOT NULL , - POLICY_ID INTEGER NOT NULL , + POLICY_ID INT(11) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT FK_ROLE_POLICY_POLICY FOREIGN KEY (POLICY_ID ) REFERENCES DM_POLICY (ID ) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - - -CREATE TABLE DM_USER_POLICY ( - ID INTEGER NOT NULL IDENTITY , - POLICY_ID INTEGER NOT NULL , +CREATE TABLE IF NOT EXISTS DM_USER_POLICY ( + ID INT NOT NULL AUTO_INCREMENT , + POLICY_ID INT NOT NULL , USERNAME VARCHAR(45) NOT NULL , PRIMARY KEY (ID) , CONSTRAINT DM_POLICY_USER_POLICY @@ -258,43 +231,41 @@ CREATE TABLE DM_USER_POLICY ( REFERENCES DM_POLICY (ID ) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - CREATE TABLE DM_DEVICE_POLICY_APPLIED ( - ID INTEGER NOT NULL IDENTITY , - DEVICE_ID INTEGER NOT NULL , - ENROLMENT_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL , - POLICY_CONTENT VARBINARY(max) NULL , - TENANT_ID INTEGER NOT NULL, - APPLIED SMALLINT NULL , - CREATED_TIME DATETIME2(0) NULL , - UPDATED_TIME DATETIME2(0) NULL , - APPLIED_TIME DATETIME2(0) NULL , + CREATE TABLE IF NOT EXISTS DM_DEVICE_POLICY_APPLIED ( + ID INT NOT NULL AUTO_INCREMENT , + DEVICE_ID INT NOT NULL , + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL , + POLICY_CONTENT BLOB NULL , + TENANT_ID INT NOT NULL, + APPLIED TINYINT(1) NULL , + CREATED_TIME TIMESTAMP NULL , + UPDATED_TIME TIMESTAMP NULL , + APPLIED_TIME TIMESTAMP NULL , PRIMARY KEY (ID) , CONSTRAINT FK_DM_POLICY_DEVCIE_APPLIED FOREIGN KEY (DEVICE_ID ) REFERENCES DM_DEVICE (ID ) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; - -CREATE TABLE DM_CRITERIA ( - ID INTEGER NOT NULL IDENTITY, - TENANT_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_CRITERIA ( + ID INT NOT NULL AUTO_INCREMENT, + TENANT_ID INT NOT NULL, NAME VARCHAR(50) NULL, PRIMARY KEY (ID) -); +)ENGINE = InnoDB; - -CREATE TABLE DM_POLICY_CRITERIA ( - ID INTEGER NOT NULL IDENTITY, - CRITERIA_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA ( + ID INT NOT NULL AUTO_INCREMENT, + CRITERIA_ID INT NOT NULL, + POLICY_ID INT NOT NULL, PRIMARY KEY (ID), CONSTRAINT FK_CRITERIA_POLICY_CRITERIA FOREIGN KEY (CRITERIA_ID) @@ -306,80 +277,80 @@ CREATE TABLE DM_POLICY_CRITERIA ( REFERENCES DM_POLICY (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_POLICY_CRITERIA_PROPERTIES ( - ID INTEGER NOT NULL IDENTITY, - POLICY_CRITERION_ID INTEGER NOT NULL, + +CREATE TABLE IF NOT EXISTS DM_POLICY_CRITERIA_PROPERTIES ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_CRITERION_ID INT NOT NULL, PROP_KEY VARCHAR(45) NULL, PROP_VALUE VARCHAR(100) NULL, - CONTENT VARBINARY(max) NULL , + CONTENT BLOB NULL COMMENT 'This is used to ', PRIMARY KEY (ID), CONSTRAINT FK_POLICY_CRITERIA_PROPERTIES FOREIGN KEY (POLICY_CRITERION_ID) REFERENCES DM_POLICY_CRITERIA (ID) ON DELETE CASCADE ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_POLICY_COMPLIANCE_STATUS ( - ID INTEGER NOT NULL IDENTITY, - DEVICE_ID INTEGER NOT NULL, - ENROLMENT_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - STATUS INTEGER NULL, - LAST_SUCCESS_TIME DATETIME2(0) NULL, - LAST_REQUESTED_TIME DATETIME2(0) NULL, - LAST_FAILED_TIME DATETIME2(0) NULL, - ATTEMPTS INTEGER NULL, + +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, + ENROLMENT_ID INT(11) NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + STATUS INT NULL, + LAST_SUCCESS_TIME TIMESTAMP NULL, + LAST_REQUESTED_TIME TIMESTAMP NULL, + LAST_FAILED_TIME TIMESTAMP NULL, + ATTEMPTS INT NULL, PRIMARY KEY (ID) -); +)ENGINE = InnoDB; -CREATE TABLE DM_POLICY_CHANGE_MGT ( - ID INTEGER NOT NULL IDENTITY, - POLICY_ID INTEGER NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL, - TENANT_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( + ID INT NOT NULL AUTO_INCREMENT, + POLICY_ID INT NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL , + TENANT_ID INT(11) NOT NULL, PRIMARY KEY (ID) -); +)ENGINE = InnoDB; -CREATE TABLE DM_POLICY_COMPLIANCE_FEATURES ( - ID INTEGER NOT NULL IDENTITY, - COMPLIANCE_STATUS_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( + ID INT NOT NULL AUTO_INCREMENT, + COMPLIANCE_STATUS_ID INT NOT NULL, + TENANT_ID INT NOT NULL, FEATURE_CODE VARCHAR(100) NOT NULL, - STATUS INTEGER NULL, + STATUS INT NULL, PRIMARY KEY (ID), CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS FOREIGN KEY (COMPLIANCE_STATUS_ID) REFERENCES DM_POLICY_COMPLIANCE_STATUS (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -CREATE TABLE DM_DEVICE_GROUP_POLICY ( - ID INTEGER NOT NULL IDENTITY, - DEVICE_GROUP_ID INTEGER NOT NULL, - POLICY_ID INTEGER NOT NULL, - TENANT_ID INTEGER NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_DEVICE_GROUP_POLICY - FOREIGN KEY (DEVICE_GROUP_ID) - REFERENCES DM_GROUP (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, - CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY - FOREIGN KEY (POLICY_ID) - REFERENCES DM_POLICY (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION -); -CREATE TABLE DM_APPLICATION ( - ID INTEGER IDENTITY NOT NULL, +CREATE TABLE IF NOT EXISTS DM_ENROLMENT ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER NOT NULL, + OWNER VARCHAR(50) NOT NULL, + OWNERSHIP VARCHAR(45) DEFAULT NULL, + STATUS VARCHAR(50) NULL, + DATE_OF_ENROLMENT TIMESTAMP NULL DEFAULT NULL, + DATE_OF_LAST_UPDATE TIMESTAMP NULL DEFAULT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES + DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +)ENGINE = InnoDB; + + +CREATE TABLE IF NOT EXISTS DM_APPLICATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, NAME VARCHAR(150) NOT NULL, APP_IDENTIFIER VARCHAR(150) NOT NULL, PLATFORM VARCHAR(50) DEFAULT NULL, @@ -388,15 +359,16 @@ CREATE TABLE DM_APPLICATION ( TYPE VARCHAR(50) NULL, LOCATION_URL VARCHAR(100) DEFAULT NULL, IMAGE_URL VARCHAR(100) DEFAULT NULL, - APP_PROPERTIES VARBINARY(max) NULL, - MEMORY_USAGE INTEGER NULL, - IS_ACTIVE BIT NOT NULL DEFAULT 'FALSE', + APP_PROPERTIES BLOB NULL, + MEMORY_USAGE INTEGER(10) NULL, + IS_ACTIVE BOOLEAN NOT NULL DEFAULT FALSE, TENANT_ID INTEGER NOT NULL, PRIMARY KEY (ID) -); +)ENGINE = InnoDB; -CREATE TABLE DM_DEVICE_APPLICATION_MAPPING ( - ID INTEGER IDENTITY NOT NULL, + +CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( + ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, APPLICATION_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL, @@ -405,13 +377,44 @@ CREATE TABLE DM_DEVICE_APPLICATION_MAPPING ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_application FOREIGN KEY (APPLICATION_ID) REFERENCES DM_APPLICATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +)ENGINE = InnoDB; -- POLICY RELATED TABLES FINISHED -- --- NOTIFICATION TABLE -- -CREATE TABLE DM_NOTIFICATION ( - NOTIFICATION_ID INTEGER IDENTITY NOT NULL, +-- DEVICE GROUP TABLES -- + +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION TEXT DEFAULT NULL, + DATE_OF_CREATE BIGINT DEFAULT NULL, + DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID) +)ENGINE = InnoDB; + + + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + PRIMARY KEY (ID), + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +)ENGINE = InnoDB; + +-- END OF DEVICE GROUP TABLES -- + + +-- NOTIFICATION TABLES -- + +CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( + NOTIFICATION_ID INTEGER AUTO_INCREMENT NOT NULL, DEVICE_ID INTEGER NOT NULL, OPERATION_ID INTEGER NOT NULL, TENANT_ID INTEGER NOT NULL, @@ -422,58 +425,59 @@ CREATE TABLE DM_NOTIFICATION ( DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk_dm_operation_notification FOREIGN KEY (OPERATION_ID) REFERENCES DM_OPERATION (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); --- NOTIFICATION TABLE END -- +)ENGINE = InnoDB; -IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_INFO' and type = 'u') - DROP TABLE DM_DEVICE_INFO; +-- END NOTIFICATION TABLES -- -CREATE TABLE DM_DEVICE_INFO ( - ID INTEGER IDENTITY NOT NULL, - DEVICE_ID INTEGER NULL, + +DROP TABLE IF EXISTS DM_DEVICE_INFO; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, KEY_FIELD VARCHAR(45) NULL, VALUE_FIELD VARCHAR(100) NULL, PRIMARY KEY (ID), + INDEX DM_DEVICE_INFO_DEVICE_idx (DEVICE_ID ASC), CONSTRAINT DM_DEVICE_INFO_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +) +ENGINE = InnoDB; -CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC); -IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_LOCATION' and type = 'u') - DROP TABLE DM_DEVICE_LOCATION; -CREATE TABLE DM_DEVICE_LOCATION ( - ID INTEGER IDENTITY NOT NULL, - DEVICE_ID INTEGER NULL, - LATITUDE FLOAT NULL, - LONGITUDE FLOAT NULL, +DROP TABLE IF EXISTS DM_DEVICE_LOCATION; + +CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION ( + ID INTEGER AUTO_INCREMENT NOT NULL, + DEVICE_ID INT NULL, + LATITUDE DOUBLE NULL, + LONGITUDE DOUBLE NULL, STREET1 VARCHAR(45) NULL, STREET2 VARCHAR(45) NULL, CITY VARCHAR(45) NULL, ZIP VARCHAR(10) NULL, STATE VARCHAR(45) NULL, COUNTRY VARCHAR(45) NULL, - UPDATE_TIMESTAMP BIGINT NOT NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), + INDEX DM_DEVICE_LOCATION_DEVICE_idx (DEVICE_ID ASC), CONSTRAINT DM_DEVICE_LOCATION_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION -); +) +ENGINE = InnoDB; -CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC); +DROP TABLE IF EXISTS DM_DEVICE_DETAIL ; -IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_DETAIL' and type = 'u') - DROP TABLE DM_DEVICE_DETAIL; - -CREATE TABLE DM_DEVICE_DETAIL ( - ID INTEGER NOT NULL IDENTITY, - DEVICE_ID INTEGER NOT NULL, +CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_ID INT NOT NULL, DEVICE_MODEL VARCHAR(45) NULL, VENDOR VARCHAR(45) NULL, OS_VERSION VARCHAR(45) NULL, @@ -488,33 +492,43 @@ CREATE TABLE DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INTEGER NULL, - UPDATE_TIMESTAMP BIGINT NOT NULL, + PLUGGED_IN INT(1) NULL, + UPDATE_TIMESTAMP BIGINT(15) NOT NULL, PRIMARY KEY (ID), + INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx (DEVICE_ID ASC), CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION - ON UPDATE NO ACTION -); + ON UPDATE NO ACTION) +ENGINE = InnoDB; -CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC); +-- POLICY AND DEVICE GROUP MAPPING -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( + ID INT NOT NULL AUTO_INCREMENT, + DEVICE_GROUP_ID INT NOT NULL, + POLICY_ID INT NOT NULL, + TENANT_ID INT NOT NULL, + PRIMARY KEY (ID), + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +)ENGINE = InnoDB; + +-- END OF POLICY AND DEVICE GROUP MAPPING -- -- DASHBOARD RELATED VIEWS -- -CREATE VIEW POLICY_COMPLIANCE_INFO AS -SELECT TOP 100 PERCENT -DEVICE_INFO.DEVICE_ID, -DEVICE_INFO.DEVICE_IDENTIFICATION, -DEVICE_INFO.PLATFORM, -DEVICE_INFO.OWNERSHIP, -DEVICE_INFO.CONNECTIVITY_STATUS, -ISNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID, -ISNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS -IS_COMPLIANT, -DEVICE_INFO.TENANT_ID -FROM -(SELECT +CREATE VIEW DEVICE_INFO_VIEW AS +SELECT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, DM_DEVICE_TYPE.NAME AS PLATFORM, @@ -522,20 +536,34 @@ DM_ENROLMENT.OWNERSHIP, DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, DM_DEVICE.TENANT_ID FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT -WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO -LEFT JOIN -(SELECT +WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID; + +CREATE VIEW DEVICE_WITH_POLICY_INFO_VIEW AS +SELECT DEVICE_ID, POLICY_ID, STATUS AS IS_COMPLIANT +FROM DM_POLICY_COMPLIANCE_STATUS; + +CREATE VIEW POLICY_COMPLIANCE_INFO AS +SELECT +DEVICE_INFO_VIEW.DEVICE_ID, +DEVICE_INFO_VIEW.DEVICE_IDENTIFICATION, +DEVICE_INFO_VIEW.PLATFORM, +DEVICE_INFO_VIEW.OWNERSHIP, +DEVICE_INFO_VIEW.CONNECTIVITY_STATUS, +IFNULL(DEVICE_WITH_POLICY_INFO_VIEW.POLICY_ID, -1) AS POLICY_ID, +IFNULL(DEVICE_WITH_POLICY_INFO_VIEW.IS_COMPLIANT, -1) AS IS_COMPLIANT, +DEVICE_INFO_VIEW.TENANT_ID FROM -DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO -ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID -ORDER BY DEVICE_INFO.DEVICE_ID; -GO +DEVICE_INFO_VIEW +LEFT JOIN +DEVICE_WITH_POLICY_INFO_VIEW +ON DEVICE_INFO_VIEW.DEVICE_ID = DEVICE_WITH_POLICY_INFO_VIEW.DEVICE_ID +ORDER BY DEVICE_INFO_VIEW.DEVICE_ID; CREATE VIEW FEATURE_NON_COMPLIANCE_INFO AS -SELECT TOP 100 PERCENT +SELECT DM_DEVICE.ID AS DEVICE_ID, DM_DEVICE.DEVICE_IDENTIFICATION, DM_DEVICE_DETAIL.DEVICE_MODEL, @@ -545,8 +573,7 @@ DM_ENROLMENT.OWNERSHIP, DM_ENROLMENT.OWNER, DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS, DM_POLICY_COMPLIANCE_STATUS.POLICY_ID, -DM_DEVICE_TYPE.NAME -AS PLATFORM, +DM_DEVICE_TYPE.NAME AS PLATFORM, DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE, DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT, DM_DEVICE.TENANT_ID @@ -554,13 +581,11 @@ FROM DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL WHERE DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND -DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = -DM_ENROLMENT.ID AND +DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID ORDER BY TENANT_ID, DEVICE_ID; -GO -- END OF DASHBOARD RELATED VIEWS -- From 35ea88b9dec668148b0f86b8d719b3a521c99c69 Mon Sep 17 00:00:00 2001 From: harshanl Date: Thu, 4 Aug 2016 20:39:31 +0530 Subject: [PATCH 44/76] Fixed EMM-1476. --- ....java => AbstractNotificationDAOImpl.java} | 41 +------------ .../resources/dbscripts/cdm/postgresql.sql | 60 +++++++++++++++---- 2 files changed, 51 insertions(+), 50 deletions(-) rename components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/{NotificationDAOImpl.java => AbstractNotificationDAOImpl.java} (89%) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java similarity index 89% rename from components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java index 608c5a4f2e..0f16103c6d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/NotificationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java @@ -35,7 +35,7 @@ import java.util.List; /** * Implementation of NotificationDAO which includes the methods to do CRUD operations on notification. */ -public class NotificationDAOImpl implements NotificationDAO { +public abstract class NotificationDAOImpl implements NotificationDAO { @Override public int addNotification(int deviceId, int tenantId, @@ -176,45 +176,6 @@ public class NotificationDAOImpl implements NotificationDAO { return notifications; } - @Override - public List getAllNotifications(PaginationRequest request, int tenantId) throws NotificationManagementException { - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = - "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + - " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + - "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; - - sql = sql + " LIMIT ?,?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setInt(2, tenantId); - int paramIdx = 3; - - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all notifications", e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - } - - @Override public int getNotificationCount(int tenantId) throws NotificationManagementException { int notificationCount = 0; diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql index dc3c6229f2..52083e9d8c 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/postgresql.sql @@ -2,7 +2,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE ( ID BIGSERIAL PRIMARY KEY, NAME VARCHAR(300) DEFAULT NULL, PROVIDER_TENANT_ID INTEGER DEFAULT 0, - SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE + SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE, + UNIQUE(NAME) ); CREATE TABLE IF NOT EXISTS DM_DEVICE ( @@ -272,7 +273,7 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_STATUS ( CREATE TABLE IF NOT EXISTS DM_POLICY_CHANGE_MGT ( ID BIGSERIAL NOT NULL PRIMARY KEY, POLICY_ID INTEGER NOT NULL, - DEVICE_TYPE VARCHAR(300) NOT NULL, + DEVICE_TYPE VARCHAR(300) NOT NULL, TENANT_ID INTEGER NOT NULL ); @@ -289,18 +290,11 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES ( ON UPDATE NO ACTION ); - CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( ID BIGSERIAL NOT NULL PRIMARY KEY, DEVICE_GROUP_ID INT NOT NULL, POLICY_ID INT NOT NULL, TENANT_ID INT NOT NULL, - PRIMARY KEY (ID), - CONSTRAINT FK_DM_DEVICE_GROUP_POLICY - FOREIGN KEY (DEVICE_GROUP_ID) - REFERENCES DM_GROUP (ID) - ON DELETE NO ACTION - ON UPDATE NO ACTION, CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY FOREIGN KEY (POLICY_ID) REFERENCES DM_POLICY (ID) @@ -350,6 +344,52 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_APPLICATION_MAPPING ( -- POLICY RELATED TABLES FINISHED -- +-- DEVICE GROUP TABLES -- + +CREATE TABLE IF NOT EXISTS DM_GROUP ( + ID BIGSERIAL NOT NULL PRIMARY KEY, + GROUP_NAME VARCHAR(100) DEFAULT NULL, + DESCRIPTION BYTEA DEFAULT NULL, + DATE_OF_CREATE INTEGER DEFAULT NULL, + DATE_OF_LAST_UPDATE INTEGER DEFAULT NULL, + OWNER VARCHAR(45) DEFAULT NULL, + TENANT_ID INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_MAP ( + ID BIGSERIAL NOT NULL PRIMARY KEY, + DEVICE_ID INTEGER DEFAULT NULL, + GROUP_ID INTEGER DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID) + REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, + CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID) + REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION +); + +-- END OF DEVICE GROUP TABLES -- + +-- POLICY AND DEVICE GROUP MAPPING -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY ( + ID BIGSERIAL NOT NULL PRIMARY KEY, + DEVICE_GROUP_ID INTEGER NOT NULL, + POLICY_ID INTEGER NOT NULL, + TENANT_ID INTEGER NOT NULL, + CONSTRAINT FK_DM_DEVICE_GROUP_POLICY + FOREIGN KEY (DEVICE_GROUP_ID) + REFERENCES DM_GROUP (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION, + CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY + FOREIGN KEY (POLICY_ID) + REFERENCES DM_POLICY (ID) + ON DELETE NO ACTION + ON UPDATE NO ACTION +); + +-- END OF POLICY AND DEVICE GROUP MAPPING -- + -- NOTIFICATION TABLE -- CREATE TABLE IF NOT EXISTS DM_NOTIFICATION ( NOTIFICATION_ID BIGSERIAL NOT NULL PRIMARY KEY, @@ -420,7 +460,7 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL ( CPU_USAGE DECIMAL(5) NULL, TOTAL_RAM_MEMORY DECIMAL(30,3) NULL, AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL, - PLUGGED_IN INT NULL, + PLUGGED_IN BOOLEAN NOT NULL DEFAULT FALSE, UPDATE_TIMESTAMP BIGINT NOT NULL, CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE FOREIGN KEY (DEVICE_ID) From 657e4864fbf093dff91781306ca3660b51666a03 Mon Sep 17 00:00:00 2001 From: harshanl Date: Thu, 4 Aug 2016 20:40:40 +0530 Subject: [PATCH 45/76] Added MSSQL, PostgreSQL and Oracle db support for Notification feature. --- .../src/main/webapp/META-INF/permissions.xml | 754 +++++++++--------- .../dao/NotificationManagementDAOFactory.java | 33 +- .../dao/impl/AbstractNotificationDAOImpl.java | 63 +- .../dao/impl/GenericNotificationDAOImpl.java | 122 +++ .../dao/impl/OracleNotificationDAOImpl.java | 122 +++ .../impl/PostgreSQLNotificationDAOImpl.java | 122 +++ .../impl/SQLServerNotificationDAOImpl.java | 122 +++ .../mgt/dao/util/NotificationDAOUtil.java | 10 + .../operation/PostgreSQLOperationDAOImpl.java | 8 +- 9 files changed, 917 insertions(+), 439 deletions(-) create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java create mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml index 6439eab85e..050e9089cf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -30,379 +30,385 @@ - - Device Management - /device-mgt - / - GET - - - - Device Management Admin - /device-mgt/admin - / - GET - - - Devices - /device-mgt/admin/devices - / - GET - - - - List devices - /device-mgt/admin/devices/List - /devices - GET - - - Search devices - /device-mgt/admin/devices/Search - /devices/search-devices - POST - - - View device - /device-mgt/admin/devices/View - /devices/*/* - GET - - - View device applications - /device-mgt/admin/devices/View-Applications - /devices/*/*/applications - GET - - - View device effective-policy - /device-mgt/admin/devices/View-Active-Policy - /devices/*/*/effective-policy - GET - - - View devices feature - /device-mgt/admin/devices/View-Features - /devices/*/*/features - GET - - - View device operations - /device-mgt/admin/devices/View-Operations - /devices/*/*/operations - GET - - - View Compliance Data - /device-mgt/admin/devices/View-Compliance-Data - /devices/*/*/compliance-data - GET - - - List all devices - /device-mgt/admin/devices/Admin-View - /admin/devices - GET - - - View device types - /device-mgt/admin/devices/Admin-DeviceType-View - /admin/device-types - GET - - - - Policies - /device-mgt/admin/policies - / - GET - - - - List policies - /device-mgt/admin/policies/List - /policies - GET - - - Add Policy - /device-mgt/admin/policies/Add - /policies - POST - - - Activate policy - /device-mgt/admin/policies/Activate-Policy - /policies/activate-policy - PUT - - - Deactivate Policy - /device-mgt/admin/policies/Deactivate-Policy - /policies/deactivate-policy - PUT - - - Remove Policy - /device-mgt/admin/policies/Remove - /policies/remove-policy - POST - - - View Policy - /device-mgt/admin/policies/View - /policies/* - GET - - - Update Policy - /device-mgt/admin/policies/Update - /policies/* - PUT - - - Update Policy - /device-mgt/admin/policies/Update - /policies/apply-changes - PUT - - - Update Policy - /device-mgt/admin/policies/Change-Priority - /policies/priorities - PUT - - - - Notifications - /device-mgt/admin/notifications - / - GET - - - - View notifications - /device-mgt/admin/notifications/View - /notifications - GET - - - Mark checked notifications - /device-mgt/admin/notifications/View - /notifications/*/mark-checked - PUT - - - - Users - /device-mgt/admin/users - / - GET - - - - List users - /device-mgt/admin/users/List - /users - GET - - - Add user - /device-mgt/admin/users/Add - /users - POST - - - List users - /device-mgt/admin/users/Search - /users/search/usernames - GET - - - Remove user - /device-mgt/admin/users/Remove - /users/* - DELETE - - - View user - /device-mgt/admin/users/View - /users/* - GET - - - Update user - /device-mgt/admin/users/Update - /users/* - PUT - - - Update user credentials - /device-mgt/admin/users/Change-Password - /users/*/credentials - PUT - - - View assigned role - /device-mgt/admin/roles/Assigned-Roles - /users/*/roles - GET - - - Change any user credentials - /device-mgt/admin/users/Change-Password-Any - /admin/users/*/credentials - POST - - - Send invitation mail - /device-mgt/admin/users/Send-invitations - /users/send-invitation - POST - - - - Roles - /device-mgt/admin/roles - / - GET - - - - List roles - /device-mgt/admin/roles/List - /roles - GET - - - Add role - /device-mgt/admin/roles/Add - /roles - POST - - - Remove role - /device-mgt/admin/roles/Remove - /roles/* - DELETE - - - View role - /device-mgt/admin/roles/View - /roles/* - GET - - - Update role - /device-mgt/admin/roles/Update - /roles/* - PUT - - - View role permissions - /device-mgt/admin/roles/View-Permission - /roles/*/permissions - GET - - - Add Users to role - /device-mgt/admin/roles/Add-Users - /roles/*/users - PUT - - - - Configurations - /device-mgt/admin/general-configs - / - GET - - - - View configuration - /device-mgt/admin/general-configuration/View - /configuration - GET - - - Update configuration - /device-mgt/admin/general-configuration/Update - /configuration - PUT - - - - Activities - /device-mgt/admin/activities - / - GET - - - - View Activities - /device-mgt/admin/activities/View - /activities - GET - - - View Activity Details - /device-mgt/admin/activities/View - /activities/* - GET - - - - Applications - /device-mgt/admin/applications - / - GET - - - - Install Applications - /device-mgt/admin/application/Install - /admin/applications/install-application - POST - - - Uninstall-Applications - /device-mgt/admin/application/Uninstall - /admin/applications/uninstall-application - POST - - - - - - Device Management User - /device-mgt/user - / - GET - - - User Devices - /device-mgt/user/devices - / - GET - - - User Policies - /device-mgt/user/policies - / - GET - - - User Notifications - /device-mgt/user/notifications - / - GET - - - User Operations - /device-mgt/user/operations - / - GET - - + + Device Management + /device-mgt + / + GET + + + + Device Management Admin + /device-mgt/admin + / + GET + + + Devices + /device-mgt/admin/devices + / + GET + + + + List devices + /device-mgt/admin/devices/List + /devices + GET + + + Search devices + /device-mgt/admin/devices/Search + /devices/search-devices + POST + + + View device + /device-mgt/admin/devices/View + /devices/*/* + GET + + + View device info + /device-mgt/admin/devices/View + /devices/*/*/info + GET + + + View device applications + /device-mgt/admin/devices/View-Applications + /devices/*/*/applications + GET + + + View device effective-policy + /device-mgt/admin/devices/View-Active-Policy + /devices/*/*/effective-policy + GET + + + View devices feature + /device-mgt/admin/devices/View-Features + /devices/*/*/features + GET + + + View device operations + /device-mgt/admin/devices/View-Operations + /devices/*/*/operations + GET + + + View Compliance Data + /device-mgt/admin/devices/View-Compliance-Data + /devices/*/*/compliance-data + GET + + + List all devices + /device-mgt/admin/devices/Admin-View + /admin/devices + GET + + + View device types + /device-mgt/admin/devices/Admin-DeviceType-View + /admin/device-types + GET + + + + Policies + /device-mgt/admin/policies + / + GET + + + + List policies + /device-mgt/admin/policies/List + /policies + GET + + + Add Policy + /device-mgt/admin/policies/Add + /policies + POST + + + Activate policy + /device-mgt/admin/policies/Activate-Policy + /policies/activate-policy + PUT + + + Deactivate Policy + /device-mgt/admin/policies/Deactivate-Policy + /policies/deactivate-policy + PUT + + + Remove Policy + /device-mgt/admin/policies/Remove + /policies/remove-policy + POST + + + View Policy + /device-mgt/admin/policies/View + /policies/* + GET + + + Update Policy + /device-mgt/admin/policies/Update + /policies/* + PUT + + + Update Policy + /device-mgt/admin/policies/Update + /policies/apply-changes + PUT + + + Update Policy + /device-mgt/admin/policies/Change-Priority + /policies/priorities + PUT + + + + Notifications + /device-mgt/admin/notifications + / + GET + + + + View notifications + /device-mgt/admin/notifications/View + /notifications + GET + + + Mark checked notifications + /device-mgt/admin/notifications/View + /notifications/*/mark-checked + PUT + + + + Users + /device-mgt/admin/users + / + GET + + + + List users + /device-mgt/admin/users/List + /users + GET + + + Add user + /device-mgt/admin/users/Add + /users + POST + + + List users + /device-mgt/admin/users/Search + /users/search/usernames + GET + + + Remove user + /device-mgt/admin/users/Remove + /users/* + DELETE + + + View user + /device-mgt/admin/users/View + /users/* + GET + + + Update user + /device-mgt/admin/users/Update + /users/* + PUT + + + Update user credentials + /device-mgt/admin/users/Change-Password + /users/*/credentials + PUT + + + View assigned role + /device-mgt/admin/roles/Assigned-Roles + /users/*/roles + GET + + + Change any user credentials + /device-mgt/admin/users/Change-Password-Any + /admin/users/*/credentials + POST + + + Send invitation mail + /device-mgt/admin/users/Send-invitations + /users/send-invitation + POST + + + + Roles + /device-mgt/admin/roles + / + GET + + + + List roles + /device-mgt/admin/roles/List + /roles + GET + + + Add role + /device-mgt/admin/roles/Add + /roles + POST + + + Remove role + /device-mgt/admin/roles/Remove + /roles/* + DELETE + + + View role + /device-mgt/admin/roles/View + /roles/* + GET + + + Update role + /device-mgt/admin/roles/Update + /roles/* + PUT + + + View role permissions + /device-mgt/admin/roles/View-Permission + /roles/*/permissions + GET + + + Add Users to role + /device-mgt/admin/roles/Add-Users + /roles/*/users + PUT + + + + Configurations + /device-mgt/admin/general-configs + / + GET + + + + View configuration + /device-mgt/admin/general-configuration/View + /configuration + GET + + + Update configuration + /device-mgt/admin/general-configuration/Update + /configuration + PUT + + + + Activities + /device-mgt/admin/activities + / + GET + + + + View Activities + /device-mgt/admin/activities/View + /activities + GET + + + View Activity Details + /device-mgt/admin/activities/View + /activities/* + GET + + + + Applications + /device-mgt/admin/applications + / + GET + + + + Install Applications + /device-mgt/admin/application/Install + /admin/applications/install-application + POST + + + Uninstall-Applications + /device-mgt/admin/application/Uninstall + /admin/applications/uninstall-application + POST + + + + + + Device Management User + /device-mgt/user + / + GET + + + User Devices + /device-mgt/user/devices + / + GET + + + User Policies + /device-mgt/user/policies + / + GET + + + User Notifications + /device-mgt/user/notifications + / + GET + + + User Operations + /device-mgt/user/operations + / + GET + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java index 20e8543cb4..d280dd643e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/NotificationManagementDAOFactory.java @@ -20,11 +20,13 @@ package org.wso2.carbon.device.mgt.core.notification.mgt.dao; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException; import org.wso2.carbon.device.mgt.common.TransactionManagementException; +import org.wso2.carbon.device.mgt.common.UnsupportedDatabaseEngineException; import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig; import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition; -import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.NotificationDAOImpl; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl.*; import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; import javax.sql.DataSource; @@ -39,21 +41,48 @@ import java.util.List; public class NotificationManagementDAOFactory { private static DataSource dataSource; + private static String databaseEngine; private static final Log log = LogFactory.getLog(NotificationManagementDAOFactory.class); private static ThreadLocal currentConnection = new ThreadLocal(); public static NotificationDAO getNotificationDAO() { - return new NotificationDAOImpl(); + if (databaseEngine != null) { + switch (databaseEngine) { + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE: + return new OracleNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL: + return new SQLServerNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: + return new PostgreSQLNotificationDAOImpl(); + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: + case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: + return new GenericNotificationDAOImpl(); + default: + throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine); + } + } + throw new IllegalStateException("Database engine has not initialized properly."); } public static void init(DataSourceConfig config) { dataSource = resolveDataSource(config); + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } public static void init(DataSource dtSource) { dataSource = dtSource; + try { + databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName(); + } catch (SQLException e) { + log.error("Error occurred while retrieving config.datasource connection", e); + } } + public static void beginTransaction() throws TransactionManagementException { Connection conn = currentConnection.get(); if (conn != null) { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java index 0f16103c6d..96c47cf0d2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/AbstractNotificationDAOImpl.java @@ -35,7 +35,7 @@ import java.util.List; /** * Implementation of NotificationDAO which includes the methods to do CRUD operations on notification. */ -public abstract class NotificationDAOImpl implements NotificationDAO { +public abstract class AbstractNotificationDAOImpl implements NotificationDAO { @Override public int addNotification(int deviceId, int tenantId, @@ -87,7 +87,7 @@ public abstract class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); while (rs.next()) { - notification = this.getNotification(rs); + notification = NotificationDAOUtil.getNotification(rs); } } catch (SQLException e) { throw new NotificationManagementException( @@ -165,7 +165,7 @@ public abstract class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); notifications = new ArrayList<>(); while (rs.next()) { - notifications.add(this.getNotification(rs)); + notifications.add(NotificationDAOUtil.getNotification(rs)); } } catch (SQLException e) { throw new NotificationManagementException( @@ -238,7 +238,7 @@ public abstract class NotificationDAOImpl implements NotificationDAO { rs = stmt.executeQuery(); notifications = new ArrayList<>(); while (rs.next()) { - notifications.add(this.getNotification(rs)); + notifications.add(NotificationDAOUtil.getNotification(rs)); } } catch (SQLException e) { throw new NotificationManagementException( @@ -283,59 +283,4 @@ public abstract class NotificationDAOImpl implements NotificationDAO { } return notificationCountByStatus; } - - @Override - public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws - NotificationManagementException{ - Connection conn; - PreparedStatement stmt = null; - ResultSet rs = null; - List notifications = null; - try { - conn = NotificationManagementDAOFactory.getConnection(); - String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + - " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + - "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + - "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + - "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + - "AND TENANT_ID = ?"; - - sql = sql + " LIMIT ?,?"; - - stmt = conn.prepareStatement(sql); - stmt.setInt(1, tenantId); - stmt.setString(2, status.toString()); - stmt.setInt(3, tenantId); - - int paramIdx = 4; - - stmt.setInt(paramIdx++, request.getStartIndex()); - stmt.setInt(paramIdx, request.getRowCount()); - - - rs = stmt.executeQuery(); - notifications = new ArrayList<>(); - while (rs.next()) { - notifications.add(this.getNotification(rs)); - } - } catch (SQLException e) { - throw new NotificationManagementException( - "Error occurred while retrieving information of all " + - "notifications by status : " + status, e); - } finally { - NotificationDAOUtil.cleanupResources(stmt, rs); - } - return notifications; - - } - - private Notification getNotification(ResultSet rs) throws SQLException { - Notification notification = new Notification(); - notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); - notification.setOperationId(rs.getInt("OPERATION_ID")); - notification.setDescription(rs.getString("DESCRIPTION")); - notification.setStatus(rs.getString("STATUS")); - return notification; - } - } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java new file mode 100644 index 0000000000..0653ec3029 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/GenericNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the generic implementation of NotificationDAO which can be used to support ANSI db syntax. + */ +public class GenericNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " LIMIT ?,?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " LIMIT ?,?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java new file mode 100644 index 0000000000..829e586d79 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/OracleNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the Oracle implementation of NotificationDAO which can be used to support Oracle db syntax. + */ +public class OracleNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " WHERE OFFSET >= ? AND ROWNUM <= ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " OFFSET >= ? AND ROWNUM <= ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java new file mode 100644 index 0000000000..2039c04cbc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/PostgreSQLNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of NotificationDAO which can be used to support PostgreSQL db syntax. + */ +public class PostgreSQLNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " LIMIT ? OFFSET ?"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getRowCount()); + stmt.setInt(paramIdx, request.getStartIndex()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java new file mode 100644 index 0000000000..e03a220ed1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/impl/SQLServerNotificationDAOImpl.java @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.core.notification.mgt.dao.impl; + +import org.wso2.carbon.device.mgt.common.PaginationRequest; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; +import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.notification.mgt.dao.util.NotificationDAOUtil; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class holds the implementation of NotificationDAO which can be used to support SQLServer db syntax. + */ +public class SQLServerNotificationDAOImpl extends AbstractNotificationDAOImpl { + + @Override + public List getAllNotifications(PaginationRequest request, int tenantId) throws + NotificationManagementException { + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = + "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS, n1.DESCRIPTION," + + " d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT " + + "NOTIFICATION_ID, DEVICE_ID, OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID AND TENANT_ID = ?"; + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setInt(2, tenantId); + int paramIdx = 3; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all notifications", e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } + + + @Override + public List getNotificationsByStatus(PaginationRequest request, Notification.Status status, int tenantId) throws + NotificationManagementException{ + Connection conn; + PreparedStatement stmt = null; + ResultSet rs = null; + List notifications = null; + try { + conn = NotificationManagementDAOFactory.getConnection(); + String sql = "SELECT n1.NOTIFICATION_ID, n1.DEVICE_ID, n1.OPERATION_ID, n1.STATUS," + + " n1.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM " + + "DM_DEVICE d, DM_DEVICE_TYPE t, (SELECT NOTIFICATION_ID, DEVICE_ID, " + + "OPERATION_ID, STATUS, DESCRIPTION FROM DM_NOTIFICATION WHERE " + + "TENANT_ID = ? AND STATUS = ?) n1 WHERE n1.DEVICE_ID = d.ID AND d.DEVICE_TYPE_ID=t.ID " + + "AND TENANT_ID = ?"; + + sql = sql + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + + stmt = conn.prepareStatement(sql); + stmt.setInt(1, tenantId); + stmt.setString(2, status.toString()); + stmt.setInt(3, tenantId); + + int paramIdx = 4; + + stmt.setInt(paramIdx++, request.getStartIndex()); + stmt.setInt(paramIdx, request.getRowCount()); + + + rs = stmt.executeQuery(); + notifications = new ArrayList<>(); + while (rs.next()) { + notifications.add(NotificationDAOUtil.getNotification(rs)); + } + } catch (SQLException e) { + throw new NotificationManagementException( + "Error occurred while retrieving information of all " + + "notifications by status : " + status, e); + } finally { + NotificationDAOUtil.cleanupResources(stmt, rs); + } + return notifications; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java index 5c87e1b311..36f7df6be0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/dao/util/NotificationDAOUtil.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.core.notification.mgt.dao.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.common.notification.mgt.Notification; import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.user.api.UserStoreException; @@ -123,4 +124,13 @@ public class NotificationDAOUtil { throw new RuntimeException("Error in looking up data source: " + e.getMessage(), e); } } + + public static Notification getNotification(ResultSet rs) throws SQLException { + Notification notification = new Notification(); + notification.setNotificationId(rs.getInt("NOTIFICATION_ID")); + notification.setOperationId(rs.getInt("OPERATION_ID")); + notification.setDescription(rs.getString("DESCRIPTION")); + notification.setStatus(rs.getString("STATUS")); + return notification; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java index 0d107ead1d..c9ddcb3d91 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/PostgreSQLOperationDAOImpl.java @@ -46,8 +46,8 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, " + - "OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, " + + "o.OPERATION_CODE, om.STATUS FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ?) om ON o.ID = om.OPERATION_ID ORDER BY o.CREATED_TIMESTAMP DESC LIMIT ? OFFSET ?"; stmt = conn.prepareStatement(sql); @@ -72,7 +72,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { } } catch (SQLException e) { throw new OperationManagementDAOException("SQL error occurred while retrieving the operation " + - "available for the device'" + enrolmentId + "' with status '", e); + "available for the device'" + enrolmentId, e); } finally { OperationManagementDAOUtil.cleanupResources(stmt, rs); } @@ -89,7 +89,7 @@ public class PostgreSQLOperationDAOImpl extends GenericOperationDAOImpl { List operations = new ArrayList(); try { Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT o.ID, TYPE, CREATED_TIMESTAMP, RECEIVED_TIMESTAMP, OPERATION_CODE " + + String sql = "SELECT o.ID, o.TYPE, o.CREATED_TIMESTAMP, o.RECEIVED_TIMESTAMP, o.OPERATION_CODE " + "FROM DM_OPERATION o " + "INNER JOIN (SELECT * FROM DM_ENROLMENT_OP_MAPPING dm " + "WHERE dm.ENROLMENT_ID = ? AND dm.STATUS = ?) om ON o.ID = om.OPERATION_ID ORDER BY " + From f1c1c676562e078fe3b9c8782577bd38f3194711 Mon Sep 17 00:00:00 2001 From: harshanl Date: Fri, 5 Aug 2016 11:34:11 +0530 Subject: [PATCH 46/76] Removed unused policy.mgt module from device core bundle --- .../core/policy/mgt/EvaluationContext.java | 25 -------- .../policy/mgt/PolicyEvaluationException.java | 25 -------- .../policy/mgt/PolicyEvaluationStrategy.java | 25 -------- .../policy/mgt/PolicyManagementException.java | 25 -------- .../mgt/core/policy/mgt/PolicyManager.java | 60 ------------------- .../mgt/core/policy/mgt/PolicyRepository.java | 35 ----------- .../device/mgt/core/policy/mgt/Profile.java | 22 ------- .../device/mgt/core/policy/mgt/Rule.java | 25 -------- .../policy/mgt/RuleCombiningStrategy.java | 25 -------- .../mgt/core/policy/mgt/dao/PolicyDAO.java | 25 -------- .../core/policy/mgt/dao/PolicyDAOFactory.java | 27 --------- .../core/policy/mgt/dao/PolicyDAOImpl.java | 25 -------- .../mgt/policy/PlatformBasedPolicy.java | 33 ---------- .../mgt/core/policy/mgt/policy/Policy.java | 33 ---------- .../policy/mgt/policy/RoleBasedPolicy.java | 33 ---------- .../policy/mgt/policy/UsedBasedPolicy.java | 33 ---------- 16 files changed, 476 deletions(-) delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java delete mode 100644 components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java deleted file mode 100644 index fb62730082..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/EvaluationContext.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public class EvaluationContext { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java deleted file mode 100644 index 569f311aa6..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public class PolicyEvaluationException extends Exception { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java deleted file mode 100644 index bd4557eeb0..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyEvaluationStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public interface PolicyEvaluationStrategy { - - Profile execute(EvaluationContext ctx) throws PolicyEvaluationException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java deleted file mode 100644 index a36bd28fda..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManagementException.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public class PolicyManagementException extends Exception { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java deleted file mode 100644 index a69068a003..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyManager.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy; - -import java.util.List; - -public interface PolicyManager { - - public enum Type { - USER_BASED, ROLE_BASED, PLATFORM_BASED - } - - boolean addPolicy(Policy policy) throws PolicyManagementException; - - boolean removePolicy(String policyId) throws PolicyManagementException; - - boolean updatePolicy(Policy policy) throws PolicyManagementException; - - Policy getPolicy(String policyId) throws PolicyManagementException; - - List getPolicies() throws PolicyManagementException; - - List getUserBasedPolicies(String user) throws PolicyManagementException; - - List getRoleBasedPolicies(String role) throws PolicyManagementException; - - List getPlatformBasedPolicies(String platform) throws PolicyManagementException; - - boolean assignRoleBasedPolicy(String policyId, String role) throws PolicyManagementException; - - boolean assignRoleBasedPolicy(String policyId, List roles) throws PolicyManagementException; - - boolean assignUserBasedPolicy(String policyId, String user) throws PolicyManagementException; - - boolean assignUserBasedPolicy(String policyId, List users) throws PolicyManagementException; - - boolean assignPlatformBasedPolicy(String policyId, String platform) throws PolicyManagementException; - - Profile getEffectiveProfile(DeviceIdentifier deviceId) throws PolicyManagementException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java deleted file mode 100644 index 1e16c2a58f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/PolicyRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -import org.wso2.carbon.device.mgt.core.policy.mgt.policy.Policy; - -public interface PolicyRepository { - - public enum Type { - USER_BASED, ROLE_BASED, PLATFORM_BASED - } - - void addPolicy(Policy policy) throws PolicyManagementException; - - void remotePolicy(Policy policy) throws PolicyManagementException; - - void getPolicy(String id) throws PolicyManagementException; - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java deleted file mode 100644 index 70f1b4269f..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Profile.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public class Profile { -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java deleted file mode 100644 index ad40cff1af..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/Rule.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public class Rule { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java deleted file mode 100644 index 862089c135..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/RuleCombiningStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt; - -public interface RuleCombiningStrategy { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java deleted file mode 100644 index db6354b008..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAO.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.dao; - -public interface PolicyDAO { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java deleted file mode 100644 index 5e5c570e62..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.dao; - -public class PolicyDAOFactory { - - public static PolicyDAO getPolicyDAO() { - return new PolicyDAOImpl(); - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java deleted file mode 100644 index de2de21bd7..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/dao/PolicyDAOImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.dao; - -public class PolicyDAOImpl implements PolicyDAO { - - - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java deleted file mode 100644 index 4914a33f26..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/PlatformBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.policy; - -public class PlatformBasedPolicy extends Policy { - - private String platform; - - public String getPlatform() { - return platform; - } - - public void setPlatform(String platform) { - this.platform = platform; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java deleted file mode 100644 index a528c09eed..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/Policy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.policy; - -public class Policy { - - private String id; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java deleted file mode 100644 index c08544f125..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/RoleBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.policy; - -public class RoleBasedPolicy extends Policy { - - private String role; - - public String getRole() { - return role; - } - - public void setRole(String role) { - this.role = role; - } - -} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java deleted file mode 100644 index 0eb9417826..0000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/policy/mgt/policy/UsedBasedPolicy.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. - * - * WSO2 Inc. licenses this file to you under the Apache License, - * Version 2.0 (the "License"); you may not use this file except - * in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.wso2.carbon.device.mgt.core.policy.mgt.policy; - -public class UsedBasedPolicy extends Policy { - - private String username; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - -} From ccae64c37434c778f8f26ee06eca8348c4da31c1 Mon Sep 17 00:00:00 2001 From: madhawap Date: Fri, 5 Aug 2016 12:05:55 +0530 Subject: [PATCH 47/76] changes to certificate-mgt mssql dbscript --- .../main/resources/dbscripts/cdm/certs/mssql.sql | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql index 6c377c68f6..0e7f76e5eb 100644 --- a/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql +++ b/features/certificate-mgt/org.wso2.carbon.certificate.mgt.server.feature/src/main/resources/dbscripts/cdm/certs/mssql.sql @@ -1,8 +1,8 @@ -CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( - ID INTEGER auto_increment NOT NULL, - SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, - CERTIFICATE BLOB DEFAULT NULL, - TENANT_ID INTEGER DEFAULT 0, - USERNAME VARCHAR(500) DEFAULT NULL, - PRIMARY KEY (ID) -); +CREATE TABLE DM_DEVICE_CERTIFICATE ( + ID INTEGER IDENTITY NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE VARBINARY(max) DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, +PRIMARY KEY (ID) +); \ No newline at end of file From d2ad852db19bcf0f8fdf4044c991cbd598d9182f Mon Sep 17 00:00:00 2001 From: madhawap Date: Fri, 5 Aug 2016 12:16:59 +0530 Subject: [PATCH 48/76] changes to certificate-mgt mysql dbscript, fix for the jira EMM-1487 --- .../src/main/resources/dbscripts/cdm/mysql.sql | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql index 098ebc5d98..8d1ddb215d 100644 --- a/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql +++ b/features/device-mgt/org.wso2.carbon.device.mgt.server.feature/src/main/resources/dbscripts/cdm/mysql.sql @@ -585,3 +585,16 @@ ORDER BY TENANT_ID, DEVICE_ID; -- END OF DASHBOARD RELATED VIEWS -- +-- CERTIFICATES TABLES -- + +CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE ( + ID INTEGER auto_increment NOT NULL, + SERIAL_NUMBER VARCHAR(500) DEFAULT NULL, + CERTIFICATE BLOB DEFAULT NULL, + TENANT_ID INTEGER DEFAULT 0, + USERNAME VARCHAR(500) DEFAULT NULL, + PRIMARY KEY (ID) +)ENGINE = InnoDB; + +-- END CERTIFICATES TABLES -- + From 87cdfa209e4d0a83dce4eb9febb96c4c5ce15b1b Mon Sep 17 00:00:00 2001 From: dilanua Date: Sat, 6 Aug 2016 17:13:58 +0530 Subject: [PATCH 49/76] Updating policy management --- .../pages/cdmf.page.policy.create/create.hbs | 16 +++++++++------- .../app/units/cdmf.unit.ui.title/title.hbs | 17 ++++++++++------- .../uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs | 17 ++++++++++------- .../app/units/uuf.unit.navbar/navbar.hbs | 15 ++++++++------- 4 files changed, 37 insertions(+), 28 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.create/create.hbs index 360523ebb1..6b246fe791 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.create/create.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 | Add Policy"}} {{#zone "breadcrumbs"}}
  • @@ -24,6 +25,7 @@
  • + Policies diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs index 1d82a81154..5fbe77d385 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.title/title.hbs @@ -2,17 +2,20 @@ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at + Version 2.0 (the "License"); you may not use this file + except in compliance with the License. You may + obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language governing permissions and limitations under the License. }} -{{#zone "title"}}{{@unit.params.pageTitle}} | {{@app.conf.appName}}{{/zone}} \ No newline at end of file + +{{#zone "title"}} + {{@unit.params.pageTitle}} | {{@app.conf.appName}} +{{/zone}} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs index af6cd3218f..fca8b278a2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/uuf-template-app/app/units/uuf.unit.navbar.breadcrumbs/breadcrumbs.hbs @@ -2,21 +2,24 @@ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. WSO2 Inc. licenses this file to you under the Apache License, - Version 2.0 (the "License"); you may not use this file except - in compliance with the License. - You may obtain a copy of the License at + Version 2.0 (the "License"); you may not use this file + except in compliance with the License. You may + obtain a copy of the License at - http://www.apache.org/licenses/LICENSE-2.0 + http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + either express or implied. See the License for the specific language governing permissions and limitations under the License. }} + {{#zone "navbarHeader"}} -