diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml index a0eeea3e1e2..7d14ea8b0cf 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml @@ -22,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.annotations - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT bundle WSO2 Carbon - API Management Annotations WSO2 Carbon - API Management Custom Annotation Module 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 new file mode 100644 index 00000000000..14d447ac2c0 --- /dev/null +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java @@ -0,0 +1,42 @@ +/* +* 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.annotations.api; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * This class is the representation of custom developed Permission annotation. + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Permission { + + /** + * Represents the permission name. + * @return Returns permission name. + */ + String name(); + + /** + * Represents the permission string. + * @return Returns permission string. + */ + String permission(); + +} \ No newline at end of file diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml index 3adf644e246..e54a20da371 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml @@ -21,12 +21,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 4.0.0 - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT org.wso2.carbon.apimgt.application.extension.api war WSO2 Carbon - API Application Management API diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml index e61770da13a..a7c934c4076 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml @@ -22,12 +22,12 @@ apimgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 4.0.0 - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT org.wso2.carbon.apimgt.application.extension bundle WSO2 Carbon - API Application Management 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 3679e3eed03..0153758ac52 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 @@ -22,13 +22,13 @@ apimgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.apimgt.webapp.publisher - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT bundle WSO2 Carbon - API Management Webapp Publisher WSO2 Carbon - API Management Webapp Publisher diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java index 02f75607fdd..ea5e524fc31 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherStartupHandler.java @@ -44,33 +44,33 @@ public class APIPublisherStartupHandler implements ServerStartupObserver { @Override public void completedServerStartup() { - APIPublisherDataHolder.getInstance().setServerStarted(true); - currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis(); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - if (log.isDebugEnabled()) { - log.debug("Server has just started, hence started publishing unpublished APIs"); - log.debug("Total number of unpublished APIs: " - + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); - } - publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); - while (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty()) { - try { - retryTime = retryTime * CONNECTION_RETRY_FACTOR; - Thread.sleep(retryTime); - } catch (InterruptedException te) { - log.error("Error occurred while sleeping", te); - } - if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) { - publishAPIs(currentAPIsStack, failedAPIsStack); - } else { - publishAPIs(failedAPIsStack, currentAPIsStack); - } - } - } - }); - t.start(); +// APIPublisherDataHolder.getInstance().setServerStarted(true); +// currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis(); +// Thread t = new Thread(new Runnable() { +// @Override +// public void run() { +// if (log.isDebugEnabled()) { +// log.debug("Server has just started, hence started publishing unpublished APIs"); +// log.debug("Total number of unpublished APIs: " +// + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); +// } +// publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); +// while (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty()) { +// try { +// retryTime = retryTime * CONNECTION_RETRY_FACTOR; +// Thread.sleep(retryTime); +// } catch (InterruptedException te) { +// log.error("Error occurred while sleeping", te); +// } +// if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) { +// publishAPIs(currentAPIsStack, failedAPIsStack); +// } else { +// publishAPIs(failedAPIsStack, currentAPIsStack); +// } +// } +// } +// }); +// t.start(); } private void publishAPIs(Stack apis, Stack failedStack) { diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java index d2932f994e5..11e991f349e 100644 --- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java +++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/listener/APIPublisherLifecycleListener.java @@ -49,72 +49,72 @@ public class APIPublisherLifecycleListener implements LifecycleListener { @Override public void lifecycleEvent(LifecycleEvent lifecycleEvent) { - if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance() - .isPublished()) { - StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); - ServletContext servletContext = context.getServletContext(); - String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); - boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); - - String profile = System.getProperty(PROPERTY_PROFILE); - - if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) - && isManagedApi) { - try { - AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); - Set annotatedAPIClasses = annotationProcessor. - scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); - - List apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, - annotatedAPIClasses); - - for (APIResourceConfiguration apiDefinition : apiDefinitions) { - - APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); - - try { - int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). - getTenantId(apiConfig.getTenantDomain()); - - boolean isTenantActive = APIPublisherDataHolder.getInstance(). - getTenantManager().isTenantActive(tenantId); - - if (isTenantActive) { - apiConfig.init(); - API api = APIPublisherUtil.getAPI(apiConfig); - boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); - if (isServerStarted) { - APIPublisherService apiPublisherService = - APIPublisherDataHolder.getInstance().getApiPublisherService(); - if (apiPublisherService == null) { - throw new IllegalStateException( - "API Publisher service is not initialized properly"); - } - apiPublisherService.publishAPI(api); - } else { - if (log.isDebugEnabled()) { - log.debug("Server has not started yet. Hence adding API '" + - api.getId().getApiName() + "' to the queue"); - } - APIPublisherDataHolder.getInstance().getUnpublishedApis().push(api); - } - } else { - log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + - "found when publishing the Web app"); - } - } catch (Throwable e) { - log.error("Error occurred while publishing API '" + apiConfig.getName() + - "' with the context '" + apiConfig.getContext() + - "' and version '" + apiConfig.getVersion() + "'", e); - } - } - } catch (IOException e) { - log.error("Error encountered while discovering annotated classes", e); - } catch (ClassNotFoundException e) { - log.error("Error while scanning class for annotations", e); - } - } - } +// if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance() +// .isPublished()) { +// StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); +// ServletContext servletContext = context.getServletContext(); +// String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); +// boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); +// +// String profile = System.getProperty(PROPERTY_PROFILE); +// +// if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) +// && isManagedApi) { +// try { +// AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); +// Set annotatedAPIClasses = annotationProcessor. +// scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); +// +// List apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, +// annotatedAPIClasses); +// +// for (APIResourceConfiguration apiDefinition : apiDefinitions) { +// +// APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); +// +// try { +// int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). +// getTenantId(apiConfig.getTenantDomain()); +// +// boolean isTenantActive = APIPublisherDataHolder.getInstance(). +// getTenantManager().isTenantActive(tenantId); +// +// if (isTenantActive) { +// apiConfig.init(); +// API api = APIPublisherUtil.getAPI(apiConfig); +// boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); +// if (isServerStarted) { +// APIPublisherService apiPublisherService = +// APIPublisherDataHolder.getInstance().getApiPublisherService(); +// if (apiPublisherService == null) { +// throw new IllegalStateException( +// "API Publisher service is not initialized properly"); +// } +// apiPublisherService.publishAPI(api); +// } else { +// if (log.isDebugEnabled()) { +// log.debug("Server has not started yet. Hence adding API '" + +// api.getId().getApiName() + "' to the queue"); +// } +// APIPublisherDataHolder.getInstance().getUnpublishedApis().push(api); +// } +// } else { +// log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + +// "found when publishing the Web app"); +// } +// } catch (Throwable e) { +// log.error("Error occurred while publishing API '" + apiConfig.getName() + +// "' with the context '" + apiConfig.getContext() + +// "' and version '" + apiConfig.getVersion() + "'", e); +// } +// } +// } catch (IOException e) { +// log.error("Error encountered while discovering annotated classes", e); +// } catch (ClassNotFoundException e) { +// log.error("Error while scanning class for annotations", e); +// } +// } +// } } //TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml index a4f6b67e1af..33991cb99fe 100644 --- a/components/apimgt-extensions/pom.xml +++ b/components/apimgt-extensions/pom.xml @@ -22,13 +22,13 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../../pom.xml 4.0.0 apimgt-extensions - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT pom WSO2 Carbon - API Management Extensions Component http://wso2.org 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 c0b5483a3c3..ce38a087f0b 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 @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml @@ -76,7 +76,7 @@ - + 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 fbb94589626..6527bff32de 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,6 +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; @@ -47,6 +48,7 @@ public interface CertificateMgtService { response = ErrorResponse.class) }) @Scope(key = "certificate:sign-csr", name = "Sign CSR", description = "") + @Permission(name = "Sign CSR", permission = "/device-mgt/certificates/manage") Response getSignedCertFromCSR( @ApiParam( name = "If-Modified-Since", diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml index df2b2cf629b..5a63c7f5331 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/webapp/META-INF/permissions.xml @@ -32,7 +32,7 @@ get certificate in the database - /device-mgt/admin/certificate/GetSignCSR + /device-mgt/certificate/GetSignCSR /certificates/scep/signcsr POST emm_admin 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 304a441d10e..d4882beb281 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 @@ -22,7 +22,7 @@ certificate-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml @@ -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 da1d54bc4ff..b417fe56a8c 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,6 +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; @@ -77,7 +78,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n Server error occurred while adding certificates.", response = ErrorResponse.class) }) - @Scope(key = "certificate:manage", name = "Add certificates", description = "") + @Permission(name = "Manage certificates", permission = "/device-mgt/certificates/manage") Response addCertificate( @ApiParam( name = "enrollmentCertificates", @@ -135,7 +136,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving information requested certificate.", response = ErrorResponse.class) }) - @Scope(key = "certificate:view", name = "View certificates", description = "") + @Permission(name = "View certificates", permission = "/device-mgt/certificates/view") Response getCertificate( @ApiParam(name = "serialNumber", value = "Provide the serial number of the certificate that you wish to get the details of", @@ -207,7 +208,7 @@ public interface CertificateManagementAdminService { "Server error occurred while retrieving all certificates enrolled in the system.", response = ErrorResponse.class) }) - @Scope(key = "certificate:view", name = "View certificates", description = "") + @Permission(name = "View certificates", permission = "/device-mgt/certificates/view") Response getAllCertificates( @ApiParam( name = "offset", @@ -250,7 +251,7 @@ public interface CertificateManagementAdminService { message = "Internal Server Error. \n " + "Server error occurred while removing the certificate.", response = ErrorResponse.class)}) - @Scope(key = "certificate:manage", name = "Add certificates", description = "") + @Permission(name = "Manage certificates", permission = "/device-mgt/certificates/manage") Response removeCertificate( @ApiParam( name = "serialNumber", diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml index 6002517cef0..7fd3679c504 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml @@ -21,13 +21,13 @@ org.wso2.carbon.devicemgt certificate-mgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 4.0.0 org.wso2.carbon.certificate.mgt.core - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT bundle WSO2 Carbon - Certificate Management Core WSO2 Carbon - Certificate Management Core diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml index 355f3a47e9a..7530d6d0a43 100644 --- a/components/certificate-mgt/pom.xml +++ b/components/certificate-mgt/pom.xml @@ -22,14 +22,14 @@ org.wso2.carbon.devicemgt carbon-devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../../pom.xml 4.0.0 org.wso2.carbon.devicemgt certificate-mgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT pom WSO2 Carbon - Certificate Management Component http://wso2.org diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/pom.xml index 58435dcef64..f5de6519ad8 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/gcm/GCMNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/gcm/GCMNotificationStrategy.java index 65738e4ee1b..05c8105e4b3 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/gcm/GCMNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.gcm/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/gcm/GCMNotificationStrategy.java @@ -78,7 +78,7 @@ public class GCMNotificationStrategy implements NotificationStrategy { HttpURLConnection conn = null; try { - conn = (HttpURLConnection) (new URL(config.getProperty(GCM_ENDPOINT)).openConnection()); + conn = (HttpURLConnection) new URL(GCM_ENDPOINT).openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml index cc905f6e9e8..a060e97c9ec 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml index f4e5494a30f..d62fb559919 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml @@ -22,7 +22,7 @@ device-mgt-extensions org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml index 81e6c2c4625..c3eb5a04677 100644 --- a/components/device-mgt-extensions/pom.xml +++ b/components/device-mgt-extensions/pom.xml @@ -22,7 +22,7 @@ carbon-devicemgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml index 6c6a68cd16a..f95d2a30c3a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/pom.xml @@ -3,7 +3,7 @@ org.wso2.carbon.devicemgt device-mgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml index 9d0be0f5b18..17d5c405765 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.analytics.data.publisher/pom.xml @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 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 85072c4890f..ca6c3f3342d 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 @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 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 94658cd1323..80ed6c8b2ae 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,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.beans; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.wso2.carbon.user.mgt.common.UIPermissionNode; import java.util.List; @@ -29,12 +30,19 @@ 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.", + @ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.", required = true, dataType = "List[java.lang.String]") - private List scopes; + private String[] permissions; @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; @@ -44,12 +52,12 @@ public class RoleInfo { this.roleName = roleName; } - public List getScopes() { - return scopes; + public String[] getPermissions() { + return permissions; } - public void setScopes(List scopes) { - this.scopes = scopes; + public void setPermissions(String[] permissions) { + this.permissions = permissions; } public String[] getUsers() { @@ -60,4 +68,12 @@ 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/common/GsonMessageBodyHandler.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java index d2f9d2113f7..f069edee755 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/common/GsonMessageBodyHandler.java @@ -40,6 +40,7 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; @Consumes(APPLICATION_JSON) public class GsonMessageBodyHandler implements MessageBodyWriter, MessageBodyReader { + public static final String DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z"; private Gson gson; private static final String UTF_8 = "UTF-8"; @@ -50,7 +51,7 @@ public class GsonMessageBodyHandler implements MessageBodyWriter, Messag private Gson getGson() { if (gson == null) { final GsonBuilder gsonBuilder = new GsonBuilder(); - gson = gsonBuilder.create(); + gson = gsonBuilder.setDateFormat(DATE_FORMAT).create(); } return gson; } 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 f91a9ccdb6f..1c23be25441 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,6 +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; @@ -92,7 +93,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Scope(key = "activity:view", name = "View Activities", description = "") + @Permission(name = "View Activities", permission = "/device-mgt/devices/owning/view") Response getActivity( @ApiParam( name = "id", @@ -153,7 +154,7 @@ public interface ActivityInfoProviderService { message = "Internal Server Error. \n Server error occurred while fetching activity data.", response = ErrorResponse.class) }) - @Scope(key = "activity:view", name = "View Activities", description = "") + @Permission(name = "View Activities", permission = "/device-mgt/devices/owning/view") 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 3708677b751..0a450b6ec03 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,6 +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 +82,7 @@ public interface ConfigurationManagementService { "platform configuration.", response = ErrorResponse.class) }) - @Scope(key = "configuration:view", name = "View Configurations", description = "") + @Permission(name = "View Configurations", permission = "/device-mgt/configurations/view") Response getConfiguration( @ApiParam( name = "If-Modified-Since", @@ -127,7 +128,7 @@ public interface ConfigurationManagementService { "Server error occurred while modifying general platform configuration.", response = ErrorResponse.class) }) - @Scope(key = "configuration:modify", name = "Modify Configurations", description = "") + @Permission(name = "Manage configurations", permission = "/device-mgt/configurations/manage") 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 ce100352dad..e1240f9dd4b 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,6 +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; @@ -92,7 +93,7 @@ public interface DeviceManagementService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getDevices( @ApiParam( name = "name", @@ -199,7 +200,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving information requested device.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getDevice( @ApiParam( name = "type", @@ -281,7 +282,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving feature list of the device.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getFeaturesOfDevice( @ApiParam( name = "type", @@ -357,7 +358,7 @@ public interface DeviceManagementService { "Server error occurred while enrolling the device.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response searchDevices( @ApiParam( name = "offset", @@ -436,8 +437,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving installed application list of the device.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") - + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getInstalledApplications( @ApiParam( name = "type", @@ -533,7 +533,7 @@ public interface DeviceManagementService { "Server error occurred while retrieving operation list scheduled for the device.", response = ErrorResponse.class) }) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getDeviceOperations( @ApiParam( name = "type", @@ -631,7 +631,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") Response getEffectivePolicyOfDevice( @ApiParam( name = "type", @@ -683,7 +683,7 @@ public interface DeviceManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") 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/DeviceTypeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java index 2da0537b6bc..b9a24fbafe4 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceTypeManagementService.java @@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -78,7 +79,7 @@ public interface DeviceTypeManagementService { response = ErrorResponse.class) } ) - @Scope(key = "device-type:admin:view", name = "View device types", description = "") + @Permission(name = "View Device Types", permission = "/device-mgt/devices/owning/view") Response getDeviceTypes( @ApiParam( name = "If-Modified-Since", diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index 2fa4297881a..cf5b2882fa4 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 @@ -82,7 +82,7 @@ public interface GroupManagementService { // // @GET // @Path("/{groupName}/devices") -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/admin/groups/roles"}) +// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/groups/roles"}) // Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, // @QueryParam("limit") int limit); // 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 34bc726c66d..e0a2a3b1f72 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,6 +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.notification.mgt.Notification; import org.wso2.carbon.device.mgt.jaxrs.NotificationList; @@ -90,7 +91,7 @@ public interface NotificationManagementService { "\n Server error occurred while fetching the notification list.", response = ErrorResponse.class) }) - @Scope(key = "notification:view", name = "View and manage notifications", description = "") + @Permission(name = "View notifications", permission = "/device-mgt/notifications/view") Response getNotifications( @ApiParam( name = "status", @@ -142,7 +143,7 @@ public interface NotificationManagementService { message = "Error occurred while updating notification status.") } ) - @Scope(key = "notification:view", name = "View and manage notifications", description = "") + @Permission(name = "View notifications", permission = "/device-mgt/notifications/view") 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 1ede29f3e87..70edb9126f9 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,6 +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.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper; @@ -100,7 +101,7 @@ public interface PolicyManagementService { "Server error occurred while adding a new policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response addPolicy( @ApiParam( name = "policy", @@ -154,7 +155,7 @@ public interface PolicyManagementService { "policies."), response = ErrorResponse.class) }) - @Scope(key = "policy:view", name = "Views policies", description = "") + @Permission(name = "View policies", permission = "/device-mgt/policies/view") Response getPolicies( @ApiParam( name = "If-Modified-Since", @@ -220,7 +221,7 @@ public interface PolicyManagementService { "policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:view", name = "View policies", description = "") + @Permission(name = "View policies", permission = "/device-mgt/policies/view") Response getPolicy( @ApiParam( name = "id", @@ -284,7 +285,7 @@ public interface PolicyManagementService { "Server error occurred while updating the policy.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response updatePolicy( @ApiParam( name = "id", @@ -330,7 +331,7 @@ public interface PolicyManagementService { "Server error occurred while bulk removing policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response removePolicies( @ApiParam( name = "policyIds", @@ -366,7 +367,7 @@ public interface PolicyManagementService { message = "ErrorResponse in activating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response activatePolicies( @ApiParam( name = "policyIds", @@ -374,7 +375,7 @@ public interface PolicyManagementService { required = true) List policyIds); - @PUT + @POST @Path("/deactivate-policy") @ApiOperation( consumes = MediaType.APPLICATION_JSON, @@ -402,7 +403,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response deactivatePolicies( @ApiParam( name = "policyIds", @@ -435,7 +436,7 @@ public interface PolicyManagementService { message = "ErrorResponse in deactivating policies.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") Response applyChanges(); @@ -464,7 +465,7 @@ public interface PolicyManagementService { message = "Exception in updating policy priorities.", response = ErrorResponse.class) }) - @Scope(key = "policy:manage", name = "Add policies", description = "") + @Permission(name = "Manage policies", permission = "/device-mgt/policies/manage") 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 b85b605ead0..4571c02a83e 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,10 +20,12 @@ package org.wso2.carbon.device.mgt.jaxrs.service.api; import io.swagger.annotations.*; import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.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.user.mgt.common.UIPermissionNode; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -76,7 +78,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while fetching requested list of roles.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") + @Permission(name = "View Roles", permission = "/device-mgt/roles/view") Response getRoles( @ApiParam( name = "filter", @@ -105,16 +107,16 @@ public interface RoleManagementService { @QueryParam("limit") int limit); @GET - @Path("/scopes") + @Path("/{roleName}/permissions") @ApiOperation( produces = MediaType.APPLICATION_JSON, httpMethod = "GET", - value = "Getting authorization scopes.", + value = "Getting permission details of a role.", notes = "In an organization an individual is associated a with set of responsibilities based on their " + - "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 " + + "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 " + "so using this REST API.", - response = List.class, + response = UIPermissionNode.class, responseContainer = "List", tags = "Role Management" ) @@ -122,8 +124,8 @@ public interface RoleManagementService { value = { @ApiResponse( code = 200, - message = "OK. \n Successfully fetched the scopes list.", - response = List.class, + message = "OK. \n Successfully fetched the permission list of the given role.", + response = UIPermissionNode.class, responseContainer = "List", responseHeaders = { @ResponseHeader( @@ -158,8 +160,13 @@ public interface RoleManagementService { message = "Internal Server ErrorResponse. \n Server error occurred while fetching the permission list of the requested role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") - Response getScopes( + @Permission(name = "View Roles", permission = "/device-mgt/roles/view") + Response getPermissionsOfRole( + @ApiParam( + name = "roleName", + value = "Name of the role.", + required = true) + @PathParam("roleName") String roleName, @ApiParam( name = "If-Modified-Since", value = "Validates if the requested variant has not been modified since the time specified", @@ -216,7 +223,7 @@ public interface RoleManagementService { "requested role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:view", name = "View roles", description = "") + @Permission(name = "View Roles", permission = "/device-mgt/roles/view") Response getRole( @ApiParam( name = "roleName", @@ -276,7 +283,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while adding a new role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") + @Permission(name = "Manage Roles", permission = "/device-mgt/roles/manage") Response addRole( @ApiParam( name = "role", @@ -326,7 +333,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while updating the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") + @Permission(name = "Manage Roles", permission = "/device-mgt/roles/manage") Response updateRole( @ApiParam( name = "roleName", @@ -363,7 +370,7 @@ public interface RoleManagementService { message = "Internal Server Error. \n Server error occurred while removing the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") + @Permission(name = "Manage Roles", permission = "/device-mgt/roles/manage") Response deleteRole( @ApiParam( name = "roleName", @@ -421,7 +428,7 @@ public interface RoleManagementService { "Server error occurred while updating the user list of the role.", response = ErrorResponse.class) }) - @org.wso2.carbon.apimgt.annotations.api.Scope(key = "role:manage", name = "Add roles", description = "") + @Permission(name = "Manage Roles", permission = "/device-mgt/roles/manage") 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 27fdf848e03..ce403fa2813 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,6 +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.*; @@ -83,7 +84,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while adding a new user.", response = ErrorResponse.class) }) - @Scope(key = "user:manage", name = "Add users", description = "") + @Permission(name = "Manage Users", permission = "/device-mgt/users/manage") Response addUser( @ApiParam( name = "user", @@ -135,7 +136,7 @@ public interface UserManagementService { " fetching the requested user.", response = ErrorResponse.class) }) - @Scope(key = "user:view", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/view") Response getUser( @ApiParam( name = "username", @@ -192,7 +193,7 @@ public interface UserManagementService { "Server error occurred while updating the user.", response = ErrorResponse.class) }) - @Scope(key = "user:manage", name = "Add users", description = "") + @Permission(name = "Manage Users", permission = "/device-mgt/users/manage") Response updateUser( @ApiParam( name = "username", @@ -227,7 +228,7 @@ public interface UserManagementService { response = ErrorResponse.class ) }) - @Scope(key = "user:manage", name = "Add users", description = "") + @Permission(name = "Manage Users", permission = "/device-mgt/users/manage") Response removeUser( @ApiParam(name = "username", value = "Username of the user to be deleted.", required = true) @PathParam("username") String username); @@ -276,7 +277,7 @@ public interface UserManagementService { " assigned to the user.", response = ErrorResponse.class) }) - @Scope(key = "user:view", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/view") Response getRolesOfUser( @ApiParam(name = "username", value = "Username of the user.", required = true) @PathParam("username") String username); @@ -287,12 +288,12 @@ public interface UserManagementService { httpMethod = "GET", value = "Get user list", notes = "If you wish to get the details of all the users registered with EMM, you can do so " - + "using the REST API", + + "using this REST API", tags = "User Management") @ApiResponses(value = { @ApiResponse( code = 200, - message = "OK. \n Successfully fetched the requested role.", + message = "OK. \n Successfully fetched the requested users.", response = BasicUserInfoList.class, responseHeaders = { @ResponseHeader( @@ -319,7 +320,7 @@ public interface UserManagementService { message = "Internal Server Error. \n Server error occurred while fetching the user list.", response = ErrorResponse.class) }) - @Scope(key = "user:view", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/view") Response getUsers( @ApiParam( name = "filter", @@ -342,6 +343,36 @@ public interface UserManagementService { required = false) @QueryParam("limit") int limit); + @GET + @Path("/count") + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get user count", + notes = "If you wish to get the user count registered with EMM, you can do so using this REST API", + tags = "User Management") + @ApiResponses(value = { + @ApiResponse( + code = 200, + message = "OK. \n Successfully fetched the user count.", + response = BasicUserInfoList.class, + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body") + }), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported", + response = ErrorResponse.class), + @ApiResponse( + code = 500, + message = "Internal Server Error. \n Server error occurred while fetching the user list.", + response = ErrorResponse.class) + }) + @Permission(name = "View Users", permission = "/device-mgt/users/view") + Response getUserCount(); + @GET @Path("/search/usernames") @ApiOperation( @@ -386,7 +417,7 @@ public interface UserManagementService { "list that matches the given filter.", response = ErrorResponse.class) }) - @Scope(key = "user:view", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/view") Response getUserNames( @ApiParam( name = "filter", @@ -440,7 +471,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Scope(key = "user:view", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/view") Response resetPassword( @ApiParam( name = "username", @@ -483,7 +514,7 @@ public interface UserManagementService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Scope(key = "user:manage", name = "Add users", description = "") + @Permission(name = "Manage Users", permission = "/device-mgt/users/manage") 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 546f6d96b19..e5bf357f753 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.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper; @@ -74,7 +75,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Scope(key = "application:manage", name = "Install/Uninstall applications", description = "") + @Permission(name = "Install/Uninstall applications", permission = "/device-mgt/applications/manage") Response installApplication( @ApiParam( name = "applicationWrapper", @@ -113,7 +114,7 @@ public interface ApplicationManagementAdminService { "a given set of devices.", response = ErrorResponse.class) }) - @Scope(key = "application:manage", name = "Install/Uninstall applications", description = "") + @Permission(name = "Install/Uninstall applications", permission = "/device-mgt/applications/manage") 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 66a3c75f057..e6732606592 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.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -85,7 +86,7 @@ public interface DeviceManagementAdminService { message = "Internal Server Error. \n Server error occurred while fetching the device list.", response = ErrorResponse.class) }) - @Scope(key = "device:admin:view", name = "View Devices", description = "") + @Permission(name = "View Devices", permission = "/device-mgt/devices/owning/view") 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 6307ee00e61..6b18ea83671 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,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.apimgt.annotations.api.Scope; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; @@ -68,7 +69,7 @@ public interface UserManagementAdminService { "Server error occurred while updating credentials of the user.", response = ErrorResponse.class) }) - @Scope(key = "user:admin:reset-password", name = "View users", description = "") + @Permission(name = "View Users", permission = "/device-mgt/users/manage") 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/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 9b0c4e9975b..6ef0a8664d9 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 @@ -122,7 +122,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService int count = dmService.getActivityCountUpdatedAfter(timestamp); activityList.setCount(count); if (activities == null || activities.size() == 0) { - if (isIfModifiedSinceSet || isSinceSet) { + if (isIfModifiedSinceSet) { return Response.notModified().build(); } } 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 9cd1bda1ca6..8edc3bc98dd 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 @@ -18,6 +18,7 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl; +import com.google.gson.JsonArray; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.CarbonContext; @@ -50,6 +51,7 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -127,8 +129,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService { request.setSince(sinceDate); result = dms.getAllDevices(request); if (result == null || result.getData() == null || result.getData().size() <= 0) { - return Response.status(Response.Status.OK).entity("No device is modified " + - "after the timestamp provided in 'since' filter").build(); + devices.setList(new ArrayList()); + devices.setCount(0); + return Response.status(Response.Status.OK).entity(devices).build(); } } else { result = dms.getAllDevices(request); 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 f2aeae680d4..bb8759e685e 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 @@ -221,14 +221,22 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { RequestValidationUtil.validatePolicyIds(policyIds); PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService(); boolean policyDeleted = true; + String invalidPolicyIds = ""; try { PolicyAdministratorPoint pap = policyManagementService.getPAP(); for (int i : policyIds) { Policy policy = pap.getPolicy(i); - if (policy == null || !pap.deletePolicy(policy)) { + if (policy == null) { + invalidPolicyIds += i + ","; policyDeleted = false; } } + if(policyDeleted) { + for(int i : policyIds) { + Policy policy = pap.getPolicy(i); + pap.deletePolicy(policy); + } + } } catch (PolicyManagementException e) { String msg = "ErrorResponse occurred while removing policies"; log.error(msg, e); @@ -239,12 +247,14 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { return Response.status(Response.Status.OK).entity("Policies have been successfully deleted").build(); } else { //TODO:Check of this logic is correct - return Response.status(Response.Status.NOT_FOUND).entity( - new ErrorResponse.ErrorResponseBuilder().setMessage("Policy doesn't exist").build()).build(); + String ModifiedInvalidPolicyIds = invalidPolicyIds.substring(0, invalidPolicyIds.length()-1); + return Response.status(Response.Status.BAD_REQUEST).entity( + new ErrorResponse.ErrorResponseBuilder().setMessage("Policies with the policy ID " + + ModifiedInvalidPolicyIds + " doesn't exist").build()).build(); } } - @PUT + @POST @Path("/activate-policy") @Override public Response activatePolicies(List policyIds) { @@ -276,7 +286,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService { } } - @PUT + @POST @Path("/deactivate-policy") @Override public Response deactivatePolicies(List policyIds) { 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 fa7560702cb..6cae3ad776c 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,6 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.CarbonConstants; +import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException; import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; @@ -32,11 +34,11 @@ 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.AuthorizationManager; -import org.wso2.carbon.user.api.UserRealm; -import org.wso2.carbon.user.api.UserStoreException; -import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.api.*; import org.wso2.carbon.user.core.common.AbstractUserStoreManager; +import org.wso2.carbon.user.mgt.UserRealmProxy; +import org.wso2.carbon.user.mgt.common.UIPermissionNode; +import org.wso2.carbon.user.mgt.common.UserAdminException; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @@ -90,26 +92,64 @@ public class RoleManagementServiceImpl implements RoleManagementService { } @GET - @Path("/scopes") + @Path("/{roleName}/permissions") @Override - public Response getScopes( + public Response getPermissionsOfRole( + @PathParam("roleName") String roleName, @HeaderParam("If-Modified-Since") String ifModifiedSince) { - - List scopes = new ArrayList<>(); + RequestValidationUtil.validateRoleName(roleName); try { - ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); - if (scopeManagementService == null) { - log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); - } else { - scopes = DeviceMgtUtil.convertAPIScopestoScopes(scopeManagementService.getAllScopes()); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); + if (!userRealm.getUserStoreManager().isExistingRole(roleName)) { + return Response.status(404).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 + "'"); + } } - return Response.status(Response.Status.OK).entity(scopes).build(); - } catch (ScopeManagementException e) { - String msg = "Error occurred while retrieving the scopes"; + 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"; + 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; + } + } + } + } + rolePermissions.setNodeList(deviceMgtPermissions); + return rolePermissions; } @GET @@ -122,49 +162,62 @@ public class RoleManagementServiceImpl implements RoleManagementService { } RequestValidationUtil.validateRoleName(roleName); RoleInfo roleInfo = new RoleInfo(); - List scopes = new ArrayList<>(); try { final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(Response.Status.NOT_FOUND).entity( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } - ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); - if (scopeManagementService == null) { - log.error("Scope management service initialization is failed, hence scopes will not be retrieved"); - } else { - scopes = DeviceMgtUtil.convertAPIScopesToScopeKeys(scopeManagementService.getScopesOfRole(roleName)); - } roleInfo.setRoleName(roleName); roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName)); - roleInfo.setScopes(scopes); + // 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 e) { + } catch (UserStoreException | UserAdminException e) { String msg = "Error occurred while retrieving the user 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 retrieving the scopes"; - log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } + 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"); } - userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), null); + 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); //TODO fix what's returned in the entity return Response.created(new URI(API_BASE_PATH + "/" + roleInfo.getRoleName())).entity( @@ -194,7 +247,7 @@ public class RoleManagementServiceImpl implements RoleManagementService { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(Response.Status.NOT_FOUND).entity( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } @@ -220,12 +273,14 @@ public class RoleManagementServiceImpl implements RoleManagementService { userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd); } - 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(), roleName); + 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); + } } } //TODO: Need to send the updated role information in the entity back to the client @@ -236,11 +291,6 @@ 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(); } } @@ -249,12 +299,11 @@ public class RoleManagementServiceImpl implements RoleManagementService { @Override public Response deleteRole(@PathParam("roleName") String roleName) { RequestValidationUtil.validateRoleName(roleName); - try { final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm(); final UserStoreManager userStoreManager = userRealm.getUserStoreManager(); if (!userStoreManager.isExistingRole(roleName)) { - return Response.status(Response.Status.NOT_FOUND).entity( + return Response.status(404).entity( new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" + roleName + "'").build()).build(); } @@ -267,26 +316,12 @@ public class RoleManagementServiceImpl implements RoleManagementService { // Delete all authorizations for the current role before deleting authorizationManager.clearRoleAuthorization(roleName); - //removing scopes - ScopeManagementService scopeManagementService = DeviceMgtAPIUtils.getScopeManagementService(); - if (scopeManagementService == null) { - log.error("Scope management service initialization is failed, hence scopes will not be updated"); - } else { - scopeManagementService.removeScopes(roleName); - } - - return Response.status(Response.Status.OK).entity("Role '" + roleName + "' has " + - "successfully been deleted").build(); + 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 deleting scopes of role '" + roleName + "'"; - log.error(msg, e); - return Response.serverError().entity( - new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java index 6df497f8c1a..294e52928c1 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 @@ -316,6 +316,28 @@ public class UserManagementServiceImpl implements UserManagementService { } } + @GET + @Path("/count") + @Override + public Response getUserCount() { + if (log.isDebugEnabled()) { + log.debug("Getting the user count"); + } + + try { + UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager(); + int userCount = userStoreManager.listUsers("*", -1).length; + BasicUserInfoList result = new BasicUserInfoList(); + result.setCount(userCount); + return Response.status(Response.Status.OK).entity(result).build(); + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving the user count."; + log.error(msg, e); + return Response.serverError().entity( + new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build(); + } + } + @GET @Path("/search/usernames") @Override 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 050e9089cf2..7c77cd9bf44 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 @@ -45,334 +45,334 @@ Devices - /device-mgt/admin/devices + /device-mgt/devices / GET List devices - /device-mgt/admin/devices/List + /device-mgt/devices/List /devices GET Search devices - /device-mgt/admin/devices/Search + /device-mgt/devices/Search /devices/search-devices POST View device - /device-mgt/admin/devices/View + /device-mgt/devices/View /devices/*/* GET View device info - /device-mgt/admin/devices/View + /device-mgt/devices/View /devices/*/*/info GET View device applications - /device-mgt/admin/devices/View-Applications + /device-mgt/devices/View-Applications /devices/*/*/applications GET View device effective-policy - /device-mgt/admin/devices/View-Active-Policy + /device-mgt/devices/View-Active-Policy /devices/*/*/effective-policy GET View devices feature - /device-mgt/admin/devices/View-Features + /device-mgt/devices/View-Features /devices/*/*/features GET View device operations - /device-mgt/admin/devices/View-Operations + /device-mgt/devices/View-Operations /devices/*/*/operations GET View Compliance Data - /device-mgt/admin/devices/View-Compliance-Data + /device-mgt/devices/View-Compliance-Data /devices/*/*/compliance-data GET List all devices - /device-mgt/admin/devices/Admin-View + /device-mgt/devices/Admin-View /admin/devices GET View device types - /device-mgt/admin/devices/Admin-DeviceType-View + /device-mgt/devices/Admin-DeviceType-View /admin/device-types GET Policies - /device-mgt/admin/policies + /device-mgt/policies / GET List policies - /device-mgt/admin/policies/List + /device-mgt/policies/List /policies GET Add Policy - /device-mgt/admin/policies/Add + /device-mgt/policies/Add /policies POST Activate policy - /device-mgt/admin/policies/Activate-Policy + /device-mgt/policies/Activate-Policy /policies/activate-policy PUT Deactivate Policy - /device-mgt/admin/policies/Deactivate-Policy + /device-mgt/policies/Deactivate-Policy /policies/deactivate-policy PUT Remove Policy - /device-mgt/admin/policies/Remove + /device-mgt/policies/Remove /policies/remove-policy POST View Policy - /device-mgt/admin/policies/View + /device-mgt/policies/View /policies/* GET Update Policy - /device-mgt/admin/policies/Update + /device-mgt/policies/Update /policies/* PUT Update Policy - /device-mgt/admin/policies/Update + /device-mgt/policies/Update /policies/apply-changes PUT Update Policy - /device-mgt/admin/policies/Change-Priority + /device-mgt/policies/Change-Priority /policies/priorities PUT Notifications - /device-mgt/admin/notifications + /device-mgt/notifications / GET View notifications - /device-mgt/admin/notifications/View + /device-mgt/notifications/View /notifications GET Mark checked notifications - /device-mgt/admin/notifications/View + /device-mgt/notifications/View /notifications/*/mark-checked PUT Users - /device-mgt/admin/users + /device-mgt/users / GET List users - /device-mgt/admin/users/List + /device-mgt/users/List /users GET Add user - /device-mgt/admin/users/Add + /device-mgt/users/Add /users POST List users - /device-mgt/admin/users/Search + /device-mgt/users/Search /users/search/usernames GET Remove user - /device-mgt/admin/users/Remove + /device-mgt/users/Remove /users/* DELETE View user - /device-mgt/admin/users/View + /device-mgt/users/View /users/* GET Update user - /device-mgt/admin/users/Update + /device-mgt/users/Update /users/* PUT Update user credentials - /device-mgt/admin/users/Change-Password + /device-mgt/users/Change-Password /users/*/credentials PUT View assigned role - /device-mgt/admin/roles/Assigned-Roles + /device-mgt/roles/Assigned-Roles /users/*/roles GET Change any user credentials - /device-mgt/admin/users/Change-Password-Any + /device-mgt/users/Change-Password-Any /admin/users/*/credentials POST Send invitation mail - /device-mgt/admin/users/Send-invitations + /device-mgt/users/Send-invitations /users/send-invitation POST Roles - /device-mgt/admin/roles + /device-mgt/roles / GET List roles - /device-mgt/admin/roles/List + /device-mgt/roles/List /roles GET Add role - /device-mgt/admin/roles/Add + /device-mgt/roles/Add /roles POST Remove role - /device-mgt/admin/roles/Remove + /device-mgt/roles/Remove /roles/* DELETE View role - /device-mgt/admin/roles/View + /device-mgt/roles/View /roles/* GET Update role - /device-mgt/admin/roles/Update + /device-mgt/roles/Update /roles/* PUT View role permissions - /device-mgt/admin/roles/View-Permission + /device-mgt/roles/View-Permission /roles/*/permissions GET Add Users to role - /device-mgt/admin/roles/Add-Users + /device-mgt/roles/Add-Users /roles/*/users PUT Configurations - /device-mgt/admin/general-configs + /device-mgt/general-configs / GET View configuration - /device-mgt/admin/general-configuration/View + /device-mgt/general-configuration/View /configuration GET Update configuration - /device-mgt/admin/general-configuration/Update + /device-mgt/general-configuration/Update /configuration PUT Activities - /device-mgt/admin/activities + /device-mgt/activities / GET View Activities - /device-mgt/admin/activities/View + /device-mgt/devices/owning/view /activities GET View Activity Details - /device-mgt/admin/activities/View + /device-mgt/devices/owning/view /activities/* GET Applications - /device-mgt/admin/applications + /device-mgt/applications / GET Install Applications - /device-mgt/admin/application/Install + /device-mgt/application/Install /admin/applications/install-application POST Uninstall-Applications - /device-mgt/admin/application/Uninstall + /device-mgt/application/Uninstall /admin/applications/uninstall-application POST 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 c771e8dfb43..0e9682bb860 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 @@ -21,7 +21,7 @@ device-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroupConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroupConstants.java index 24c4089b243..aab0fc16f3a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroupConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceGroupConstants.java @@ -67,7 +67,7 @@ public class DeviceGroupConstants { public static class Permissions { public static final String[] DEFAULT_ADMIN_PERMISSIONS = - {"/permission/device-mgt/admin/groups", "/permission/device-mgt/user/groups"}; + {"/permission/device-mgt/groups", "/permission/device-mgt/user/groups"}; public static final String[] DEFAULT_OPERATOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_operation"}; public static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS = diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java index c5c2656fc62..3a383b19dc9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/notification/mgt/Notification.java @@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.common.notification.mgt; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; /** * DTO of Notification object which is used to communicate Operation notifications to MDM core. @@ -58,6 +57,16 @@ public class Notification { "CHECKED: The message is in the read state.", required = true) private Status status; + @JsonProperty(value = "deviceIdentifier", required = false) + @ApiModelProperty(name = "deviceIdentifier", value = "Defines the device ID related to the notification.", + required = false) + private String deviceIdentifier; + + @JsonProperty(value = "devieType", required = false) + @ApiModelProperty(name = "devieType", value = "Defines the device type related to the notification.", + required = false) + private String deviceType; + public Status getStatus() { return status; } @@ -90,6 +99,22 @@ public class Notification { this.operationId = operationId; } + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } + + public String getDevcieType() { + return deviceType; + } + + public void setDeviceType(String devieType) { + this.deviceType = devieType; + } + @Override public String toString() { return "notification {" + @@ -97,6 +122,8 @@ public class Notification { ", status=" + status + ", description='" + description + '\'' + ", operationId='" + operationId + '\'' + + ", deviceIdentifier='" + deviceIdentifier + '\'' + + ", deviceType='" + deviceType + '\'' + '}'; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java index c706ee7a717..28aeb08a760 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/operation/mgt/ActivityStatus.java @@ -30,7 +30,7 @@ import java.util.List; public class ActivityStatus { public enum Status { - IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED + IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED } @ApiModelProperty( 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 6ba2f675c0a..ff194a7b86f 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 @@ -26,18 +26,10 @@ import javax.xml.bind.annotation.XmlRootElement; */ 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 context; - - public String getContext() { - return context; - } - - public void setContext(String context) { - this.context = context; - } public String getUrl() { return url; @@ -55,11 +47,19 @@ public class Permission { this.method = method; } - public String getUrlTemplate() { - return urlTemplate; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getPath() { + return path; } - public void setUrlTemplate(String urlTemplate) { - this.urlTemplate = urlTemplate; + public void setPath(String path) { + this.path = path; } } 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 10bb59bcb4d..5a310136632 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 @@ -32,7 +32,7 @@ public interface PermissionManagerService { * @throws PermissionManagementException If some unusual behaviour is observed while adding the * permission. */ - void addPermission(Permission permission) throws PermissionManagementException; + boolean 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 603587d641d..dcc2873242f 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 @@ -22,7 +22,7 @@ org.wso2.carbon.devicemgt device-mgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml 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 60b791a5fad..31d1be6658a 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 @@ -47,7 +47,8 @@ import java.util.Map; */ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthorizationService { - private final static String CDM_ADMIN_PERMISSION = "/device-mgt/admin"; + private final static String CDM_ADMIN_PERMISSION = "/device-mgt/devices/any/permitted-actions-upon-owning-device"; + private final static String CDM_ADMIN = "Device Management Administrator"; private static Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceImpl.class); public DeviceAccessAuthorizationServiceImpl() { @@ -243,7 +244,10 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori } private boolean addAdminPermissionToRegistry() throws PermissionManagementException { - return PermissionUtils.putPermission(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION)); + Permission permission = new Permission(); + permission.setName(CDM_ADMIN); + permission.setPath(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION)); + return PermissionUtils.putPermission(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 index a847255a6e6..855698032bf 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 @@ -21,8 +21,8 @@ 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 org.wso2.carbon.device.mgt.common.permission.mgt.Permission; import javax.servlet.ServletContext; import javax.ws.rs.*; @@ -91,21 +91,20 @@ public class AnnotationProcessor { * @param entityClasses * @return */ - public List - extractPermissions(Set entityClasses) { + public List + extractPermissions(Set entityClasses) { - List permissions = new ArrayList<>(); + List permissions = new ArrayList<>(); if (entityClasses != null && !entityClasses.isEmpty()) { for (final String className : entityClasses) { - List resourcePermissions = + List resourcePermissions = AccessController.doPrivileged(new PrivilegedAction>() { public List run() { Class clazz; - List apiPermissions = - new ArrayList<>(); + List apiPermissions = new ArrayList<>(); try { clazz = classLoader.loadClass(className); @@ -114,7 +113,7 @@ public class AnnotationProcessor { .class.getName()); Annotation apiAnno = clazz.getAnnotation(apiClazz); - List resourceList; + List resourceList; if (apiAnno != null) { @@ -170,15 +169,13 @@ public class AnnotationProcessor { * @return * @throws Throwable */ - private List - getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable { + private List getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable { - List permissions = new ArrayList<>(); + List permissions = new ArrayList<>(); + Permission permission; 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); @@ -187,9 +184,7 @@ public class AnnotationProcessor { } else { subCtx = WILD_CARD; } - permission.setContext(makeContextURLReady(resourceRootContext)); - permission.setUrlTemplate(makeContextURLReady(subCtx)); - + permission = new Permission(); // 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)) { @@ -203,10 +198,14 @@ public class AnnotationProcessor { httpMethod = getHTTPMethodAnnotation(annotations[i]); if (httpMethod != null) { permission.setMethod(httpMethod); - break; + } + if (annotations[i].annotationType().getName(). + equals(org.wso2.carbon.apimgt.annotations.api.Permission.class.getName())) { + this.setPermission(method, permission); } } permissions.add(permission); + } } return permissions; @@ -214,6 +213,7 @@ public class AnnotationProcessor { /** * Read Method annotations indicating HTTP Methods + * * @param annotation */ private String getHTTPMethodAnnotation(Annotation annotation) { @@ -255,7 +255,7 @@ public class AnnotationProcessor { * @return */ private String makeContextURLReady(String context) { - if (context != null && ! context.isEmpty()) { + if (context != null && !context.isEmpty()) { if (context.startsWith("/")) { return context; } else { @@ -294,19 +294,15 @@ public class AnnotationProcessor { * @param servletContext * @return null if cannot determin /WEB-INF/classes */ - public static URL findWebInfClassesPath(ServletContext servletContext) - { + 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 - { + try { URI uri = fp.toURI(); return uri.toURL(); - } - catch (MalformedURLException e) - { + } catch (MalformedURLException e) { throw new RuntimeException(e); } } @@ -329,4 +325,24 @@ public class AnnotationProcessor { return replacedPath.toString(); } + private void setPermission(Method currentMethod, Permission permission) throws Throwable { + Class permissionClass = + (Class) classLoader. + loadClass(org.wso2.carbon.apimgt.annotations.api.Permission.class.getName()); + Annotation permissionAnnotation = currentMethod.getAnnotation(permissionClass); + if (permissionClass != null) { + Method[] permissionClassMethods = permissionClass.getMethods(); + for (Method method : permissionClassMethods) { + switch (method.getName()) { + case "name": + permission.setName(invokeMethod(method, permissionAnnotation, STRING)); + break; + case "permission": + permission.setPath(invokeMethod(method, permissionAnnotation, STRING)); + break; + } + } + } + } + } 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 deleted file mode 100644 index 7911ff7cdfc..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java +++ /dev/null @@ -1,51 +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.config.permission; - -import org.wso2.carbon.device.mgt.common.permission.mgt.Permission; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import java.util.List; - -/** - * This class represents the information related to permissions. - */ -public class PermissionConfiguration { - - private String scopeName; - private String[] permissions; - - public String getScopeName() { - return scopeName; - } - - public void setScopeName(String scope) { - this.scopeName = scope; - } - - public String[] getPermissions() { - return 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 fbde8047e3f..8b7f5b9bca9 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 @@ -28,17 +28,10 @@ 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; import javax.servlet.ServletContext; -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; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java index 44bdd5ba454..44062cffc7e 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/AbstractDeviceDAOImpl.java @@ -416,12 +416,23 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { boolean isOwnershipProvided = false; String status = request.getStatus(); boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; try { conn = this.getConnection(); String sql = "SELECT COUNT(d1.ID) AS DEVICE_COUNT FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID " + - "AND d.TENANT_ID = ?"; + "t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t"; + //Add query for last updated timestamp + if (since != null) { + sql = sql + " , DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } if (deviceType != null && !deviceType.isEmpty()) { sql = sql + " AND t.NAME = ?"; isDeviceTypeProvided = true; @@ -452,12 +463,16 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); int paramIdx = 2; + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); } + stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { stmt.setString(paramIdx++, request.getOwnership()); @@ -748,10 +763,9 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO { ResultSet rs = null; try { conn = this.getConnection(); - String sql = "SELECT ID AS ENROLMENT_ID FROM DM_ENROLMENT WHERE DEVICE_ID = (SELECT DISTINCT d.ID " + - "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID " + - "AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) " + - "AND STATUS = ? AND TENANT_ID = ?"; + String sql = "SELECT e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID FROM DM_DEVICE d, DM_DEVICE_TYPE t " + + "WHERE d.DEVICE_TYPE_ID = t.ID AND d.DEVICE_IDENTIFICATION = ? AND t.NAME = ? AND d.TENANT_ID = ?) dtm " + + "WHERE e.DEVICE_ID = dtm.ID AND e.STATUS = ? AND e.TENANT_ID = ?;"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceId.getId()); stmt.setString(2, deviceId.getType()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java index 246a1bc1f38..b60072be2ac 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java @@ -59,8 +59,21 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { @@ -73,12 +86,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { isDeviceNameProvided = true; } - //Add query for last updated timestamp - if (since != null) { - sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; - isSinceProvided = true; - } - sql = sql + ") d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ?"; //Add the query for ownership @@ -102,15 +109,16 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); int paramIdx = 2; + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, request.getDeviceType()); } if (isDeviceNameProvided) { stmt.setString(paramIdx++, request.getDeviceName() + "%"); } - if (isSinceProvided) { - stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); - } + stmt.setInt(paramIdx++, tenantId); if (isOwnershipProvided) { stmt.setString(paramIdx++, request.getOwnership()); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java index ced650ebe1b..d070660d7ae 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java @@ -31,6 +31,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -55,6 +56,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnershipProvided = false; String status = request.getStatus(); boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; try { conn = this.getConnection(); String sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT d1.ID AS DEVICE_ID, " + @@ -62,7 +65,20 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT, " + "e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, d.NAME, " + "d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + - "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "DM_DEVICE_TYPE t "; + + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { @@ -98,6 +114,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); int paramIdx = 2; + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, request.getDeviceType()); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java index 878e3107422..26519160258 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java @@ -30,6 +30,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -54,6 +55,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnershipProvided = false; String status = request.getStatus(); boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java index 476b703ad8c..fe942787f89 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java @@ -30,6 +30,7 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; +import java.util.Date; import java.util.List; /** @@ -54,13 +55,28 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { boolean isOwnershipProvided = false; String status = request.getStatus(); boolean isStatusProvided = false; + Date since = request.getSince(); + boolean isSinceProvided = false; try { conn = this.getConnection(); String sql = "SELECT d1.ID AS DEVICE_ID, d1.DESCRIPTION, d1.NAME AS DEVICE_NAME, d1.DEVICE_TYPE, " + "d1.DEVICE_IDENTIFICATION, e.OWNER, e.OWNERSHIP, e.STATUS, e.DATE_OF_LAST_UPDATE, " + "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + - "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE " + + "FROM DM_DEVICE d, DM_DEVICE_TYPE t "; + + //Add the query to filter active devices on timestamp + if (since != null) { + sql = sql + ", DM_DEVICE_DETAIL dt"; + isSinceProvided = true; + } + + sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; + + //Add query for last updated timestamp + if (isSinceProvided) { + sql = sql + " AND dt.DEVICE_ID = d.ID AND dt.UPDATE_TIMESTAMP > ?"; + } //Add the query for device-type if (deviceType != null && !deviceType.isEmpty()) { @@ -96,6 +112,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); int paramIdx = 2; + if (isSinceProvided) { + stmt.setLong(paramIdx++, since.getTime()); + } if (isDeviceTypeProvided) { stmt.setString(paramIdx++, request.getDeviceType()); } @@ -143,7 +162,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.DESCRIPTION, " + "d.NAME, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND t.NAME = ? " + - "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "AND d.TENANT_ID = ?) d1 WHERE d1.ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID" + + " OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setString(1, request.getDeviceType()); stmt.setInt(2, tenantId); @@ -177,7 +197,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "AS DEVICE_TYPE FROM DM_DEVICE d, (SELECT e.OWNER, e.OWNERSHIP, e.ID AS ENROLMENT_ID, " + "e.DEVICE_ID, e.STATUS, e.DATE_OF_LAST_UPDATE, e.DATE_OF_ENROLMENT FROM DM_ENROLMENT e WHERE " + "e.TENANT_ID = ? AND e.OWNER = ?) e1, DM_DEVICE_TYPE t WHERE d.ID = e1.DEVICE_ID " + - "AND t.ID = d.DEVICE_TYPE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "AND t.ID = d.DEVICE_TYPE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwner()); @@ -211,7 +231,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + "d.DESCRIPTION, t.NAME AS DEVICE_TYPE, d.DEVICE_IDENTIFICATION FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.NAME LIKE ? AND d.TENANT_ID = ?) d1 " + - "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + "WHERE DEVICE_ID = e.DEVICE_ID AND TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setString(1, request.getDeviceName() + "%"); stmt.setInt(2, tenantId); @@ -246,8 +267,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "WHERE TENANT_ID = ? AND OWNERSHIP = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? " + - "ROWS FETCH NEXT ? ROWS ONLY"; + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getOwnership()); @@ -282,8 +303,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM (SELECT e.ID, e.DEVICE_ID, e.OWNER, e.OWNERSHIP, e.STATUS, " + "e.DATE_OF_ENROLMENT, e.DATE_OF_LAST_UPDATE, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e " + "WHERE TENANT_ID = ? AND STATUS = ?) e, DM_DEVICE d, DM_DEVICE_TYPE t " + - "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? OFFSET ? ROWS" + - " FETCH NEXT ? ROWS ONLY"; + "WHERE DEVICE_ID = e.DEVICE_ID AND d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ORDER BY ENROLMENT_ID " + + "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, request.getStatus()); @@ -337,7 +358,7 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl { "e.DATE_OF_ENROLMENT, e.ID AS ENROLMENT_ID FROM DM_ENROLMENT e, (SELECT d.ID, d.NAME, " + "d.DESCRIPTION, d.DEVICE_IDENTIFICATION, t.NAME AS DEVICE_TYPE FROM DM_DEVICE d, " + "DM_DEVICE_TYPE t WHERE d.DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?" + filteringString + - ") d1 WHERE d1.ID = e.DEVICE_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; + ") d1 WHERE d1.ID = e.DEVICE_ID ORDER BY ENROLMENT_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/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 cb53d964516..887f5d966e8 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 @@ -31,7 +31,6 @@ 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; @@ -52,7 +51,6 @@ 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; @@ -243,10 +241,6 @@ public class DeviceManagementServiceComponent { = new NotificationManagementServiceImpl(); bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null); - /* Registering Scope Management Service */ - ScopeManagementService scopeManagementService = new ScopeManagementServiceImpl(); - bundleContext.registerService(ScopeManagementService.class.getName(), scopeManagementService, null); - /* Registering DeviceAccessAuthorization Service */ DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl(); DeviceManagementDataHolder.getInstance().setDeviceAccessAuthorizationService(deviceAccessAuthorizationService); 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 index e03a220ed12..2d16f87587a 100644 --- 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 @@ -51,7 +51,7 @@ public class SQLServerNotificationDAOImpl extends AbstractNotificationDAOImpl { "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"; + sql = sql + " ORDER BY n1.NOTIFICATION_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); @@ -92,7 +92,7 @@ public class SQLServerNotificationDAOImpl extends AbstractNotificationDAOImpl { "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"; + sql = sql + " ORDER BY n1.NOTIFICATION_ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"; stmt = conn.prepareStatement(sql); stmt.setInt(1, tenantId); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/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 36f7df6be0a..daa5c37d29c 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 @@ -131,6 +131,8 @@ public class NotificationDAOUtil { notification.setOperationId(rs.getInt("OPERATION_ID")); notification.setDescription(rs.getString("DESCRIPTION")); notification.setStatus(rs.getString("STATUS")); + notification.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION")); + notification.setDeviceType(rs.getString("DEVICE_TYPE")); 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/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 4cebea71953..bd2b6d6f526 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 @@ -24,10 +24,7 @@ import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; -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.operation.mgt.*; import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException; @@ -90,22 +87,29 @@ public class OperationManagerImpl implements OperationManager { @Override public Activity addOperation(Operation operation, - List deviceIds) throws OperationManagementException, InvalidDeviceException { + List deviceIds) + throws OperationManagementException, InvalidDeviceException { if (log.isDebugEnabled()) { log.debug("operation:[" + operation.toString() + "]"); for (DeviceIdentifier deviceIdentifier : deviceIds) { log.debug("device identifier id:[" + deviceIdentifier.getId() + "] type:[" + - deviceIdentifier.getType() + "]"); + deviceIdentifier.getType() + "]"); } } try { - DeviceIDHolder deviceIDHolder = DeviceManagerUtil.validateDeviceIdentifiers(deviceIds); - List validDeviceIds = deviceIDHolder.getValidDeviceIDList(); + DeviceIDHolder deviceValidationResult = DeviceManagerUtil.validateDeviceIdentifiers(deviceIds); + List validDeviceIds = deviceValidationResult.getValidDeviceIDList(); if (validDeviceIds.size() > 0) { - List authorizedDeviceList = this.getAuthorizedDevices(operation, deviceIds); + DeviceIDHolder deviceAuthorizationResult = this.authorizeDevices(operation, validDeviceIds); + List authorizedDeviceList = deviceAuthorizationResult.getValidDeviceIDList(); if (authorizedDeviceList.size() <= 0) { log.info("User : " + getUser() + " is not authorized to perform operations on given device-list."); - return null; + Activity activity = new Activity(); + //Send the operation statuses only for admin triggered operations + String deviceType = validDeviceIds.get(0).getType(); + activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult, + deviceType)); + return activity; } OperationManagementDAOFactory.beginTransaction(); @@ -117,13 +121,13 @@ public class OperationManagerImpl implements OperationManager { boolean hasExistingTaskOperation; int enrolmentId; if (operationDto.getControl() == - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Control.NO_REPEAT) { isNotRepeated = true; } //TODO have to create a sql to load device details from deviceDAO using single query. String operationCode = operationDto.getCode(); - for (DeviceIdentifier deviceId : deviceIds) { + for (DeviceIdentifier deviceId : authorizedDeviceList) { Device device = getDevice(deviceId); enrolmentId = device.getEnrolmentInfo().getId(); //Do not repeat the task operations @@ -134,8 +138,8 @@ public class OperationManagerImpl implements OperationManager { } } else if (isNotRepeated) { operationDAO.updateEnrollmentOperationsStatus(enrolmentId, operationCode, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.REPEATED); + 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, enrolmentId); } else { operationMappingDAO.addOperationMapping(operationId, enrolmentId); @@ -145,8 +149,8 @@ public class OperationManagerImpl implements OperationManager { notificationStrategy.execute(new NotificationContext(deviceId, operation)); } catch (PushNotificationExecutionFailedException e) { log.error("Error occurred while sending push notifications to " + - deviceId.getType() + " device carrying id '" + - deviceId + "'", e); + deviceId.getType() + " device carrying id '" + + deviceId + "'", e); } } } @@ -157,6 +161,12 @@ public class OperationManagerImpl implements OperationManager { activity.setCode(operationCode); activity.setCreatedTimeStamp(new Date().toString()); activity.setType(Activity.Type.valueOf(operationDto.getType().toString())); + //For now set the operation statuses only for admin triggered operations + if (!isScheduledOperation) { + //Get the device-type from 1st valid DeviceIdentifier. We know the 1st element is definitely there. + String deviceType = validDeviceIds.get(0).getType(); + activity.setActivityStatus(this.getActivityStatus(deviceValidationResult, deviceAuthorizationResult, deviceType)); + } return activity; } else { throw new InvalidDeviceException("Invalid device Identifiers found."); @@ -171,21 +181,64 @@ public class OperationManagerImpl implements OperationManager { } } - private List getAuthorizedDevices( + private List getActivityStatus(DeviceIDHolder deviceIdValidationResult, DeviceIDHolder deviceAuthResult, + String deviceType) { + List activityStatuses = new ArrayList<>(); + ActivityStatus activityStatus; + //Add the invalid DeviceIds + for (String id : deviceIdValidationResult.getErrorDeviceIdList()) { + activityStatus = new ActivityStatus(); + activityStatus.setDeviceIdentifier(new DeviceIdentifier(id,deviceType)); + activityStatus.setStatus(ActivityStatus.Status.INVALID); + activityStatuses.add(activityStatus); + } + + //Add the unauthorized DeviceIds + for (String id : deviceAuthResult.getErrorDeviceIdList()) { + activityStatus = new ActivityStatus(); + activityStatus.setDeviceIdentifier(new DeviceIdentifier(id, deviceType)); + activityStatus.setStatus(ActivityStatus.Status.UNAUTHORIZED); + activityStatuses.add(activityStatus); + } + + //Add the authorized DeviceIds + for (DeviceIdentifier id : deviceAuthResult.getValidDeviceIDList()) { + activityStatus = new ActivityStatus(); + activityStatus.setDeviceIdentifier(id); + activityStatus.setStatus(ActivityStatus.Status.PENDING); + activityStatuses.add(activityStatus); + } + return activityStatuses; + } + + private DeviceIDHolder authorizeDevices( Operation operation, List deviceIds) throws OperationManagementException { List authorizedDeviceList; + List unAuthorizedDeviceList = new ArrayList<>(); + DeviceIDHolder deviceIDHolder = new DeviceIDHolder(); try { if (operation != null && isAuthenticationSkippedOperation(operation)) { authorizedDeviceList = deviceIds; } else { - authorizedDeviceList = DeviceManagementDataHolder.getInstance(). - getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds).getAuthorizedDevices(); + boolean isAuthorized; + authorizedDeviceList = new ArrayList<>(); + for (DeviceIdentifier devId : deviceIds) { + isAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService(). + isUserAuthorized(devId); + if (isAuthorized) { + authorizedDeviceList.add(devId); + } else { + unAuthorizedDeviceList.add(devId.getId()); + } + } } } catch (DeviceAccessAuthorizationException e) { throw new OperationManagementException("Error occurred while authorizing access to the devices for user :" + - this.getUser(), e); + this.getUser(), e); } - return authorizedDeviceList; + deviceIDHolder.setValidDeviceIDList(authorizedDeviceList); + deviceIDHolder.setErrorDeviceIdList(unAuthorizedDeviceList); + return deviceIDHolder; } private Device getDevice(DeviceIdentifier deviceId) throws OperationManagementException { @@ -195,7 +248,7 @@ public class OperationManagerImpl implements OperationManager { return deviceDAO.getDevice(deviceId, tenantId); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening a connection the data " + - "source", e); + "source", e); } catch (DeviceManagementDAOException e) { OperationManagementDAOFactory.rollbackTransaction(); throw new OperationManagementException( @@ -211,7 +264,8 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); @@ -231,8 +285,8 @@ public class OperationManagerImpl implements OperationManager { } } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new OperationManagementException( "Error occurred while opening a connection to the data source", e); @@ -250,14 +304,15 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); if (enrolmentId < 0) { throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + - deviceId.getType()); + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); } try { @@ -275,8 +330,8 @@ public class OperationManagerImpl implements OperationManager { paginationResult.setRecordsFiltered(count); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new OperationManagementException( "Error occurred while opening a connection to the data source", e); @@ -289,7 +344,7 @@ public class OperationManagerImpl implements OperationManager { @Override public List getPendingOperations(DeviceIdentifier deviceId) throws - OperationManagementException { + OperationManagementException { if (log.isDebugEnabled()) { log.debug("Device identifier id:[" + deviceId.getId() + "] type:[" + deviceId.getType() + "]"); } @@ -298,14 +353,15 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); if (enrolmentId < 0) { throw new OperationManagementException("Device not found for the given device Identifier:" + - deviceId.getId() + " and given type:" + - deviceId.getType()); + deviceId.getId() + " and given type:" + + deviceId.getType()); } try { @@ -326,8 +382,8 @@ public class OperationManagerImpl implements OperationManager { Collections.sort(operations, new OperationCreateTimeComparator()); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + - "pending operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); + "pending operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new OperationManagementException( "Error occurred while opening a connection to the data source", e); @@ -346,36 +402,37 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); if (enrolmentId < 0) { throw new OperationManagementException("Device not found for given device " + - "Identifier:" + deviceId.getId() + " and given type" + - deviceId.getType()); + "Identifier:" + deviceId.getId() + " and given type" + + deviceId.getType()); } try { OperationManagementDAOFactory.openConnection(); - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. - getNextOperation(enrolmentId); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO.getNextOperation( + enrolmentId); if (dtoOperation != null) { - if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND. - equals(dtoOperation.getType())) { + if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND.equals(dtoOperation.getType() + )) { org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; commandOperation = (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); + getOperation(dtoOperation.getId()); dtoOperation.setEnabled(commandOperation.isEnabled()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG. - equals(dtoOperation.getType())) { + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG.equals(dtoOperation. + getType())) { dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE. - equals(dtoOperation.getType())) { + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.PROFILE.equals(dtoOperation. + getType())) { dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); - } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY. - equals(dtoOperation.getType())) { + } else if (org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.POLICY.equals(dtoOperation. + getType())) { dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); } operation = OperationDAOUtil.convertOperation(dtoOperation); @@ -400,7 +457,8 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); @@ -410,8 +468,10 @@ public class OperationManagerImpl implements OperationManager { boolean isUpdated = false; if (operation.getStatus() != null) { isUpdated = operationDAO.updateOperationStatus(enrolmentId, operationId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status. - valueOf(operation.getStatus().toString())); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status + . + valueOf(operation.getStatus() + .toString())); } if (isUpdated && operation.getOperationResponse() != null) { operationDAO.addOperationResponse(enrolmentId, operationId, operation.getOperationResponse()); @@ -421,7 +481,7 @@ public class OperationManagerImpl implements OperationManager { OperationManagementDAOFactory.rollbackTransaction(); throw new OperationManagementException( "Error occurred while updating the operation: " + operationId + " status:" + - operation.getStatus(), e); + operation.getStatus(), e); } catch (TransactionManagementException e) { throw new OperationManagementException("Error occurred while initiating a transaction", e); } finally { @@ -456,30 +516,35 @@ public class OperationManagerImpl implements OperationManager { Operation operation = null; if (log.isDebugEnabled()) { log.debug("Operation Id: " + operationId + " Device Type: " + deviceId.getType() + " Device Identifier: " + - deviceId.getId()); + deviceId.getId()); } if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); if (enrolmentId < 0) { throw new OperationManagementException("Device not found for given device identifier: " + - deviceId.getId() + " type: " + deviceId.getType()); + deviceId.getId() + " type: " + deviceId.getType()); } try { OperationManagementDAOFactory.openConnection(); org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. - getOperationByDeviceAndId(enrolmentId, operationId); + getOperationByDeviceAndId( + enrolmentId, + operationId); if (dtoOperation.getType(). equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; commandOperation = (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); + getOperation( + dtoOperation + .getId()); dtoOperation.setEnabled(commandOperation.isEnabled()); } else if (dtoOperation.getType(). equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { @@ -494,16 +559,16 @@ public class OperationManagerImpl implements OperationManager { if (dtoOperation == null) { throw new OperationManagementException("Operation not found for operation Id:" + operationId + - " device id:" + deviceId.getId()); + " device id:" + deviceId.getId()); } operation = OperationDAOUtil.convertOperation(dtoOperation); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + deviceId.getId() + "'", e); + "operations assigned for '" + deviceId.getType() + + "' device '" + deviceId.getId() + "'", e); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening connection to the data source", - e); + e); } finally { OperationManagementDAOFactory.closeConnection(); } @@ -519,14 +584,15 @@ public class OperationManagerImpl implements OperationManager { if (!isActionAuthorized(deviceId)) { throw new OperationManagementException("User '" + getUser() + "' is not authorized to access the '" + - deviceId.getType() + "' device, which carries the identifier '" + deviceId.getId() + "'"); + deviceId.getType() + "' device, which carries the identifier '" + + deviceId.getId() + "'"); } int enrolmentId = this.getEnrolmentByStatus(deviceId, EnrolmentInfo.Status.ACTIVE); if (enrolmentId < 0) { throw new OperationManagementException( "Device not found for device id:" + deviceId.getId() + " " + "type:" + - deviceId.getType()); + deviceId.getType()); } try { @@ -535,11 +601,11 @@ public class OperationManagerImpl implements OperationManager { org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.valueOf(status.toString()); dtoOperationList.addAll(commandOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, dtoOpStatus)); dtoOperationList.addAll(configOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); dtoOperationList.addAll(profileOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); dtoOperationList.addAll(policyOperationDAO.getOperationsByDeviceAndStatus(enrolmentId, - org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); + org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status.PENDING)); Operation operation; @@ -550,9 +616,9 @@ public class OperationManagerImpl implements OperationManager { } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the list of " + - "operations assigned for '" + deviceId.getType() + - "' device '" + - deviceId.getId() + "' and status:" + status.toString(), e); + "operations assigned for '" + deviceId.getType() + + "' device '" + + deviceId.getId() + "' and status:" + status.toString(), e); } catch (SQLException e) { throw new OperationManagementException( "Error occurred while opening a connection to the data source", e); @@ -568,31 +634,35 @@ public class OperationManagerImpl implements OperationManager { try { OperationManagementDAOFactory.openConnection(); org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = operationDAO. - getOperation(operationId); + getOperation( + operationId); if (dtoOperation == null) { throw new OperationManagementException("Operation not found for given Id:" + operationId); } - if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + if (dtoOperation.getType() + .equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; commandOperation = (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. - getOperation(dtoOperation.getId()); + getOperation( + dtoOperation + .getId()); dtoOperation.setEnabled(commandOperation.isEnabled()); } else if (dtoOperation.getType(). equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. - PROFILE)) { + PROFILE)) { dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. - POLICY)) { + POLICY)) { dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); } operation = OperationDAOUtil.convertOperation(dtoOperation); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the operation with operation Id '" + - operationId, e); + operationId, e); } catch (SQLException e) { throw new OperationManagementException("Error occurred while opening a connection to the data source", e); } finally { @@ -601,61 +671,61 @@ public class OperationManagerImpl implements OperationManager { return operation; } -// @Override -// public Operation getOperationByActivityId(String activity) throws OperationManagementException { -// // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. -// Operation operation; -// int enrollmentOpMappingId = Integer.parseInt( -// activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); -// if (enrollmentOpMappingId == 0) { -// throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); -// } -// try { -// OperationManagementDAOFactory.openConnection(); -// org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = -// operationDAO.getOperationFromEnrollment(enrollmentOpMappingId); -// -// if (dtoOperation == null) { -// throw new OperationManagementException("Operation not found for given activity Id:" + activity); -// } -// org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus(); -// if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { -// org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; -// commandOperation = -// (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. -// getOperation(dtoOperation.getId()); -// dtoOperation.setEnabled(commandOperation.isEnabled()); -// } else if (dtoOperation.getType(). -// equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { -// dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); -// } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. -// PROFILE)) { -// dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); -// } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. -// POLICY)) { -// dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); -// } -// operation = OperationDAOUtil.convertOperation(dtoOperation); -// int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId); -// if (enrolmentId != 0) { -// operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId())); -// } -// -// operation.setStatus(Operation.Status.valueOf(status.toString())); -// operation.setActivityId(activity); -// -// } catch (SQLException e) { -// throw new OperationManagementException("Error occurred while opening a connection to the data source", e); -// } catch (OperationManagementDAOException e) { -// throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" + -// activity, e); -// } finally { -// OperationManagementDAOFactory.closeConnection(); -// } -// -// // return this.getOperation(operationId); -// return operation; -// } + // @Override + // public Operation getOperationByActivityId(String activity) throws OperationManagementException { + // // This parses the operation id from activity id (ex : ACTIVITY_23) and converts to the integer. + // Operation operation; + // int enrollmentOpMappingId = Integer.parseInt( + // activity.replace(DeviceManagementConstants.OperationAttributes.ACTIVITY, "")); + // if (enrollmentOpMappingId == 0) { + // throw new IllegalArgumentException("Operation ID cannot be null or zero (0)."); + // } + // try { + // OperationManagementDAOFactory.openConnection(); + // org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation dtoOperation = + // operationDAO.getOperationFromEnrollment(enrollmentOpMappingId); + // + // if (dtoOperation == null) { + // throw new OperationManagementException("Operation not found for given activity Id:" + activity); + // } + // org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Status status = dtoOperation.getStatus(); + // if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.COMMAND)) { + // org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation commandOperation; + // commandOperation = + // (org.wso2.carbon.device.mgt.core.dto.operation.mgt.CommandOperation) commandOperationDAO. + // getOperation(dtoOperation.getId()); + // dtoOperation.setEnabled(commandOperation.isEnabled()); + // } else if (dtoOperation.getType(). + // equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type.CONFIG)) { + // dtoOperation = configOperationDAO.getOperation(dtoOperation.getId()); + // } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + // PROFILE)) { + // dtoOperation = profileOperationDAO.getOperation(dtoOperation.getId()); + // } else if (dtoOperation.getType().equals(org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation.Type. + // POLICY)) { + // dtoOperation = policyOperationDAO.getOperation(dtoOperation.getId()); + // } + // operation = OperationDAOUtil.convertOperation(dtoOperation); + // int enrolmentId = operationDAO.getEnrolmentIdFromMappingId(enrollmentOpMappingId); + // if (enrolmentId != 0) { + // operation.setResponses(operationDAO.getOperationResponses(enrolmentId, operation.getId())); + // } + // + // operation.setStatus(Operation.Status.valueOf(status.toString())); + // operation.setActivityId(activity); + // + // } catch (SQLException e) { + // throw new OperationManagementException("Error occurred while opening a connection to the data source", e); + // } catch (OperationManagementDAOException e) { + // throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" + + // activity, e); + // } finally { + // OperationManagementDAOFactory.closeConnection(); + // } + // + // // return this.getOperation(operationId); + // return operation; + // } @Override public Activity getOperationByActivityId(String activity) throws OperationManagementException { @@ -672,7 +742,7 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving the operation with activity Id '" + - activity, e); + activity, e); } finally { OperationManagementDAOFactory.closeConnection(); } @@ -692,7 +762,7 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while getting the activity list changed after a " + - "given time.", e); + "given time.", e); } finally { OperationManagementDAOFactory.closeConnection(); } @@ -708,7 +778,7 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while getting the activity list changed after a " + - "given time.", e); + "given time.", e); } finally { OperationManagementDAOFactory.closeConnection(); } @@ -723,7 +793,7 @@ public class OperationManagerImpl implements OperationManager { throw new OperationManagementException("Error occurred while opening a connection to the data source.", e); } catch (OperationManagementDAOException e) { throw new OperationManagementException("Error occurred while getting the activity count changed after a " + - "given time.", e); + "given time.", e); } finally { OperationManagementDAOFactory.closeConnection(); } @@ -805,8 +875,8 @@ public class OperationManagerImpl implements OperationManager { enrolmentId = deviceDAO.getEnrolmentByStatus(deviceId, status, tenantId); } catch (DeviceManagementDAOException e) { throw new OperationManagementException("Error occurred while retrieving metadata of '" + - deviceId.getType() + "' device carrying the identifier '" + - deviceId.getId() + "'", e); + deviceId.getType() + "' device carrying the identifier '" + + deviceId.getId() + "'", e); } catch (SQLException e) { throw new OperationManagementException( "Error occurred while opening a connection to the data source", e); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java index e22a83c59e0..bfa28a66528 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/OperationManagementDAOFactory.java @@ -28,7 +28,6 @@ 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.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.*; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.H2OperationDAOImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.MySQLOperationDAOImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.OracleOperationDAOImpl; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.operation.PostgreSQLOperationDAOImpl; @@ -77,7 +76,7 @@ public class OperationManagementDAOFactory { case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL: return new PostgreSQLOperationDAOImpl(); case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2: - return new H2OperationDAOImpl(); + return new GenericOperationDAOImpl(); case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL: return new MySQLOperationDAOImpl(); default: diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java index 36bdfd738a9..8a162200328 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/GenericOperationDAOImpl.java @@ -406,30 +406,36 @@ public class GenericOperationDAOImpl implements OperationDAO { // sql = sql + " OFFSET ?"; // } - String sql = "SELECT feom.ENROLMENT_ID, feom.OPERATION_ID, feom.CREATED_TIMESTAMP, o.TYPE AS OPERATION_TYPE, " + - "o.OPERATION_CODE, orsp.OPERATION_RESPONSE, orsp.LATEST_RECEIVED_TIMESTAMP AS RECEIVED_TIMESTAMP, " + - "orsp.ID AS OP_RES_ID, feom.STATUS, feom.UPDATED_TIMESTAMP, feom.DEVICE_IDENTIFICATION, " + - "feom.DEVICE_TYPE FROM (SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.STATUS, eom.CREATED_TIMESTAMP, " + - "eom.UPDATED_TIMESTAMP, fe.DEVICE_IDENTIFICATION, fe.DEVICE_TYPE FROM " + - "(SELECT ENROLMENT_ID, OPERATION_ID, STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP " + - "FROM DM_ENROLMENT_OP_MAPPING WHERE UPDATED_TIMESTAMP > ? ORDER BY OPERATION_ID LIMIT ? OFFSET ?) eom " + - "LEFT OUTER JOIN (SELECT e.ID AS ENROLMENT_ID, d.ID AS DEVICE_ID, d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM DM_ENROLMENT e LEFT OUTER JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " + - "LEFT OUTER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID WHERE d.TENANT_ID = ? AND " + - "e.TENANT_ID = ?) fe ON fe.ENROLMENT_ID = eom.ENROLMENT_ID) feom LEFT OUTER JOIN DM_OPERATION o " + - "ON feom.OPERATION_ID = o.ID LEFT OUTER JOIN (SELECT ID, ENROLMENT_ID, OPERATION_ID, " + - "OPERATION_RESPONSE, MAX(RECEIVED_TIMESTAMP) LATEST_RECEIVED_TIMESTAMP " + - "FROM DM_DEVICE_OPERATION_RESPONSE GROUP BY ENROLMENT_ID , OPERATION_ID) orsp " + - "ON o.ID = orsp.OPERATION_ID AND feom.ENROLMENT_ID = orsp.ENROLMENT_ID GROUP BY feom.ENROLMENT_ID"; + + String sql = "SELECT opm.ENROLMENT_ID, opm.CREATED_TIMESTAMP, opm.UPDATED_TIMESTAMP, opm.OPERATION_ID,\n" + + "op.OPERATION_CODE, op.TYPE as OPERATION_TYPE, opm.STATUS, en.DEVICE_ID,\n" + + "ops.RECEIVED_TIMESTAMP, ops.ID as OP_RES_ID, ops.OPERATION_RESPONSE,\n" + + "de.DEVICE_IDENTIFICATION, dt.NAME as DEVICE_TYPE\n" + + "FROM DM_ENROLMENT_OP_MAPPING AS opm\n" + + "LEFT JOIN DM_OPERATION AS op ON opm.OPERATION_ID = op.ID \n" + + "LEFT JOIN DM_ENROLMENT as en ON opm.ENROLMENT_ID = en.ID \n" + + "LEFT JOIN DM_DEVICE as de ON en.DEVICE_ID = de.ID \n" + + "LEFT JOIN DM_DEVICE_TYPE as dt ON dt.ID = de.DEVICE_TYPE_ID \n" + + "LEFT JOIN DM_DEVICE_OPERATION_RESPONSE as ops ON \n" + + "opm.ENROLMENT_ID = ops.ENROLMENT_ID AND opm.OPERATION_ID = ops.OPERATION_ID \n" + + "WHERE opm.UPDATED_TIMESTAMP > ? \n" + + "AND de.TENANT_ID = ? \n"; + + if(timestamp == 0){ + sql += "ORDER BY opm.OPERATION_ID LIMIT ? OFFSET ?;"; + }else{ + sql += "ORDER BY opm.UPDATED_TIMESTAMP asc LIMIT ? OFFSET ?"; + } + + stmt = conn.prepareStatement(sql); stmt.setLong(1, timestamp); - stmt.setInt(2, limit); - stmt.setInt(3, offset); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); + stmt.setInt(2, tenantId); + stmt.setInt(3, limit); + stmt.setInt(4, offset); rs = stmt.executeQuery(); 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/H2OperationDAOImpl.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/H2OperationDAOImpl.java deleted file mode 100644 index ef2b57b2a55..00000000000 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/dao/impl/operation/H2OperationDAOImpl.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright (c) 2016a, 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.operation.mgt.dao.impl.operation; - -import org.wso2.carbon.context.PrivilegedCarbonContext; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.operation.mgt.Activity; -import org.wso2.carbon.device.mgt.common.operation.mgt.ActivityStatus; -import org.wso2.carbon.device.mgt.common.operation.mgt.OperationResponse; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOException; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOUtil; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.impl.GenericOperationDAOImpl; -import org.wso2.carbon.device.mgt.core.operation.mgt.dao.util.OperationDAOUtil; - -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.List; - -/** - * This class holds the implementation of OperationDAO which can be used to support H2 db syntax. - */ -public class H2OperationDAOImpl extends GenericOperationDAOImpl { - - @Override - public List getActivitiesUpdatedAfter(long timestamp, int limit, int offset) throws OperationManagementDAOException { - PreparedStatement stmt = null; - ResultSet rs = null; - List activities = new ArrayList<>(); - try { - Connection conn = OperationManagementDAOFactory.getConnection(); - String sql = "SELECT feom.ENROLMENT_ID, feom.OPERATION_ID, feom.CREATED_TIMESTAMP, o.TYPE AS OPERATION_TYPE, " + - "o.OPERATION_CODE, orsp.OPERATION_RESPONSE, orsp.LATEST_RECEIVED_TIMESTAMP AS RECEIVED_TIMESTAMP, " + - "orsp.ID AS OP_RES_ID, feom.STATUS, feom.UPDATED_TIMESTAMP, feom.DEVICE_IDENTIFICATION, " + - "feom.DEVICE_TYPE FROM (SELECT eom.ENROLMENT_ID, eom.OPERATION_ID, eom.STATUS, eom.CREATED_TIMESTAMP, " + - "eom.UPDATED_TIMESTAMP, fe.DEVICE_IDENTIFICATION, fe.DEVICE_TYPE FROM " + - "(SELECT ENROLMENT_ID, OPERATION_ID, STATUS, CREATED_TIMESTAMP, UPDATED_TIMESTAMP " + - "FROM DM_ENROLMENT_OP_MAPPING WHERE UPDATED_TIMESTAMP > ? ORDER BY OPERATION_ID LIMIT ? OFFSET ?) eom " + - "LEFT OUTER JOIN (SELECT e.ID AS ENROLMENT_ID, d.ID AS DEVICE_ID, d.DEVICE_IDENTIFICATION, " + - "t.NAME AS DEVICE_TYPE FROM DM_ENROLMENT e LEFT OUTER JOIN DM_DEVICE d ON e.DEVICE_ID = d.ID " + - "LEFT OUTER JOIN DM_DEVICE_TYPE t ON d.DEVICE_TYPE_ID = t.ID WHERE d.TENANT_ID = ? AND " + - "e.TENANT_ID = ?) fe ON fe.ENROLMENT_ID = eom.ENROLMENT_ID) feom LEFT OUTER JOIN DM_OPERATION o " + - "ON feom.OPERATION_ID = o.ID LEFT OUTER JOIN (SELECT ID, ENROLMENT_ID, OPERATION_ID, " + - "OPERATION_RESPONSE, MAX(RECEIVED_TIMESTAMP) LATEST_RECEIVED_TIMESTAMP " + - "FROM DM_DEVICE_OPERATION_RESPONSE GROUP BY ENROLMENT_ID , OPERATION_ID) orsp " + - "ON o.ID = orsp.OPERATION_ID AND feom.ENROLMENT_ID = orsp.ENROLMENT_ID GROUP BY feom.ENROLMENT_ID, " + - "feom.OPERATION_ID, feom.CREATED_TIMESTAMP, o.TYPE, o.OPERATION_CODE, orsp.OPERATION_RESPONSE, " + - "orsp.LATEST_RECEIVED_TIMESTAMP, orsp.ID, feom.STATUS, feom.UPDATED_TIMESTAMP, " + - "feom.DEVICE_IDENTIFICATION, feom.DEVICE_TYPE"; - - stmt = conn.prepareStatement(sql); - - stmt.setLong(1, timestamp); - stmt.setInt(2, limit); - stmt.setInt(3, offset); - int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); - stmt.setInt(4, tenantId); - stmt.setInt(5, tenantId); - - rs = stmt.executeQuery(); - - int operationId = 0; - int enrolmentId = 0; - int responseId = 0; - Activity activity = null; - ActivityStatus activityStatus = null; - while (rs.next()) { - - if (operationId != rs.getInt("OPERATION_ID")) { - activity = new Activity(); - activities.add(activity); - List statusList = new ArrayList<>(); - activityStatus = new ActivityStatus(); - - operationId = rs.getInt("OPERATION_ID"); - enrolmentId = rs.getInt("ENROLMENT_ID"); - - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); - activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); - activity.setCode(rs.getString("OPERATION_CODE")); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); - activityStatus.setDeviceIdentifier(deviceIdentifier); - - activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); - - List operationResponses = new ArrayList<>(); - if (rs.getInt("UPDATED_TIMESTAMP") != 0) { - activityStatus.setUpdatedTimestamp(new java.util.Date( - rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); - - } - if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); - responseId = rs.getInt("OP_RES_ID"); - } - activityStatus.setResponses(operationResponses); - statusList.add(activityStatus); - activity.setActivityStatus(statusList); - activity.setActivityId(OperationDAOUtil.getActivityId(rs.getInt("OPERATION_ID"))); - - } - - if (operationId == rs.getInt("OPERATION_ID") && enrolmentId != rs.getInt("ENROLMENT_ID")) { - activityStatus = new ActivityStatus(); - - activity.setType(Activity.Type.valueOf(rs.getString("OPERATION_TYPE"))); - activity.setCreatedTimeStamp(new java.util.Date(rs.getLong(("CREATED_TIMESTAMP")) * 1000).toString()); - activity.setCode(rs.getString("OPERATION_CODE")); - - DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); - deviceIdentifier.setId(rs.getString("DEVICE_IDENTIFICATION")); - deviceIdentifier.setType(rs.getString("DEVICE_TYPE")); - activityStatus.setDeviceIdentifier(deviceIdentifier); - - activityStatus.setStatus(ActivityStatus.Status.valueOf(rs.getString("STATUS"))); - - List operationResponses = new ArrayList<>(); - if (rs.getInt("UPDATED_TIMESTAMP") != 0) { - activityStatus.setUpdatedTimestamp(new java.util.Date( - rs.getLong(("UPDATED_TIMESTAMP")) * 1000).toString()); - } - if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - operationResponses.add(OperationDAOUtil.getOperationResponse(rs)); - responseId = rs.getInt("OP_RES_ID"); - } - activityStatus.setResponses(operationResponses); - activity.getActivityStatus().add(activityStatus); - - enrolmentId = rs.getInt("ENROLMENT_ID"); - } - - if (rs.getInt("OP_RES_ID") != 0 && responseId != rs.getInt("OP_RES_ID")) { - if (rs.getTimestamp("RECEIVED_TIMESTAMP") != (null)) { - activityStatus.getResponses().add(OperationDAOUtil.getOperationResponse(rs)); - responseId = rs.getInt("OP_RES_ID"); - } - } - } - } catch (SQLException e) { - throw new OperationManagementDAOException("Error occurred while getting the operation details from " + - "the database.", e); - } catch (ClassNotFoundException e) { - throw new OperationManagementDAOException("Error occurred while converting the operation response to string.", e); - } catch (IOException e) { - throw new OperationManagementDAOException("IO exception occurred while converting the operations responses.", e); - } finally { - OperationManagementDAOUtil.cleanupResources(stmt, rs); - } - return activities; - } -} \ 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/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 0cdae216175..1cd85960f03 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 @@ -53,9 +53,11 @@ public class PermissionManagerServiceImpl implements PermissionManagerService { } @Override - public void addPermission(Permission permission) throws PermissionManagementException { + public boolean addPermission(Permission permission) throws PermissionManagementException { // adding a permission to the tree + permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath())); 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/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 9f73a36e1c1..35f6a6d6eb1 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 @@ -66,24 +66,23 @@ public class PermissionUtils { 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(String permissionPath) - throws PermissionManagementException { + 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(permissionPath, "/"); + StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/"); String lastToken = "", currentToken, tempPath; while (tokenizer.hasMoreTokens()) { currentToken = tokenizer.nextToken(); @@ -95,7 +94,8 @@ public class PermissionUtils { } status = true; } catch (RegistryException e) { - throw new PermissionManagementException("Error occurred while persisting permission", e); + throw new PermissionManagementException("Error occurred while persisting permission : " + + permission.getName(), e); } return status; } @@ -116,17 +116,17 @@ public class PermissionUtils { 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(); - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - 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(); + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + 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/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java index 258aa3c22ba..f02f9c03341 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java @@ -181,7 +181,7 @@ public interface DeviceManagementProviderService { * @return true if the user owns the device else will return false. * @throws DeviceManagementException If some unusual behaviour is observed while fetching the device. */ - public boolean isEnrolled(DeviceIdentifier deviceId, String user) throws DeviceManagementException; + boolean isEnrolled(DeviceIdentifier deviceId, String user) throws DeviceManagementException; License getLicense(String deviceType, String languageCode) throws DeviceManagementException; 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 9e8d37b6625..17023a5a31b 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 @@ -342,12 +342,10 @@ public final class DeviceManagerUtil { if (isValidDeviceIdentifier(deviceIdentifier)) { validDeviceIDList.add(deviceIdentifier); } else { - errorDeviceIdList.add(String.format(OperationMgtConstants.DeviceConstants. - DEVICE_ID_NOT_FOUND, deviceID)); + errorDeviceIdList.add(deviceID); } } catch (DeviceManagementException e) { - errorDeviceIdList.add(String.format(OperationMgtConstants.DeviceConstants.DEVICE_ID_SERVICE_NOT_FOUND, - deviceIDCounter)); + errorDeviceIdList.add(deviceID); } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml index 07f1fb08409..7ba9b062db7 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml index c5b15c32790..a3105e9ef02 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/pom.xml @@ -22,7 +22,7 @@ device-mgt org.wso2.carbon.devicemgt - 1.1.3-SNAPSHOT + 1.2.1-SNAPSHOT ../pom.xml diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/assembly/src.xml b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/assembly/src.xml index c9805f89463..5aeaa05a35a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/assembly/src.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/assembly/src.xml @@ -28,13 +28,15 @@ ${basedir}/src + ${basedir}/src/main/resources/jaggeryapps/devicemgt /jaggeryapps/devicemgt-cdmf/ true + ${basedir}/src/main/resources/jaggeryapps/uuf-template-app - /jaggeryapps/devicemgt-cdmf/ + /jaggeryapps/uuf-template-app/ true 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 ecb9806b5d2..d0fc9c4f705 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 @@ -152,7 +152,7 @@ if (!user) { result = responsePayload.responseText; }); } else if (uriMatcher.match("/{context}/api/devices/")) { - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) { result = deviceModule.listDevices(); } else { response.sendError(403); @@ -161,7 +161,7 @@ if (!user) { elements = uriMatcher.elements(); deviceId = elements.deviceId; type = elements.type; - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/devices/list")) { result = deviceModule.viewDevice(type, deviceId); }else { response.sendError(403); @@ -171,7 +171,7 @@ if (!user) { deviceId = elements.deviceId; type = elements.type; operation = elements.operation; - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/devices/operation")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/devices/operation")) { result = deviceModule.performOperation(deviceId, operation, [], type); } else { response.sendError(403); 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 465e8961813..7303a5ee8c6 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 @@ -98,7 +98,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { /* @Deprecated */ - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/invite")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/user/invite")) { elements = uriMatcher.elements(); username = elements.username; userModule.inviteUser(username); @@ -109,7 +109,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { /* @Deprecated */ - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/add")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/user/add")) { addUserFormData = request.getContent(); username = addUserFormData.username; firstname = addUserFormData.firstname; @@ -160,7 +160,7 @@ if (uriMatcher.match("/{context}/api/user/authenticate")) { /* @Deprecated */ - if (userModule.isAuthorized("/permission/admin/device-mgt/admin/user/remove")) { + if (userModule.isAuthorized("/permission/admin/device-mgt/user/remove")) { elements = uriMatcher.elements(); username = elements.username; try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/layouts/cdmf.layout.default.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/layouts/cdmf.layout.default.hbs index e4e75b3bd0b..e0b66efd3e1 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/layouts/cdmf.layout.default.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/layouts/cdmf.layout.default.hbs @@ -30,21 +30,22 @@ under the License. --}} -
-
-
- - - - - GO BACK -
-
- + + {{defineZone "header"}} @@ -58,8 +59,10 @@ under the License. --}}
{{defineZone "contentTitle"}} -
- {{defineZone "content"}} +
+
+ {{defineZone "content"}} +
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js index 4b205346d9a..6c7dbcc1742 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/device.js @@ -40,7 +40,7 @@ deviceModule = function () { // var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager"; -/** + /** * Only GET method is implemented for now since there are no other type of methods used this method. * @param url - URL to call the backend without the host * @param method - HTTP Method (GET, POST) @@ -273,6 +273,9 @@ deviceModule = function () { deviceObject[constants["DEVICE_PROPERTIES"]] = properties; response["content"] = deviceObject; return response; + } else if (backendResponse.status == 401) { + response["status"] = "unauthorized"; + return response; } else { response["status"] = "error"; return response; @@ -295,20 +298,20 @@ deviceModule = function () { var url; if (uiPermissions.LIST_DEVICES) { url = devicemgtProps["httpsURL"] + - devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/count"; + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices?offset=0&limit=1"; } else if (uiPermissions.LIST_OWN_DEVICES) { url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/devices/user/" + carbonUser.username + "/count"; + "/devices?offset=0&limit=1&user=" + carbonUser.username; } else { log.error("Access denied for user: " + carbonUser.username); return -1; } return serviceInvokers.XMLHttp.get( url, function (responsePayload) { - return responsePayload; + return parse(responsePayload["responseText"])["count"]; }, function (responsePayload) { - log.error(responsePayload); + log.error(responsePayload["responseText"]); return -1; } ); 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 2d22a6f9cbc..792d1243ff1 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 @@ -45,7 +45,12 @@ policyModule = function () { policyObjectToView["priorityId"] = policyObjectFromRestEndpoint["priorityId"]; policyObjectToView["name"] = policyObjectFromRestEndpoint["policyName"]; policyObjectToView["platform"] = policyObjectFromRestEndpoint["profile"]["deviceType"]; - policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); + if (policyObjectToView["platform"] == "ios") { + policyObjectToView["deviceTypeIcon"] = "apple"; + } else { + policyObjectToView["deviceTypeIcon"] = policyObjectToView["platform"]; + } + //policyObjectToView["icon"] = utility.getDeviceThumb(policyObjectToView["platform"]); policyObjectToView["ownershipType"] = policyObjectFromRestEndpoint["ownershipType"]; var assignedRoleCount = policyObjectFromRestEndpoint["roles"].length; @@ -74,14 +79,14 @@ policyModule = function () { policyObjectToView["status"] = "Active/Updated"; isUpdated = true; } else if (policyObjectFromRestEndpoint["active"] == true && - policyObjectFromRestEndpoint["updated"] == false) { + policyObjectFromRestEndpoint["updated"] == false) { policyObjectToView["status"] = "Active"; } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == true) { + policyObjectFromRestEndpoint["updated"] == true) { policyObjectToView["status"] = "Inactive/Updated"; isUpdated = true; } else if (policyObjectFromRestEndpoint["active"] == false && - policyObjectFromRestEndpoint["updated"] == false) { + policyObjectFromRestEndpoint["updated"] == false) { policyObjectToView["status"] = "Inactive"; } // push view-objects to list @@ -126,13 +131,39 @@ policyModule = function () { } try { var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/policies?offset=0&limit=100"; + "/policies?offset=0&limit=100"; return serviceInvokers.XMLHttp.get(url, privateMethods.handleGetAllPoliciesResponse); } catch (e) { throw e; } }; + /* + Get policies count from backend services. + */ + publicMethods.getPoliciesCount = function () { + var carbonUser = session.get(constants["USER_SESSION_KEY"]); + if (!carbonUser) { + log.error("User object was not found in the session"); + throw constants["ERRORS"]["USER_NOT_FOUND"]; + } + try { + var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/policies?offset=0&limit=1"; + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + return parse(responsePayload["responseText"])["count"]; + }, + function (responsePayload) { + log.error(responsePayload["responseText"]); + return -1; + } + ); + } catch (e) { + throw e; + } + }; + /* @Updated - used by getAllPolicies */ diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js index 05906058918..43e30b530c3 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js @@ -59,17 +59,17 @@ var userModule = function () { privateMethods.callBackend = function (url, method) { if (constants["HTTP_GET"] == method) { return serviceInvokers.XMLHttp.get(url, - function (backendResponse) { - var response = {}; - response.content = backendResponse.responseText; - if (backendResponse.status == 200) { - response.status = "success"; - } else if (backendResponse.status == 400 || backendResponse.status == 401 || - backendResponse.status == 404 || backendResponse.status == 500) { - response.status = "error"; - } - return response; - } + function (backendResponse) { + var response = {}; + response.content = backendResponse.responseText; + if (backendResponse.status == 200) { + response.status = "success"; + } else if (backendResponse.status == 400 || backendResponse.status == 401 || + backendResponse.status == 404 || backendResponse.status == 500) { + response.status = "error"; + } + return response; + } ); } else { log.error("Runtime error : This method only support HTTP GET requests."); @@ -141,6 +141,35 @@ var userModule = function () { } }; + /* + Get users count from backend services. + */ + publicMethods.getUsersCount = 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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users?offset=0&limit=1"; + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + return parse(responsePayload["responseText"])["count"]; + }, + function (responsePayload) { + log.error(responsePayload["responseText"]); + return -1; + } + ); + } catch (e) { + throw e; + } finally { + utility.endTenantFlow(); + } + }; + /** * Return a User object from the backend by calling the JAX-RS * @param username @@ -151,7 +180,7 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" + - encodeURIComponent(username); + encodeURIComponent(username); var response = privateMethods.callBackend(url, constants["HTTP_GET"]); response["content"] = parse(response.content); response["userDomain"] = carbonUser.domain; @@ -173,7 +202,7 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/users/" + - encodeURIComponent(username) + "/roles"; + encodeURIComponent(username) + "/roles"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); if (response.status == "success") { response.content = parse(response.content).roles; @@ -223,7 +252,7 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/roles?offset=0&limit=100"; + "/roles?offset=0&limit=100"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); if (response.status == "success") { response.content = parse(response.content).roles; @@ -236,6 +265,36 @@ var userModule = function () { } }; + /** + * Get User Roles count from user store (Internal roles not included). + */ + publicMethods.getRolesCount = 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 url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + + "/roles?offset=0&limit=1"; + return serviceInvokers.XMLHttp.get( + url, function (responsePayload) { + return parse(responsePayload["responseText"])["count"]; + }, + function (responsePayload) { + log.error(responsePayload["responseText"]); + return -1; + } + ); + } catch (e) { + throw e; + } finally { + utility.endTenantFlow(); + } + }; + /* @Updated */ @@ -253,7 +312,7 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/roles?user-store=" + userStore + "&limit=100"; + "/roles?user-store=" + userStore + "&limit=100"; var response = privateMethods.callBackend(url, constants["HTTP_GET"]); if (response.status == "success") { response.content = parse(response.content).roles; @@ -270,7 +329,7 @@ var userModule = function () { * Get Platforms. * @deprecated moved this device module under getDeviceTypes. */ - //TODO Move this piece of logic out of user.js to somewhere else appropriate. + //TODO Move this piece of logic out of user.js to somewhere else appropriate. publicMethods.getPlatforms = function () { var carbonUser = session.get(constants["USER_SESSION_KEY"]); var utility = require("/app/modules/utility.js")["utility"]; @@ -306,9 +365,11 @@ var userModule = function () { try { utility.startTenantFlow(carbonUser); var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + - "/roles/" + encodeURIComponent(roleName); + "/roles/" + encodeURIComponent(roleName); var response = privateMethods.callBackend(url, constants["HTTP_GET"]); - response.content = parse(response.content); + if (response.status == "success") { + response.content = parse(response.content); + } return response; } catch (e) { throw e; @@ -394,25 +455,25 @@ var userModule = function () { publicMethods.getUIPermissions = function () { var permissions = {}; - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/devices/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/devices/list")) { permissions["LIST_DEVICES"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/devices/list")) { permissions["LIST_OWN_DEVICES"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/groups/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/groups/list")) { permissions["LIST_ALL_GROUPS"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/list")) { permissions["LIST_GROUPS"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/list")) { permissions["LIST_USERS"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/roles/list")) { permissions["LIST_ROLES"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/list")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/list")) { permissions["LIST_ALL_POLICIES"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/list")) { @@ -424,28 +485,28 @@ var userModule = function () { if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/groups/add")) { permissions["ADD_GROUP"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/add")) { permissions["ADD_USER"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/users/remove")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/users/remove")) { permissions["REMOVE_USER"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/roles/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/roles/add")) { permissions["ADD_ROLE"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/add")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/add")) { permissions["ADD_ADMIN_POLICY"] = true; } if (publicMethods.isAuthorized("/permission/admin/device-mgt/user/policies/add")) { permissions["ADD_POLICY"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/policies/priority")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/policies/priority")) { permissions["CHANGE_POLICY_PRIORITY"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/dashboard/view")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/dashboard/view")) { permissions["VIEW_DASHBOARD"] = true; } - if (publicMethods.isAuthorized("/permission/admin/device-mgt/admin/platform-configs/view")) { + if (publicMethods.isAuthorized("/permission/admin/device-mgt/platform-configs/view")) { permissions["TENANT_CONFIGURATION"] = true; } 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 185f82d8576..6520a819b5d 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 @@ -45,9 +45,9 @@ var invokers = function () { * If the token pair is not set in the session, this will return null. */ privateMethods.getAccessToken = function () { - var tokenPair = parse(session.get(constants["TOKEN_PAIR"])); + var tokenPair = session.get(constants["TOKEN_PAIR"]); if (tokenPair) { - return tokenPair["accessToken"]; + return parse(tokenPair)["accessToken"]; } else { return null; } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.hbs index b2411eac336..4d0f953422a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.hbs @@ -23,77 +23,87 @@ +
  • + + Certificates + +
  • - - - - - Add Certificate + Add
  • {{/zone}} {{#zone "content"}} - -
    -
    - -
    -
    -

    Add Certificate

    -

    Please note that * sign represents required fields of data.

    -
    -
    -
    - + {{#if isAuthorized}} + +
    +
    + +
    +
    +

    Add Certificate

    +

    Please note that * sign represents required fields of data.

    +
    +
    +
    + - -
    -
    - -
    - -
    - + +
    +
    + +
    + +
    + +
    -
    -
    -
    -
    - +
    +
    +
    + +
    -
    - -
    - + + {{else}} +

    + Permission Denied +

    +
    + You not authorized to enter Certificate Management Section. +
    + {{/if}} {{/zone}} {{#zone "bottomJs"}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.js index 4e7585163a2..6099b8a845d 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificate.create/create.js @@ -19,27 +19,28 @@ /** * Returns the dynamic state to be populated by add-user page. * - * @param context Object that gets updated with the dynamic state of this page to be presented - * @returns {*} A context object that returns the dynamic state of this page to be presented + * @param viewModel Object that gets updated with the dynamic state of this page to be presented + * @returns {*} A viewModel object that returns the dynamic state of this page to be presented */ function onRequest(context) { // var log = new Log("units/user-create/create.js"); var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; - + var viewModel = {}; + viewModel.isAuthorized = userModule.isAuthorized("/permission/admin/device-mgt/certificates/manage"); var response = userModule.getRolesByUserStore(); if (response["status"] == "success") { - context["roles"] = response["content"]; + viewModel["roles"] = response["content"]; } - context["charLimit"] = mdmProps["usernameLength"]; - context["usernameJSRegEx"] = mdmProps["userValidationConfig"]["usernameJSRegEx"]; - context["usernameHelpText"] = mdmProps["userValidationConfig"]["usernameHelpMsg"]; - context["usernameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["usernameRegExViolationErrorMsg"]; - context["firstnameJSRegEx"] = mdmProps["userValidationConfig"]["firstnameJSRegEx"]; - context["firstnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["firstnameRegExViolationErrorMsg"]; - context["lastnameJSRegEx"] = mdmProps["userValidationConfig"]["lastnameJSRegEx"]; - context["lastnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["lastnameRegExViolationErrorMsg"]; + viewModel["charLimit"] = mdmProps["usernameLength"]; + viewModel["usernameJSRegEx"] = mdmProps["userValidationConfig"]["usernameJSRegEx"]; + viewModel["usernameHelpText"] = mdmProps["userValidationConfig"]["usernameHelpMsg"]; + viewModel["usernameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["usernameRegExViolationErrorMsg"]; + viewModel["firstnameJSRegEx"] = mdmProps["userValidationConfig"]["firstnameJSRegEx"]; + viewModel["firstnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["firstnameRegExViolationErrorMsg"]; + viewModel["lastnameJSRegEx"] = mdmProps["userValidationConfig"]["lastnameJSRegEx"]; + viewModel["lastnameRegExViolationErrorMsg"] = mdmProps["userValidationConfig"]["lastnameRegExViolationErrorMsg"]; - return context; + return viewModel; } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.hbs index 86f161ae359..54546481ba9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.hbs @@ -15,6 +15,7 @@ specific language governing permissions and limitations under the License. }} + {{unit "cdmf.unit.ui.title" pageTitle="Add Certificate"}} {{#zone "breadcrumbs"}} @@ -24,14 +25,26 @@
  • - + + + Certificates + +
  • +{{/zone}} + +{{#zone "navbarActions"}} + {{#if removePermitted}} +
  • + + - Add Certificate - -
  • + Add Certificate + + + {{/if}} {{/zone}} {{#zone "content"}} @@ -87,10 +100,7 @@ - - -
    - +

    @@ -121,57 +131,58 @@
    -
    -
    -
    -

    Done. Certificate was successfully removed.

    - -
    + + +
    -
    -
    -
    -

    An unexpected error occurred. Please try again later.

    + + +
    +
    -
    -
    -
    -

    + + Unauthorized action! +

    + +
    + +
    {{/zone}} {{#zone "bottomJs"}} + - {{js "/js/certificate-listing.js"}} {{/zone}} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.js index 8aeb02353e3..a4be059e947 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/certificates.js @@ -1,15 +1,16 @@ function onRequest(context) { var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var mdmProps = require("/app/modules/conf-reader/main.js")["conf"]; + var viewModel = {}; - context["permissions"] = userModule.getUIPermissions(); - if (userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/certificate/Get")) { - context["removePermitted"] = true; + if (userModule.isAuthorized("/permission/admin/device-mgt/certificates/manage")) { + viewModel["removePermitted"] = true; } - if (userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/certificate/Get")) { - context["viewPermitted"] = true; + if (userModule.isAuthorized("/permission/admin/device-mgt/certificates/view")) { + viewModel["viewPermitted"] = true; } - context["adminUser"] = mdmProps.adminUser; - return context; + + viewModel.adminUser = mdmProps.adminUser; + return viewModel; } \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/public/js/certificate-listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/public/js/certificate-listing.js index d911d7fb451..01acf088d11 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/public/js/certificate-listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.certificates/public/js/certificate-listing.js @@ -12,9 +12,9 @@ $(function () { $(sortableElem).disableSelection(); }); -var modalPopup = ".wr-modalpopup"; -var modalPopupContainer = modalPopup + " .modalpopup-container"; -var modalPopupContent = modalPopup + " .modalpopup-content"; +var modalPopup = ".modal"; +var modalPopupContainer = modalPopup + " .modal-content"; +var modalPopupContent = modalPopup + " .modal-content"; var body = "body"; var isInit = true; @@ -34,8 +34,7 @@ function setPopupMaxHeight() { * show popup function. */ function showPopup() { - $(modalPopup).show(); - setPopupMaxHeight(); + $(modalPopup).modal('show'); } /* @@ -43,7 +42,9 @@ function showPopup() { */ function hidePopup() { $(modalPopupContent).html(''); - $(modalPopup).hide(); + $(modalPopup).modal('hide'); + $('body').removeClass('modal-open').css('padding-right','0px'); + $('.modal-backdrop').remove(); } /** 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 06ac10ba3ab..c5682c0c5b8 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 @@ -36,10 +36,12 @@ function onRequest() { page.permissions = permissions; page.enrollmentURL = devicemgtProps.enrollmentURL; page.device_count = deviceModule.getDevicesCount(); - page.group_count = groupModule.getGroupCount(); - page.user_count = userModule.getUsers()["content"].length; - page.policy_count = policyModule.getAllPolicies()["content"].length; - page.role_count = userModule.getRoles()["content"].length; + //TODO: Enable Group Management Service API on CDMF + //page.group_count = groupModule.getGroupCount(); + page.group_count = -1; + page.user_count = userModule.getUsersCount(); + page.policy_count = policyModule.getPoliciesCount(); + page.role_count = userModule.getRolesCount(); return page; -} +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index 421ab3b7793..4b1975f9bfd 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -229,61 +229,83 @@
    -
    -
    -
    -

    Do you really want to remove this device from your Devices List?

    + + +
    +
    -
    -
    -
    -

    Device was successfully removed.

    -
    + + +
    -
    -
    -
    -

    Please enter new name for the device?

    -
    - -
    - -
    - -
    + + +
    +
    + + +