diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java
similarity index 80%
rename from components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java
rename to components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java
index 65ade5cc3a..9e0068635b 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Permission.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/src/main/java/org/wso2/carbon/apimgt/annotations/api/Scope.java
@@ -28,18 +28,24 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
-public @interface Permission {
+public @interface Scope {
+
+ /**
+ * Represents the scope key which should be unique.
+ * @return Returns scope key.
+ */
+ String key();
/**
* Represents the scope name.
* @return Returns scope name.
*/
- String scope();
+ String name();
/**
- * Represents the associated permissions.
- * @return Returns list of permissions.
+ * Represents the scope description.
+ * @return Returns scope description.
*/
- String[] permissions();
+ String description();
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
index 5e7794b952..8d3f9af30b 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
@@ -161,6 +161,10 @@
org.wso2.carbon.user.apiprovided
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.apimgt.annotations
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java
index 8a81a8a5ec..8e2843cdc3 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/java/org/wso2/carbon/apimgt/application/extension/api/ApiApplicationRegistrationService.java
@@ -18,20 +18,19 @@
package org.wso2.carbon.apimgt.application.extension.api;
+import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.POST;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
+import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This is the application registration service that exposed for apimApplicationRegistration
*/
+@API(name = "API Registration Service", version = "1.0.0",
+ context = "api-application-registration",
+ tags = {"devicemgt_admin"})
public interface ApiApplicationRegistrationService {
/**
@@ -40,6 +39,7 @@ public interface ApiApplicationRegistrationService {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
+ @Path("register/tenants")
Response register(@PathParam("tenantDomain") String tenantDomain,
@QueryParam("applicationName") String applicationName);
@@ -51,6 +51,7 @@ public interface ApiApplicationRegistrationService {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
+ @Path("register")
Response register(RegistrationProfile registrationProfile);
/**
@@ -59,5 +60,6 @@ public interface ApiApplicationRegistrationService {
* @return the response status of request.
*/
@DELETE
+ @Path("unregister")
Response unregister(@QueryParam("applicationName") String applicationName);
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml
index 549bf4c1bd..e771ee6c09 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/src/main/webapp/WEB-INF/web.xml
@@ -47,7 +47,11 @@
managed-api-enabled
- false
+ true
+
+
+ managed-api-owner
+ admin
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
index 21338e0129..3a565f1762 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
@@ -107,6 +107,10 @@
javax.ws.rsjavax.ws.rs-api
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.device.mgt.common
+
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java
index 3a2385d67c..289037e58e 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/APIPublisherUtil.java
@@ -18,7 +18,6 @@
package org.wso2.carbon.apimgt.webapp.publisher;
-import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
@@ -30,6 +29,10 @@ import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.util.Utils;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
+import org.wso2.carbon.user.api.UserRealm;
+import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.ServletContext;
import java.util.*;
@@ -121,16 +124,18 @@ public class APIPublisherUtil {
if (scope != null) {
if (apiScopes.get(scope.getKey()) == null) {
apiScopes.put(scope.getKey(), scope);
- } else {
- existingScope = apiScopes.get(scope.getKey());
- existingPermissions = existingScope.getRoles();
- existingPermissions = getDistinctPermissions(existingPermissions + "," + scope.getRoles());
- existingScope.setRoles(existingPermissions);
- apiScopes.put(scope.getKey(), existingScope);
}
}
}
Set scopes = new HashSet<>(apiScopes.values());
+ // adding existing persisted roles to the scopes
+ try {
+ setExistingRoles(scopes);
+ } catch (ScopeManagementException | UserStoreException e) {
+ throw new APIManagementException("Error occurred while retrieving roles for the existing scopes");
+ }
+
+ // set current scopes to API
api.setScopes(scopes);
// this has to be done because of the use of pass by reference
@@ -307,9 +312,34 @@ public class APIPublisherUtil {
return apiConfig;
}
- private static String getDistinctPermissions(String permissions) {
- String[] unique = new HashSet(Arrays.asList(permissions.split(","))).toArray(new String[0]);
- return StringUtils.join(unique, ",");
+ /**
+ * This method is used to set the existing roles of the given scope.
+ *
+ * @param scopes List of scopes.
+ * @throws ScopeManagementException
+ */
+ private static void setExistingRoles(Set scopes) throws ScopeManagementException, UserStoreException {
+ String scopeKey;
+ String roles;
+ ScopeManagementService scopeManagementService = WebappPublisherUtil.getScopeManagementService();
+ UserRealm userRealm = WebappPublisherUtil.getUserRealm();
+
+ if (scopeManagementService == null) {
+ throw new ScopeManagementException("Error occurred while initializing scope management service");
+ } else if (userRealm == null) {
+ throw new UserStoreException("Error occurred while initializing realm service");
+ } else {
+ String adminRole = userRealm.getRealmConfiguration().getAdminRoleName();
+ for (Scope scope : scopes) {
+ scopeKey = scope.getKey();
+ roles = scopeManagementService.getRolesOfScope(scopeKey);
+ if (roles == null) {
+ roles = adminRole;
+ }
+ scope.setRoles(roles);
+
+ }
+ }
}
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
index 17e2edb9a8..ca2f0cba13 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/WebappPublisherUtil.java
@@ -18,7 +18,16 @@
package org.wso2.carbon.apimgt.webapp.publisher;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
+import org.wso2.carbon.context.CarbonContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
+import org.wso2.carbon.user.api.UserRealm;
+import org.wso2.carbon.user.api.UserStoreException;
+import org.wso2.carbon.user.api.UserStoreManager;
+import org.wso2.carbon.user.core.service.RealmService;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
@@ -31,6 +40,10 @@ import java.io.File;
*/
public class WebappPublisherUtil {
+ private static Log log = LogFactory.getLog(WebappPublisherUtil.class);
+ private static final int CARBON_SUPER = -1234;
+
+
public static Document convertToDocument(File file) throws WebappPublisherConfigurationFailedException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
@@ -44,4 +57,32 @@ public class WebappPublisherUtil {
}
}
+ public static ScopeManagementService getScopeManagementService() {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ ScopeManagementService scopeManagementService =
+ (ScopeManagementService) ctx.getOSGiService(ScopeManagementService.class, null);
+ if (scopeManagementService == null) {
+ String msg = "Scope Management Service has not been initialized.";
+ log.error(msg);
+ throw new IllegalStateException(msg);
+ }
+ return scopeManagementService;
+ }
+
+ /**
+ * Getting the current tenant's user realm
+ */
+ public static UserRealm getUserRealm() throws UserStoreException {
+ RealmService realmService;
+ UserRealm realm;
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
+
+ if (realmService == null) {
+ throw new IllegalStateException("Realm service not initialized");
+ }
+ realm = realmService.getTenantUserRealm(CARBON_SUPER);
+ return realm;
+ }
+
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java
deleted file mode 100644
index 651c285723..0000000000
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionManagementException.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * you may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-package org.wso2.carbon.apimgt.webapp.publisher.config;
-
-/**
- * Custom exception class of Permission related operations.
- */
-public class PermissionManagementException extends Exception {
-
- private static final long serialVersionUID = -3151279311929070298L;
-
- private String errorMessage;
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
- public PermissionManagementException(String msg, Exception nestedEx) {
- super(msg, nestedEx);
- setErrorMessage(msg);
- }
-
- public PermissionManagementException(String message, Throwable cause) {
- super(message, cause);
- setErrorMessage(message);
- }
-
- public PermissionManagementException(String msg) {
- super(msg);
- setErrorMessage(msg);
- }
-
- public PermissionManagementException() {
- super();
- }
-
- public PermissionManagementException(Throwable cause) {
- super(cause);
- }
-
-}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java
index 0e8550c941..bc4bf85724 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/AnnotationProcessor.java
@@ -19,20 +19,13 @@
package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util;
import org.apache.catalina.core.StandardContext;
-import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.scannotation.AnnotationDB;
-import org.scannotation.WarUrlFinder;
import org.wso2.carbon.apimgt.annotations.api.API;
-import org.wso2.carbon.apimgt.annotations.api.Permission;
-import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
-import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionConfiguration;
-import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException;
import javax.servlet.ServletContext;
import javax.ws.rs.*;
@@ -61,11 +54,9 @@ public class AnnotationProcessor {
private static final String WILD_CARD = "/*";
private static final String AUTH_TYPE = "Any";
- private static final String PROTOCOL_HTTP = "http";
- private static final String SERVER_HOST = "carbon.local.ip";
- private static final String HTTP_PORT = "httpPort";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
+
Class apiClazz;
private StandardContext context;
private Method[] pathClazzMethods;
@@ -75,7 +66,6 @@ public class AnnotationProcessor {
public AnnotationProcessor(final StandardContext context) {
- this.context = context;
servletContext = context.getServletContext();
classLoader = servletContext.getClassLoader();
}
@@ -141,7 +131,7 @@ public class AnnotationProcessor {
pathClazzMethods = pathClazz.getMethods();
Annotation rootContectAnno = clazz.getAnnotation(pathClazz);
- String subContext = "";
+ String subContext;
if (rootContectAnno != null) {
subContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING);
if (subContext != null && !subContext.isEmpty()) {
@@ -150,8 +140,6 @@ public class AnnotationProcessor {
} else {
rootContext = rootContext + "/" + subContext;
}
- } else {
- subContext = "";
}
if (log.isDebugEnabled()) {
log.debug("API Root Context = " + rootContext);
@@ -166,7 +154,7 @@ public class AnnotationProcessor {
}
}
} catch (ClassNotFoundException e) {
- log.error("Error when passing the api annotation for device type apis.");
+ log.error("Error when passing the api annotation for device type apis.", e);
}
return apiResourceConfig;
}
@@ -251,15 +239,9 @@ public class AnnotationProcessor {
Annotation producesAnno = method.getAnnotation(producesClass);
resource.setProduces(invokeMethod(producesClassMethods[0], producesAnno, STRING_ARR));
}
- if (annotations[i].annotationType().getName().equals(Permission.class.getName())) {
- PermissionConfiguration permissionConf = this.getPermission(method);
- if (permissionConf != null) {
- Scope scope = new Scope();
- scope.setKey(permissionConf.getScopeName());
- scope.setDescription(permissionConf.getScopeName());
- scope.setName(permissionConf.getScopeName());
- String roles = StringUtils.join(permissionConf.getPermissions(), ",");
- scope.setRoles(roles);
+ if (annotations[i].annotationType().getName().equals(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName())) {
+ org.wso2.carbon.apimgt.api.model.Scope scope = this.getScope(method);
+ if (scope != null) {
resource.setScope(scope);
}
}
@@ -357,35 +339,32 @@ public class AnnotationProcessor {
return ((String[]) methodHandler.invoke(annotation, method, null));
}
- private PermissionConfiguration getPermission(Method currentMethod) throws Throwable {
- Class permissionClass = (Class) classLoader.loadClass(Permission.class.getName());
- Annotation permissionAnnotation = currentMethod.getAnnotation(permissionClass);
- if (permissionClass != null) {
- Method[] permissionClassMethods = permissionClass.getMethods();
- PermissionConfiguration permissionConf = new PermissionConfiguration();
+ private org.wso2.carbon.apimgt.api.model.Scope getScope(Method currentMethod) throws Throwable {
+ Class scopeClass =
+ (Class) classLoader.
+ loadClass(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName());
+ Annotation permissionAnnotation = currentMethod.getAnnotation(scopeClass);
+ if (scopeClass != null) {
+ Method[] permissionClassMethods = scopeClass.getMethods();
+ org.wso2.carbon.apimgt.api.model.Scope scope = new org.wso2.carbon.apimgt.api.model.Scope();
for (Method method : permissionClassMethods) {
switch (method.getName()) {
- case "scope":
- permissionConf.setScopeName(invokeMethod(method, permissionAnnotation, STRING));
+ case "key":
+ scope.setKey(invokeMethod(method, permissionAnnotation, STRING));
+ break;
+ case "name":
+ scope.setName(invokeMethod(method, permissionAnnotation, STRING));
break;
- case "permissions":
- String permissions[] = invokeMethod(method, permissionAnnotation);
- this.addPermission(permissions);
- permissionConf.setPermissions(permissions);
+ case "description":
+ scope.setDescription(invokeMethod(method, permissionAnnotation, STRING));
break;
}
}
- return permissionConf;
+ return scope;
}
return null;
}
- private void addPermission(String[] permissions) throws PermissionManagementException {
- for (String permission : permissions) {
- PermissionUtils.addPermission(permission);
- }
- }
-
/**
* Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory
* if your servlet container does not extract the /WEB-INF/classes into a real file-based directory
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java
index a62a58f733..e20b4ba467 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/ExtendedIteratorFactory.java
@@ -15,6 +15,7 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util;
+
import org.scannotation.archiveiterator.DirectoryIteratorFactory;
import org.scannotation.archiveiterator.Filter;
import org.scannotation.archiveiterator.JarIterator;
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java
deleted file mode 100644
index 32c5bad855..0000000000
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/lifecycle/util/PermissionUtils.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
- *
- * WSO2 Inc. licenses this file to you under the Apache License,
- * Version 2.0 (the "License"); you may not use this file except
- * in compliance with the License.
- * you may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util;
-
-import org.wso2.carbon.apimgt.webapp.publisher.config.PermissionManagementException;
-import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
-import org.wso2.carbon.context.PrivilegedCarbonContext;
-import org.wso2.carbon.registry.api.RegistryException;
-import org.wso2.carbon.registry.api.Resource;
-import org.wso2.carbon.registry.core.Registry;
-
-import java.util.StringTokenizer;
-
-/**
- * Utility class which holds necessary utility methods required for persisting permissions in
- * registry.
- */
-public class PermissionUtils {
-
- public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin";
- public static final String PERMISSION_PROPERTY_NAME = "name";
-
- public static Registry getGovernanceRegistry() throws PermissionManagementException {
- try {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
- return APIPublisherDataHolder.getInstance().getRegistryService()
- .getGovernanceSystemRegistry(
- tenantId);
- } catch (RegistryException e) {
- throw new PermissionManagementException(
- "Error in retrieving governance registry instance: " +
- e.getMessage(), e);
- }
- }
-
- public static void addPermission(String permission) throws PermissionManagementException {
- String resourcePermission = getAbsolutePermissionPath(permission);
- try {
- StringTokenizer tokenizer = new StringTokenizer(resourcePermission, "/");
- String lastToken = "", currentToken, tempPath;
- while (tokenizer.hasMoreTokens()) {
- currentToken = tokenizer.nextToken();
- tempPath = lastToken + "/" + currentToken;
- if (!checkResourceExists(tempPath)) {
- createRegistryCollection(tempPath, currentToken);
- }
- lastToken = tempPath;
- }
- } catch (RegistryException e) {
- throw new PermissionManagementException("Error occurred while persisting permission : " +
- resourcePermission, e);
- }
- }
-
- public static void createRegistryCollection(String path, String resourceName)
- throws PermissionManagementException,
- RegistryException {
- Resource resource = PermissionUtils.getGovernanceRegistry().newCollection();
- resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName);
- PermissionUtils.getGovernanceRegistry().beginTransaction();
- PermissionUtils.getGovernanceRegistry().put(path, resource);
- PermissionUtils.getGovernanceRegistry().commitTransaction();
- }
-
- public static boolean checkResourceExists(String path)
- throws PermissionManagementException,
- org.wso2.carbon.registry.core.exceptions.RegistryException {
- return PermissionUtils.getGovernanceRegistry().resourceExists(path);
- }
-
- private static String getAbsolutePermissionPath(String permissionPath) {
- return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath;
- }
-
-}
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
index 494e30b349..b1b0b768d7 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
@@ -76,7 +76,7 @@
-
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java
index 96351caedd..fbb9458962 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/src/main/java/org/wso2/carbon/certificate/mgt/jaxrs/api/CertificateMgtService.java
@@ -4,7 +4,7 @@ import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
-import org.wso2.carbon.apimgt.annotations.api.Permission;
+import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.certificate.mgt.jaxrs.beans.ErrorResponse;
import javax.ws.rs.*;
@@ -46,7 +46,7 @@ public interface CertificateMgtService {
message = "Internal Server Error. \n Error occurred while retrieving signed certificate.",
response = ErrorResponse.class)
})
- @Permission(scope = "sign-csr", permissions = {"/permission/admin/device-mgt/scep/sign-csr"})
+ @Scope(key = "certificate:sign-csr", name = "Sign CSR", description = "")
Response getSignedCertFromCSR(
@ApiParam(
name = "If-Modified-Since",
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
index 07d2611d20..e0bbaee6bc 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
@@ -72,7 +72,7 @@
-
+
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java
index 6988f31712..da1d54bc4f 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/CertificateManagementAdminService.java
@@ -1,7 +1,8 @@
package org.wso2.carbon.certificate.mgt.cert.jaxrs.api;
import io.swagger.annotations.*;
-import org.wso2.carbon.apimgt.annotations.api.Permission;
+import org.wso2.carbon.apimgt.annotations.api.API;
+import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.CertificateList;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.EnrollmentCertificate;
import org.wso2.carbon.certificate.mgt.cert.jaxrs.api.beans.ErrorResponse;
@@ -11,6 +12,10 @@ import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+@API(name = "Certificate Management", version = "1.0.0",
+ context = "api/certificate-mgt/v1.0/admin/certificates",
+ tags = {"devicemgt_admin"})
+
@Api(value = "Certificate Management", description = "This API carries all certificate management related operations " +
"such as get all the available devices, etc.")
@Path("/admin/certificates")
@@ -72,7 +77,7 @@ public interface CertificateManagementAdminService {
message = "Internal Server Error. \n Server error occurred while adding certificates.",
response = ErrorResponse.class)
})
- @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/save"})
+ @Scope(key = "certificate:manage", name = "Add certificates", description = "")
Response addCertificate(
@ApiParam(
name = "enrollmentCertificates",
@@ -130,7 +135,7 @@ public interface CertificateManagementAdminService {
"Server error occurred while retrieving information requested certificate.",
response = ErrorResponse.class)
})
- @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
+ @Scope(key = "certificate:view", name = "View certificates", description = "")
Response getCertificate(
@ApiParam(name = "serialNumber",
value = "Provide the serial number of the certificate that you wish to get the details of",
@@ -202,7 +207,7 @@ public interface CertificateManagementAdminService {
"Server error occurred while retrieving all certificates enrolled in the system.",
response = ErrorResponse.class)
})
- @Permission(scope = "certificate-view", permissions = {"/permission/admin/device-mgt/certificate/view"})
+ @Scope(key = "certificate:view", name = "View certificates", description = "")
Response getAllCertificates(
@ApiParam(
name = "offset",
@@ -245,7 +250,7 @@ public interface CertificateManagementAdminService {
message = "Internal Server Error. \n " +
"Server error occurred while removing the certificate.",
response = ErrorResponse.class)})
- @Permission(scope = "certificate-modify", permissions = {"/permission/admin/device-mgt/certificate/remove"})
+ @Scope(key = "certificate:manage", name = "Add certificates", description = "")
Response removeCertificate(
@ApiParam(
name = "serialNumber",
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
index bef54b2194..f3c454bda5 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/java/org/wso2/carbon/certificate/mgt/cert/jaxrs/api/impl/CertificateManagementAdminServiceImpl.java
@@ -119,11 +119,14 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
try {
boolean status = certificateService.removeCertificate(serialNumber);
if (!status) {
- Response.status(Response.Status.NOT_FOUND).entity("No certificate is found with the given " +
- "serial number '" + serialNumber + "'");
+ return Response.status(Response.Status.NOT_FOUND).entity(
+ "No certificate is found with the given " +
+ "serial number '" + serialNumber + "'").build();
+ } else {
+ return Response.status(Response.Status.OK).entity(
+ "Certificate that carries the serial number '" +
+ serialNumber + "' has been removed").build();
}
- return Response.status(Response.Status.OK).entity("Certificate that carries the serial number '" +
- serialNumber + "' has been removed").build();
} catch (CertificateManagementException e) {
String msg = "Error occurred while converting PEM file to X509Certificate";
log.error(msg, e);
@@ -132,4 +135,4 @@ public class CertificateManagementAdminServiceImpl implements CertificateManagem
}
}
-}
+}
\ No newline at end of file
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml
index a22b8681cd..68a07fcb86 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -44,7 +44,7 @@
-
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
index 0876d99c1f..98bdddfd20 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
@@ -110,14 +110,17 @@
org.apache.cxfcxf-rt-frontend-jaxws
+ providedorg.apache.cxfcxf-rt-frontend-jaxrs
+ providedorg.apache.cxfcxf-rt-transports-http
+ providedjunit
@@ -237,6 +240,7 @@
org.wso2.carbon.devicemgtorg.wso2.carbon.apimgt.annotations
+ providedorg.wso2.carbon.devicemgt
@@ -248,6 +252,14 @@
jackson-annotationsprovided
+
+ org.hibernate
+ hibernate-validator
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java
index 8804fa3add..c695932eae 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/ErrorResponse.java
@@ -34,7 +34,7 @@ public class ErrorResponse {
private String moreInfo = null;
private List errorItems = new ArrayList<>();
- private ErrorResponse() {
+ public ErrorResponse() {
}
@JsonProperty(value = "code")
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java
index 1795e29982..c0c768eeb2 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/PolicyWrapper.java
@@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import javax.validation.constraints.Size;
import java.util.List;
@ApiModel(value = "PolicyWrapper", description = "This class carries all information related to Policy "
@@ -29,9 +30,11 @@ import java.util.List;
public class PolicyWrapper {
@ApiModelProperty(name = "policyName", value = "The name of the policy", required = true)
+ @Size(max = 45)
private String policyName;
@ApiModelProperty(name = "description", value = "Gives a description on the policy", required = true)
+ @Size(max = 1000)
private String description;
@ApiModelProperty(name = "compliance", value = "Provides the non-compliance rules. WSO2 EMM provides the"
@@ -41,6 +44,7 @@ public class PolicyWrapper {
+ "Monitor - If the device does not adhere to the given policies the server is notified of the "
+ "violation unknown to the user and the administrator can take the necessary actions with regard"
+ " to the reported", required = true)
+ @Size(max = 100)
private String compliance;
@ApiModelProperty(name = "ownershipType", value = "The policy ownership type. It can be any of the "
@@ -49,6 +53,7 @@ public class PolicyWrapper {
+ "BYOD (Bring Your Own Device) - The policy will only be applied on the BYOD device type\n"
+ "COPE (Corporate-Owned, Personally-Enabled) - The policy will only be applied on the COPE "
+ "device type", required = true)
+ @Size(max = 45)
private String ownershipType;
@ApiModelProperty(name = "active", value = "If the value is true it indicates that the policy is active. "
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java
index 27aebb2abf..77bd4f9b63 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Profile.java
@@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
-import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java
index e62b5a4a3c..701d341133 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/RoleInfo.java
@@ -20,7 +20,8 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
-import org.wso2.carbon.user.mgt.common.UIPermissionNode;
+
+import java.util.List;
@ApiModel(value = "RoleInfo", description = "Role details including permission and the users in the roles are " +
"wrapped here.")
@@ -28,19 +29,12 @@ public class RoleInfo {
@ApiModelProperty(name = "roleName", value = "The name of the role.", required = true)
private String roleName;
- @ApiModelProperty(name = "permissions", value = "Lists out all the permissions associated with roles.",
- required = true, dataType = "List[java.lang.String]")
- private String[] permissions;
+ @ApiModelProperty(name = "scopes", value = "Lists out all the scopes associated with roles.",
+ required = true, dataType = "List[org.wso2.carbon.device.mgt.jaxrs.beans.Scope]")
+ private List scopes;
@ApiModelProperty(name = "users", value = "The list of users assigned to the selected role.",
required = true, dataType = "List[java.lang.String]")
private String[] users;
- @ApiModelProperty(name = "permissionList", value = "This contain the following, " +
- "\n resourcePath\tThe path related to the API.\n " +
- "displayName\tThe name of the permission that is shown " +
- "in the UI.\n" +
- "nodeList\tLists out the nested permissions.",
- required = true)
- private UIPermissionNode permissionList;
public String getRoleName() {
return roleName;
@@ -50,12 +44,12 @@ public class RoleInfo {
this.roleName = roleName;
}
- public String[] getPermissions() {
- return permissions;
+ public List getScopes() {
+ return scopes;
}
- public void setPermissions(String[] permissions) {
- this.permissions = permissions;
+ public void setScopes(List scopes) {
+ this.scopes = scopes;
}
public String[] getUsers() {
@@ -66,11 +60,4 @@ public class RoleInfo {
this.users = users;
}
- public UIPermissionNode getPermissionList() {
- return permissionList;
- }
-
- public void setPermissionList(UIPermissionNode permissionList) {
- this.permissionList = permissionList;
- }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java
new file mode 100644
index 0000000000..0badaa417c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/Scope.java
@@ -0,0 +1,71 @@
+/*
+* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.wso2.carbon.device.mgt.jaxrs.beans;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+@ApiModel(value = "Scope", description = "Template of the authorization scope")
+public class Scope {
+
+ @ApiModelProperty(name = "scope key", value = "An unique string as a key.", required = true)
+ private String key;
+
+ @ApiModelProperty(name = "scope name", value = "Scope name.", required = true)
+ private String name;
+
+ @ApiModelProperty(name = "roles", value = "List of roles to be associated with the scope", required = true)
+ private String roles;
+
+ @ApiModelProperty(name = "scope description", value = "A description of the scope", required = true)
+ private String description;
+
+ public Scope() {
+ }
+
+ public String getKey() {
+ return this.key;
+ }
+
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getRoles() {
+ return this.roles;
+ }
+
+ public void setRoles(String roles) {
+ this.roles = roles;
+ }
+
+ public String getDescription() {
+ return this.description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java
similarity index 55%
rename from components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java
index 7d16d198b9..d97b78b6dd 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/main/java/org/wso2/carbon/apimgt/webapp/publisher/config/PermissionConfiguration.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/BadRequestException.java
@@ -16,30 +16,19 @@
* under the License.
*/
-package org.wso2.carbon.apimgt.webapp.publisher.config;
+package org.wso2.carbon.device.mgt.jaxrs.exception;
-/**
- * This class represents the information related to permissions.
- */
-public class PermissionConfiguration {
-
- private String scopeName;
- private String[] permissions;
-
- public String getScopeName() {
- return scopeName;
- }
+import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
- public void setScopeName(String scope) {
- this.scopeName = scope;
- }
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
- public String[] getPermissions() {
- return permissions;
- }
+/**
+ * Custom exception class for wrapping BadRequest related exceptions.
+ */
+public class BadRequestException extends WebApplicationException {
- public void setPermissions(String[] permissions) {
- this.permissions = permissions;
+ public BadRequestException(ErrorResponse error) {
+ super(Response.status(Response.Status.BAD_REQUEST).entity(error).build());
}
-
-}
+}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java
new file mode 100644
index 0000000000..9664057f61
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ConstraintViolationException.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
+
+import javax.validation.ConstraintViolation;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import java.util.Set;
+
+public class ConstraintViolationException extends WebApplicationException {
+ private String message;
+
+ public ConstraintViolationException(Set> violations) {
+ super(Response.status(Response.Status.BAD_REQUEST)
+ .entity(DeviceMgtUtil.getConstraintViolationErrorDTO(violations))
+ .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
+ .build());
+
+ //Set the error message
+ StringBuilder stringBuilder = new StringBuilder();
+ for (ConstraintViolation violation : violations) {
+ stringBuilder.append(violation.getRootBeanClass().getSimpleName());
+ stringBuilder.append(".");
+ stringBuilder.append(violation.getPropertyPath());
+ stringBuilder.append(": ");
+ stringBuilder.append(violation.getMessage());
+ stringBuilder.append(", ");
+ }
+ message = stringBuilder.toString();
+ }
+
+ @Override
+ public String getMessage() {
+ return message;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java
new file mode 100644
index 0000000000..ff4e0be32a
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ErrorDTO.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ErrorDTO {
+
+ private Long code = null;
+ private String message = null;
+ private String description = null;
+
+ public void setMoreInfo(String moreInfo) {
+ this.moreInfo = moreInfo;
+ }
+
+ public void setCode(Long code) {
+ this.code = code;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public void setError(List error) {
+ this.error = error;
+ }
+
+ private String moreInfo = null;
+
+ public String getMessage() {
+ return message;
+ }
+
+ public Long getCode() {
+ return code;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getMoreInfo() {
+ return moreInfo;
+ }
+
+ public List getError() {
+ return error;
+ }
+
+ public String toString() {
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append("class ErrorDTO {\n");
+ stringBuilder.append(" code: ").append(code).append("\n");
+ stringBuilder.append(" message: ").append(message).append("\n");
+ stringBuilder.append(" description: ").append(description).append("\n");
+ stringBuilder.append(" moreInfo: ").append(moreInfo).append("\n");
+ stringBuilder.append(" error: ").append(error).append("\n");
+ stringBuilder.append("}\n");
+ return stringBuilder.toString();
+ }
+
+ private List error = new ArrayList<>();
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java
new file mode 100644
index 0000000000..912f624632
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ForbiddenException.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+
+/**
+ * Exception class that is corresponding to 401 Forbidden response
+ */
+
+public class ForbiddenException extends WebApplicationException {
+
+ private String message;
+
+ public ForbiddenException() {
+ super(Response.status(Response.Status.FORBIDDEN)
+ .build());
+ }
+
+ public ForbiddenException(ErrorDTO errorDTO) {
+ super(Response.status(Response.Status.FORBIDDEN)
+ .entity(errorDTO)
+ .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
+ .build());
+ message = errorDTO.getDescription();
+ }
+
+ @Override
+ public String getMessage() {
+ return message;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java
new file mode 100644
index 0000000000..be3d037a8d
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/GlobalThrowableMapper.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+import com.google.gson.JsonParseException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
+
+import javax.naming.AuthenticationException;
+import javax.ws.rs.ClientErrorException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+
+/**
+ * Handle the cxf level exceptions.
+ */
+public class GlobalThrowableMapper implements ExceptionMapper {
+ private static final Log log = LogFactory.getLog(GlobalThrowableMapper.class);
+
+ private ErrorDTO e500 = new ErrorDTO();
+
+ GlobalThrowableMapper() {
+ e500.setCode((long) 500);
+ e500.setMessage("Internal server error.");
+ e500.setMoreInfo("");
+ e500.setDescription("The server encountered an internal error. Please contact administrator.");
+
+ }
+
+ @Override
+ public Response toResponse(Throwable e) {
+
+ if (e instanceof JsonParseException) {
+ String errorMessage = "Malformed request body.";
+ if (log.isDebugEnabled()) {
+ log.error(errorMessage, e);
+ }
+ return DeviceMgtUtil.buildBadRequestException(errorMessage).getResponse();
+ }
+ if (e instanceof NotFoundException) {
+ return ((NotFoundException) e).getResponse();
+ }
+ if (e instanceof UnexpectedServerErrorException) {
+ if (log.isDebugEnabled()) {
+ log.error("Unexpected server error.", e);
+ }
+ return ((UnexpectedServerErrorException) e).getResponse();
+ }
+ if (e instanceof ConstraintViolationException) {
+ if (log.isDebugEnabled()) {
+ log.error("Constraint violation.", e);
+ }
+ return ((ConstraintViolationException) e).getResponse();
+ }
+ if (e instanceof IllegalArgumentException) {
+ ErrorDTO errorDetail = new ErrorDTO();
+ errorDetail.setCode((long) 400);
+ errorDetail.setMoreInfo("");
+ errorDetail.setMessage("");
+ errorDetail.setDescription(e.getMessage());
+ return Response
+ .status(Response.Status.BAD_REQUEST)
+ .entity(errorDetail)
+ .build();
+ }
+ if (e instanceof ClientErrorException) {
+ if (log.isDebugEnabled()) {
+ log.error("Client error.", e);
+ }
+ return ((ClientErrorException) e).getResponse();
+ }
+ if (e instanceof AuthenticationException) {
+ ErrorDTO errorDetail = new ErrorDTO();
+ errorDetail.setCode((long) 401);
+ errorDetail.setMoreInfo("");
+ errorDetail.setMessage("");
+ errorDetail.setDescription(e.getMessage());
+ return Response
+ .status(Response.Status.UNAUTHORIZED)
+ .entity(errorDetail)
+ .build();
+ }
+ if (e instanceof ForbiddenException) {
+ if (log.isDebugEnabled()) {
+ log.error("Resource forbidden.", e);
+ }
+ return ((ForbiddenException) e).getResponse();
+ }
+ //unknown exception log and return
+ if (log.isDebugEnabled()) {
+ log.error("An Unknown exception has been captured by global exception mapper.", e);
+ }
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header("Content-Type", "application/json")
+ .entity(e500).build();
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java
new file mode 100644
index 0000000000..ac9fc5c568
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/NotFoundException.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+
+import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+
+public class NotFoundException extends WebApplicationException {
+ private String message;
+ private static final long serialVersionUID = 147943572342342340L;
+
+ public NotFoundException(ErrorResponse error) {
+ super(Response.status(Response.Status.NOT_FOUND).entity(error).build());
+ }
+ public NotFoundException(ErrorDTO errorDTO) {
+ super(Response.status(Response.Status.NOT_FOUND)
+ .entity(errorDTO)
+ .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
+ .build());
+ message = errorDTO.getDescription();
+ }
+
+ @Override
+ public String getMessage() {
+ return message;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java
new file mode 100644
index 0000000000..40d5d74e68
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/UnexpectedServerErrorException.java
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+
+import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+
+public class UnexpectedServerErrorException extends WebApplicationException {
+ private String message;
+ private static final long serialVersionUID = 147943579458906890L;
+
+ public UnexpectedServerErrorException(ErrorResponse error) {
+ super(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build());
+ }
+ public UnexpectedServerErrorException(ErrorDTO errorDTO) {
+ super(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity(errorDTO)
+ .header(Constants.DeviceConstants.HEADER_CONTENT_TYPE, Constants.DeviceConstants.APPLICATION_JSON)
+ .build());
+ message = errorDTO.getDescription();
+ }
+
+ @Override
+ public String getMessage() {
+ return message;
+ }
+
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java
new file mode 100644
index 0000000000..480911b39b
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/exception/ValidationInterceptor.java
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.exception;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.cxf.interceptor.Fault;
+import org.apache.cxf.jaxrs.lifecycle.ResourceProvider;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageContentsList;
+import org.apache.cxf.phase.AbstractPhaseInterceptor;
+import org.apache.cxf.phase.Phase;
+
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.executable.ExecutableValidator;
+import java.lang.reflect.Method;
+import java.util.List;
+import java.util.Set;
+
+public class ValidationInterceptor extends AbstractPhaseInterceptor {
+ private Log log = LogFactory.getLog(getClass());
+ private Validator validator = null; //validator interface is thread-safe
+
+ public ValidationInterceptor() {
+ super(Phase.PRE_INVOKE);
+ ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
+ validator = defaultFactory.getValidator();
+ if (validator == null) {
+ log.warn("Bean Validation provider could not be found, no validation will be performed");
+ } else {
+ log.debug("Validation In-Interceptor initialized successfully");
+ }
+ }
+
+ @Override
+ public void handleMessage(Message message) throws Fault {
+ final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
+ if (operationResource == null) {
+ log.info("OperationResourceInfo is not available, skipping validation");
+ return;
+ }
+
+ final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
+ if (classResource == null) {
+ log.info("ClassResourceInfo is not available, skipping validation");
+ return;
+ }
+
+ final ResourceProvider resourceProvider = classResource.getResourceProvider();
+ if (resourceProvider == null) {
+ log.info("ResourceProvider is not available, skipping validation");
+ return;
+ }
+
+ final List
+
+ org.wso2.carbon.apimgt
+ org.wso2.carbon.apimgt.api
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java
index ad92cb27d8..6ba2f675c0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/Permission.java
@@ -24,47 +24,25 @@ import javax.xml.bind.annotation.XmlRootElement;
/**
* This class represents the information related to permission.
*/
-@XmlRootElement (name = "Permission")
public class Permission {
- private String name; // permission name
- private String path; // permission string
private String url; // url of the resource
+ private String urlTemplate; // resource template
private String method; // http method
- private String scope; //scope of the resource
+ private String context;
- public String getName() {
- return name;
+ public String getContext() {
+ return context;
}
- @XmlElement (name = "name", required = true)
- public void setName(String name) {
- this.name = name;
+ public void setContext(String context) {
+ this.context = context;
}
- public String getPath() {
- return path;
- }
-
- @XmlElement (name = "path", required = true)
- public void setPath(String path) {
- this.path = path;
- }
-
- public String getScope() {
- return scope;
- }
-
- @XmlElement(name = "scope", required = false)
- public void setScope(String scope) {
- this.scope = scope;
- }
-
public String getUrl() {
return url;
}
- @XmlElement (name = "url", required = true)
public void setUrl(String url) {
this.url = url;
}
@@ -73,8 +51,15 @@ public class Permission {
return method;
}
- @XmlElement (name = "method", required = true)
public void setMethod(String method) {
this.method = method;
}
+
+ public String getUrlTemplate() {
+ return urlTemplate;
+ }
+
+ public void setUrlTemplate(String urlTemplate) {
+ this.urlTemplate = urlTemplate;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java
index 30b771565d..10bb59bcb4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/permission/mgt/PermissionManagerService.java
@@ -29,11 +29,10 @@ public interface PermissionManagerService {
/**
*
* @param permission - Permission to be added
- * @return The status of the operation.
* @throws PermissionManagementException If some unusual behaviour is observed while adding the
* permission.
*/
- boolean addPermission(Permission permission) throws PermissionManagementException;
+ void addPermission(Permission permission) throws PermissionManagementException;
/**
*
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java
new file mode 100644
index 0000000000..ed5082a72c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementException.java
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.wso2.carbon.device.mgt.common.scope.mgt;
+
+/**
+ * This exception is used to throw when there is an issue in scope management service.
+ */
+public class ScopeManagementException extends Exception {
+
+ private static final long serialVersionUID = -315127931137779899L;
+
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public ScopeManagementException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public ScopeManagementException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public ScopeManagementException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public ScopeManagementException() {
+ super();
+ }
+
+ public ScopeManagementException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java
new file mode 100644
index 0000000000..b90011aaf0
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/scope/mgt/ScopeManagementService.java
@@ -0,0 +1,53 @@
+/*
+* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.device.mgt.common.scope.mgt;
+
+import java.util.List;
+import org.wso2.carbon.apimgt.api.model.Scope;
+
+/**
+ * This interface contains the basic operations related to scope management.
+ */
+public interface ScopeManagementService {
+
+ /**
+ * This method is used to update the given list of scopes.
+ *
+ * @param scopes List of scopes to be updated.
+ * @throws ScopeManagementException
+ */
+ void updateScopes(List scopes) throws ScopeManagementException;
+
+ /**
+ * This method is used to retrieve all the scopes.
+ *
+ * @return List of scopes.
+ * @throws ScopeManagementException
+ */
+ List getAllScopes() throws ScopeManagementException;
+
+ /**
+ * This method is to retrieve the roles of the given scope
+ * @param scopeKey key of the scope
+ * @return List of roles
+ * @throws ScopeManagementException
+ */
+ String getRolesOfScope(String scopeKey) throws ScopeManagementException;
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
index b96ddcac8d..e317b1d1b9 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
@@ -91,6 +91,10 @@
!org.wso2.carbon.device.mgt.core.internal,
org.wso2.carbon.device.mgt.core.*
+
+ javax.ws.rs-api,
+ scribe;scope=compile|runtime;inline=false;
+ *
@@ -228,6 +232,7 @@
commons-collections.wso2commons-collections
+
org.wso2.carbon.devicemgtorg.wso2.carbon.email.sender.core
@@ -236,15 +241,12 @@
mysqlmysql-connector-java
- 5.1.34test
-
com.google.code.gsongson
- 1.7.1
@@ -253,6 +255,26 @@
provided
+
+ org.wso2.orbit.org.scannotation
+ scannotation
+
+
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.apimgt.annotations
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+
+
+
+ javax.ws.rs
+ jsr311-api
+
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
index 27bbcc13ef..60b791a5fa 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/authorization/DeviceAccessAuthorizationServiceImpl.java
@@ -63,7 +63,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
throws DeviceAccessAuthorizationException {
int tenantId = this.getTenantId();
if (username == null || username.isEmpty()) {
- return false;
+ return !DeviceManagementDataHolder.getInstance().requireDeviceAuthorization(deviceIdentifier.getType());
}
//check for admin and ownership permissions
if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) {
@@ -243,9 +243,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
}
private boolean addAdminPermissionToRegistry() throws PermissionManagementException {
- Permission permission = new Permission();
- permission.setPath(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION));
- return PermissionUtils.putPermission(permission);
+ return PermissionUtils.putPermission(PermissionUtils.getAbsolutePermissionPath(CDM_ADMIN_PERMISSION));
}
private Map getOwnershipOfDevices(List devices) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java
new file mode 100644
index 0000000000..a847255a6e
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/AnnotationProcessor.java
@@ -0,0 +1,332 @@
+/*
+ * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.permission;
+
+import org.apache.catalina.core.StandardContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.scannotation.AnnotationDB;
+import org.wso2.carbon.apimgt.annotations.api.API;
+
+import javax.servlet.ServletContext;
+import javax.ws.rs.*;
+import java.io.File;
+import java.io.IOException;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+public class AnnotationProcessor {
+
+ private static final Log log = LogFactory.getLog(AnnotationProcessor.class);
+
+ private static final String PACKAGE_ORG_APACHE = "org.apache";
+ private static final String PACKAGE_ORG_CODEHAUS = "org.codehaus";
+ private static final String PACKAGE_ORG_SPRINGFRAMEWORK = "org.springframework";
+ private static final String WILD_CARD = "/*";
+ private static final String URL_SEPARATOR = "/";
+
+ private static final String STRING_ARR = "string_arr";
+ private static final String STRING = "string";
+
+ private Method[] pathClazzMethods;
+ private Class pathClazz;
+ Class apiClazz;
+ private ClassLoader classLoader;
+ private ServletContext servletContext;
+
+
+ public AnnotationProcessor(final StandardContext context) {
+ servletContext = context.getServletContext();
+ classLoader = servletContext.getClassLoader();
+ }
+
+ /**
+ * Scan the context for classes with annotations
+ *
+ * @return
+ * @throws IOException
+ */
+ public Set scanStandardContext(String className) throws IOException {
+ ExtendedAnnotationDB db = new ExtendedAnnotationDB();
+ db.addIgnoredPackages(PACKAGE_ORG_APACHE);
+ db.addIgnoredPackages(PACKAGE_ORG_CODEHAUS);
+ db.addIgnoredPackages(PACKAGE_ORG_SPRINGFRAMEWORK);
+ URL classPath = findWebInfClassesPath(servletContext);
+ db.scanArchives(classPath);
+
+ //Returns a list of classes with given Annotation
+ return db.getAnnotationIndex().get(className);
+ }
+
+ /**
+ * Method identifies the URL templates and context by reading the annotations of a class
+ *
+ * @param entityClasses
+ * @return
+ */
+ public List
+ extractPermissions(Set entityClasses) {
+
+ List permissions = new ArrayList<>();
+
+ if (entityClasses != null && !entityClasses.isEmpty()) {
+
+ for (final String className : entityClasses) {
+
+ List resourcePermissions =
+ AccessController.doPrivileged(new PrivilegedAction>() {
+ public List run() {
+ Class> clazz;
+ List apiPermissions =
+ new ArrayList<>();
+ try {
+ clazz = classLoader.loadClass(className);
+
+ apiClazz = (Class)
+ classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API
+ .class.getName());
+
+ Annotation apiAnno = clazz.getAnnotation(apiClazz);
+ List resourceList;
+
+ if (apiAnno != null) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("Application Context root = " + servletContext.getContextPath());
+ }
+
+ try {
+ String rootContext = servletContext.getContextPath();
+ pathClazz = (Class) classLoader.loadClass(Path.class.getName());
+ pathClazzMethods = pathClazz.getMethods();
+
+ Annotation rootContectAnno = clazz.getAnnotation(pathClazz);
+ String subContext = "";
+ if (rootContectAnno != null) {
+ subContext = invokeMethod(pathClazzMethods[0], rootContectAnno, STRING);
+ if (subContext != null && !subContext.isEmpty()) {
+ if (subContext.trim().startsWith("/")) {
+ rootContext = rootContext + subContext;
+ } else {
+ rootContext = rootContext + "/" + subContext;
+ }
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("API Root Context = " + rootContext);
+ }
+ }
+
+ Method[] annotatedMethods = clazz.getDeclaredMethods();
+ apiPermissions = getApiResources(rootContext, annotatedMethods);
+ } catch (Throwable throwable) {
+ log.error("Error encountered while scanning for annotations", throwable);
+ }
+ }
+ } catch (ClassNotFoundException e) {
+ log.error("Error when passing the api annotation for device type apis.");
+ }
+ return apiPermissions;
+ }
+ });
+ permissions.addAll(resourcePermissions);
+ }
+ }
+ return permissions;
+ }
+
+
+ /**
+ * Get Resources for each API
+ *
+ * @param resourceRootContext
+ * @param annotatedMethods
+ * @return
+ * @throws Throwable
+ */
+ private List
+ getApiResources(String resourceRootContext, Method[] annotatedMethods) throws Throwable {
+
+ List permissions = new ArrayList<>();
+ String subCtx;
+ for (Method method : annotatedMethods) {
+ Annotation[] annotations = method.getDeclaredAnnotations();
+ org.wso2.carbon.device.mgt.common.permission.mgt.Permission permission =
+ new org.wso2.carbon.device.mgt.common.permission.mgt.Permission();
+
+ if (isHttpMethodAvailable(annotations)) {
+ Annotation methodContextAnno = method.getAnnotation(pathClazz);
+ if (methodContextAnno != null) {
+ subCtx = invokeMethod(pathClazzMethods[0], methodContextAnno, STRING);
+ } else {
+ subCtx = WILD_CARD;
+ }
+ permission.setContext(makeContextURLReady(resourceRootContext));
+ permission.setUrlTemplate(makeContextURLReady(subCtx));
+
+ // this check is added to avoid url resolving conflict which happens due
+ // to adding of '*' notation for dynamic path variables.
+ if (WILD_CARD.equals(subCtx)) {
+ subCtx = makeContextURLReady(resourceRootContext);
+ } else {
+ subCtx = makeContextURLReady(resourceRootContext) + makeContextURLReady(subCtx);
+ }
+ permission.setUrl(replaceDynamicPathVariables(subCtx));
+ String httpMethod;
+ for (int i = 0; i < annotations.length; i++) {
+ httpMethod = getHTTPMethodAnnotation(annotations[i]);
+ if (httpMethod != null) {
+ permission.setMethod(httpMethod);
+ break;
+ }
+ }
+ permissions.add(permission);
+ }
+ }
+ return permissions;
+ }
+
+ /**
+ * Read Method annotations indicating HTTP Methods
+ * @param annotation
+ */
+ private String getHTTPMethodAnnotation(Annotation annotation) {
+ if (annotation.annotationType().getName().equals(GET.class.getName())) {
+ return HttpMethod.GET;
+ } else if (annotation.annotationType().getName().equals(POST.class.getName())) {
+ return HttpMethod.POST;
+ } else if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) {
+ return HttpMethod.OPTIONS;
+ } else if (annotation.annotationType().getName().equals(DELETE.class.getName())) {
+ return HttpMethod.DELETE;
+ } else if (annotation.annotationType().getName().equals(PUT.class.getName())) {
+ return HttpMethod.PUT;
+ }
+ return null;
+ }
+
+ private boolean isHttpMethodAvailable(Annotation[] annotations) {
+ for (Annotation annotation : annotations) {
+ if (annotation.annotationType().getName().equals(GET.class.getName())) {
+ return true;
+ } else if (annotation.annotationType().getName().equals(POST.class.getName())) {
+ return true;
+ } else if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) {
+ return true;
+ } else if (annotation.annotationType().getName().equals(DELETE.class.getName())) {
+ return true;
+ } else if (annotation.annotationType().getName().equals(PUT.class.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Append '/' to the context and make it URL ready
+ *
+ * @param context
+ * @return
+ */
+ private String makeContextURLReady(String context) {
+ if (context != null && ! context.isEmpty()) {
+ if (context.startsWith("/")) {
+ return context;
+ } else {
+ return "/" + context;
+ }
+ }
+ return "";
+ }
+
+ /**
+ * When an annotation and method is passed, this method invokes that executes said method against the annotation
+ *
+ * @param method
+ * @param annotation
+ * @param returnType
+ * @return
+ * @throws Throwable
+ */
+ private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
+ InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
+ switch (returnType) {
+ case STRING:
+ return (String) methodHandler.invoke(annotation, method, null);
+ case STRING_ARR:
+ return ((String[]) methodHandler.invoke(annotation, method, null))[0];
+ default:
+ return null;
+ }
+ }
+
+
+ /**
+ * Find the URL pointing to "/WEB-INF/classes" This method may not work in conjunction with IteratorFactory
+ * if your servlet container does not extract the /WEB-INF/classes into a real file-based directory
+ *
+ * @param servletContext
+ * @return null if cannot determin /WEB-INF/classes
+ */
+ public static URL findWebInfClassesPath(ServletContext servletContext)
+ {
+ String path = servletContext.getRealPath("/WEB-INF/classes");
+ if (path == null) return null;
+ File fp = new File(path);
+ if (fp.exists() == false) return null;
+ try
+ {
+ URI uri = fp.toURI();
+ return uri.toURL();
+ }
+ catch (MalformedURLException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private String replaceDynamicPathVariables(String path) {
+ StringBuilder replacedPath = new StringBuilder();
+ StringTokenizer st = new StringTokenizer(path, URL_SEPARATOR);
+ String currentToken;
+ while (st.hasMoreTokens()) {
+ currentToken = st.nextToken();
+ if (currentToken.charAt(0) == '{') {
+ if (currentToken.charAt(currentToken.length() - 1) == '}') {
+ replacedPath.append(WILD_CARD);
+ }
+ } else {
+ replacedPath.append(URL_SEPARATOR);
+ replacedPath.append(currentToken);
+ }
+ }
+ return replacedPath.toString();
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java
new file mode 100644
index 0000000000..dbbd97e3a6
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedAnnotationDB.java
@@ -0,0 +1,92 @@
+/*
+* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.wso2.carbon.device.mgt.core.config.permission;
+
+import org.scannotation.AnnotationDB;
+import org.scannotation.archiveiterator.Filter;
+import org.scannotation.archiveiterator.StreamIterator;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+
+public class ExtendedAnnotationDB extends AnnotationDB {
+
+ public ExtendedAnnotationDB() {
+ super();
+ }
+
+ public void scanArchives(URL... urls) throws IOException {
+ URL[] arr$ = urls;
+ int len$ = urls.length;
+
+ for(int i$ = 0; i$ < len$; ++i$) {
+ URL url = arr$[i$];
+ Filter filter = new Filter() {
+ public boolean accepts(String filename) {
+ if(filename.endsWith(".class")) {
+ if(filename.startsWith("/") || filename.startsWith("\\")) {
+ filename = filename.substring(1);
+ }
+
+ if(!ExtendedAnnotationDB.this.ignoreScan(filename.replace('/', '.'))) {
+ return true;
+ }
+ }
+ return false;
+ }
+ };
+ StreamIterator it = ExtendedIteratorFactory.create(url, filter);
+
+ InputStream stream;
+ while((stream = it.next()) != null) {
+ this.scanClass(stream);
+ }
+ }
+
+ }
+
+ private boolean ignoreScan(String intf) {
+ String[] arr$;
+ int len$;
+ int i$;
+ String ignored;
+ if(this.scanPackages != null) {
+ arr$ = this.scanPackages;
+ len$ = arr$.length;
+
+ for(i$ = 0; i$ < len$; ++i$) {
+ ignored = arr$[i$];
+ if(intf.startsWith(ignored + ".")) {
+ return false;
+ }
+ }
+
+ return true;
+ } else {
+ arr$ = this.ignoredPackages;
+ len$ = arr$.length;
+
+ for(i$ = 0; i$ < len$; ++i$) {
+ ignored = arr$[i$];
+ if(intf.startsWith(ignored + ".")) {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java
new file mode 100644
index 0000000000..1394375656
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedFileProtocolIteratorFactory.java
@@ -0,0 +1,32 @@
+/*
+* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.wso2.carbon.device.mgt.core.config.permission;
+
+import org.scannotation.archiveiterator.*;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+
+public class ExtendedFileProtocolIteratorFactory implements DirectoryIteratorFactory {
+
+ @Override
+ public StreamIterator create(URL url, Filter filter) throws IOException {
+ File f = new File(java.net.URLDecoder.decode(url.getPath(), "UTF-8"));
+ return f.isDirectory()?new FileIterator(f, filter):new JarIterator(url.openStream(), filter);
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java
new file mode 100644
index 0000000000..18c8b7620c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/ExtendedIteratorFactory.java
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* Licensed under the Apache License, Version 2.0 (the "License");
+* you may not use this file except in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing, software
+* distributed under the License is distributed on an "AS IS" BASIS,
+* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+* See the License for the specific language governing permissions and
+* limitations under the License.
+*/
+package org.wso2.carbon.device.mgt.core.config.permission;
+
+import org.scannotation.archiveiterator.DirectoryIteratorFactory;
+import org.scannotation.archiveiterator.Filter;
+import org.scannotation.archiveiterator.JarIterator;
+import org.scannotation.archiveiterator.StreamIterator;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class ExtendedIteratorFactory {
+
+ private static final ConcurrentHashMap registry = new ConcurrentHashMap();
+
+ public static StreamIterator create(URL url, Filter filter) throws IOException {
+ String urlString = url.toString();
+ if(urlString.endsWith("!/")) {
+ urlString = urlString.substring(4);
+ urlString = urlString.substring(0, urlString.length() - 2);
+ url = new URL(urlString);
+ }
+
+ if(!urlString.endsWith("/")) {
+ return new JarIterator(url.openStream(), filter);
+ } else {
+ DirectoryIteratorFactory factory = registry.get(url.getProtocol());
+ if(factory == null) {
+ throw new IOException("Unable to scan directory of protocol: " + url.getProtocol());
+ } else {
+ return factory.create(url, filter);
+ }
+ }
+ }
+
+ static {
+ registry.put("file", new ExtendedFileProtocolIteratorFactory());
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java
index f974ea5f20..7911ff7cdf 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/PermissionConfiguration.java
@@ -25,29 +25,27 @@ import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
- * This class represents the information related to permission configuration.
+ * This class represents the information related to permissions.
*/
-@XmlRootElement (name = "PermissionConfiguration")
public class PermissionConfiguration {
- private List permissions;
- private String apiVersion;
+ private String scopeName;
+ private String[] permissions;
- public String getApiVersion() {
- return apiVersion;
+ public String getScopeName() {
+ return scopeName;
}
- @XmlElement (name = "APIVersion", required = true)
- public void setApiVersion(String apiVersion) {
- this.apiVersion = apiVersion;
+ public void setScopeName(String scope) {
+ this.scopeName = scope;
}
- public List getPermissions() {
+ public String[] getPermissions() {
return permissions;
}
- @XmlElement (name = "Permission", required = true)
- public void setPermissions(List permissions) {
+ public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java
index f274eee845..fbde8047e3 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/permission/lifecycle/WebAppDeploymentLifecycleListener.java
@@ -26,6 +26,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
+import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
+import org.wso2.carbon.device.mgt.core.config.permission.AnnotationProcessor;
import org.wso2.carbon.device.mgt.core.config.permission.PermissionConfiguration;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
@@ -35,8 +37,10 @@ import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
+import java.io.IOException;
import java.io.InputStream;
import java.util.List;
+import java.util.Set;
/**
* This listener class will initiate the permission addition of permissions defined in
@@ -45,7 +49,8 @@ import java.util.List;
@SuppressWarnings("unused")
public class WebAppDeploymentLifecycleListener implements LifecycleListener {
- private static final String PERMISSION_CONFIG_PATH = "META-INF" + File.separator + "permissions.xml";
+ private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
+
private static final Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class);
@Override
@@ -54,34 +59,27 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext();
String contextPath = context.getServletContext().getContextPath();
- try {
- InputStream permissionStream = servletContext.getResourceAsStream(PERMISSION_CONFIG_PATH);
- if (permissionStream != null) {
- /* Un-marshaling Device Management configuration */
- JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
- Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
- PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
- unmarshaller.unmarshal(permissionStream);
- List permissions = permissionConfiguration.getPermissions();
- String apiVersion = permissionConfiguration.getApiVersion();
- if (permissionConfiguration != null && permissions != null) {
+ String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
+ boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
+
+ if (isManagedApi) {
+ try {
+ AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
+ Set annotatedAPIClasses = annotationProcessor.
+ scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
+ List permissions = annotationProcessor.extractPermissions(annotatedAPIClasses);
+ PermissionManagerService permissionManagerService = PermissionManagerServiceImpl.getInstance();
+ if (permissions != null) {
for (Permission permission : permissions) {
- // update the permission path to absolute permission path
- permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath()));
- permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion,
- permission.getUrl()).toLowerCase());
- permission.setMethod(permission.getMethod().toUpperCase());
- PermissionManagerServiceImpl.getInstance().addPermission(permission);
+ permissionManagerService.addPermission(permission);
}
}
+ } catch (PermissionManagementException e) {
+ log.error("Exception occurred while adding the permissions from webapp : "
+ + servletContext.getContextPath(), e);
+ } catch (IOException e) {
+ log.error("Cannot find API annotation Class in the webapp '" + contextPath + "' class path", e);
}
- } catch (JAXBException e) {
- log.error(
- "Exception occurred while parsing the permission configuration of webapp : "
- + context.getServletContext().getContextPath(), e);
- } catch (PermissionManagementException e) {
- log.error("Exception occurred while adding the permissions from webapp : "
- + servletContext.getContextPath(), e);
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
index 8ca3ca45cc..7f5f5f5e97 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
@@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.internal;
+import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
@@ -56,6 +57,16 @@ public class DeviceManagementDataHolder {
private EmailSenderService emailSenderService;
private PushNotificationProviderRepository pushNotificationProviderRepository;
+ public APIManagerConfiguration getApiManagerConfiguration() {
+ return apiManagerConfiguration;
+ }
+
+ public void setApiManagerConfiguration(APIManagerConfiguration apiManagerConfiguration) {
+ this.apiManagerConfiguration = apiManagerConfiguration;
+ }
+
+ private APIManagerConfiguration apiManagerConfiguration;
+
private DeviceManagementDataHolder() {}
public static DeviceManagementDataHolder getInstance() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
index 6669baadde..03a96ea520 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
@@ -21,6 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
@@ -30,6 +31,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
@@ -50,6 +52,8 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl;
import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository;
+import org.wso2.carbon.device.mgt.core.scope.mgt.ScopeManagementServiceImpl;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
@@ -59,8 +63,10 @@ import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService;
+import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
+import java.io.File;
import java.util.ArrayList;
import java.util.List;
@@ -117,6 +123,9 @@ public class DeviceManagementServiceComponent {
private static List deviceManagers = new ArrayList<>();
private static List startupListeners = new ArrayList<>();
private DeviceManagementPluginRepository pluginRepository = new DeviceManagementPluginRepository();
+ private static final String APIM_CONFIGURATION_PATH = CarbonUtils.getCarbonHome() + File.separator + "repository" +
+ File.separator + "conf" + File.separator + "api-manager.xml";
+ private static final String DATA_SOURCE_NAME = "DataSourceName";
public static void registerPluginInitializationListener(PluginInitializationListener listener) {
synchronized (LOCK) {
@@ -149,12 +158,19 @@ public class DeviceManagementServiceComponent {
DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig();
+
+ APIManagerConfiguration apiManagerConfiguration = new APIManagerConfiguration();
+ apiManagerConfiguration.load(APIM_CONFIGURATION_PATH);
+ DeviceManagementDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfiguration);
+
DeviceManagementDAOFactory.init(dsConfig);
GroupManagementDAOFactory.init(dsConfig);
NotificationManagementDAOFactory.init(dsConfig);
-
OperationManagementDAOFactory.init(dsConfig);
+ String apiManagerDataSource = apiManagerConfiguration.getFirstProperty(DATA_SOURCE_NAME);
+ ScopeManagementDAOFactory.init(apiManagerDataSource);
+
/* Initialize Operation Manager */
this.initOperationsManager();
@@ -227,10 +243,9 @@ public class DeviceManagementServiceComponent {
= new NotificationManagementServiceImpl();
bundleContext.registerService(NotificationManagementService.class.getName(), notificationManagementService, null);
- /* Registering PermissionManager Service */
- PermissionManagerService permissionManagerService
- = PermissionManagerServiceImpl.getInstance();
- bundleContext.registerService(PermissionManagerService.class.getName(), permissionManagerService, null);
+ /* Registering Scope Management Service */
+ ScopeManagementService scopeManagementService = new ScopeManagementServiceImpl();
+ bundleContext.registerService(ScopeManagementService.class.getName(), scopeManagementService, null);
/* Registering DeviceAccessAuthorization Service */
DeviceAccessAuthorizationService deviceAccessAuthorizationService = new DeviceAccessAuthorizationServiceImpl();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java
index 190b90dbc7..0cdae21617 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionManagerServiceImpl.java
@@ -22,8 +22,9 @@ import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagerService;
-import java.util.List;
+import java.util.HashSet;
import java.util.Properties;
+import java.util.Set;
/**
* This class will add, update custom permissions defined in permission.xml in webapps and it will
@@ -52,16 +53,19 @@ public class PermissionManagerServiceImpl implements PermissionManagerService {
}
@Override
- public boolean addPermission(Permission permission) throws PermissionManagementException {
+ public void addPermission(Permission permission) throws PermissionManagementException {
// adding a permission to the tree
permissionTree.addPermission(permission);
- return PermissionUtils.putPermission(permission);
}
@Override
public Permission getPermission(Properties properties) throws PermissionManagementException {
String url = (String) properties.get(URL_PROPERTY);
String httpMethod = (String) properties.get(HTTP_METHOD_PROPERTY);
+
+ if (url == null || url.isEmpty() || httpMethod == null || httpMethod.isEmpty()) {
+ throw new PermissionManagementException("Resource URI/HTTP method is empty");
+ }
return permissionTree.getPermission(url, httpMethod);
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java
index 8294cce8a0..62af312e66 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionTree.java
@@ -54,9 +54,6 @@ public class PermissionTree {
tempRoot = addPermissionNode(tempRoot, tempChild);
}
tempRoot.addPermission(permission.getMethod(), permission); //setting permission to the vertex
- if (log.isDebugEnabled()) {
- log.debug("Added permission '" + permission.getName() + "'");
- }
}
/**
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java
index 27b95e56cc..9f73a36e1c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/permission/mgt/PermissionUtils.java
@@ -39,84 +39,82 @@ import java.util.StringTokenizer;
*/
public class PermissionUtils {
- public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin";
- public static final String PERMISSION_PROPERTY_NAME = "name";
+ public static final String ADMIN_PERMISSION_REGISTRY_PATH = "/permission/admin";
+ public static final String PERMISSION_PROPERTY_NAME = "name";
- public static Registry getGovernanceRegistry() throws PermissionManagementException {
- try {
- int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
- return DeviceManagementDataHolder.getInstance().getRegistryService()
- .getGovernanceSystemRegistry(
- tenantId);
- } catch (RegistryException e) {
- throw new PermissionManagementException(
- "Error in retrieving governance registry instance: " +
- e.getMessage(), e);
- }
- }
+ public static Registry getGovernanceRegistry() throws PermissionManagementException {
+ try {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+ return DeviceManagementDataHolder.getInstance().getRegistryService()
+ .getGovernanceSystemRegistry(
+ tenantId);
+ } catch (RegistryException e) {
+ throw new PermissionManagementException(
+ "Error in retrieving governance registry instance: " +
+ e.getMessage(), e);
+ }
+ }
- public static String getAbsolutePermissionPath(String permissionPath) {
- return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath;
- }
+ public static String getAbsolutePermissionPath(String permissionPath) {
+ return PermissionUtils.ADMIN_PERMISSION_REGISTRY_PATH + permissionPath;
+ }
public static String getAbsoluteContextPathOfAPI(String contextPath, String version, String url) {
- if((version != null) && !version.isEmpty()) {
- return contextPath + "/" + version + url;
+ if ((version != null) && !version.isEmpty()) {
+ return contextPath + "/" + version + url;
}
return contextPath + url;
}
- public static Permission getPermission(String path) throws PermissionManagementException {
- try {
- Resource resource = PermissionUtils.getGovernanceRegistry().get(path);
- Permission permission = new Permission();
- permission.setName(resource.getProperty(PERMISSION_PROPERTY_NAME));
- permission.setPath(resource.getPath());
- return permission;
- } catch (RegistryException e) {
- throw new PermissionManagementException("Error in retrieving registry resource : " +
- e.getMessage(), e);
- }
- }
-
- public static boolean putPermission(Permission permission)
- throws PermissionManagementException {
- boolean status;
- try {
- StringTokenizer tokenizer = new StringTokenizer(permission.getPath(), "/");
- String lastToken = "", currentToken, tempPath;
- while(tokenizer.hasMoreTokens()) {
- currentToken = tokenizer.nextToken();
- tempPath = lastToken + "/" + currentToken;
- if(!checkResourceExists(tempPath)) {
+ // public static Permission getPermission(String path) throws PermissionManagementException {
+// try {
+// Resource resource = PermissionUtils.getGovernanceRegistry().get(path);
+// Permission permission = new Permission();
+// permission.setName(resource.getProperty(PERMISSION_PROPERTY_NAME));
+// permission.setPath(resource.getPath());
+// return permission;
+// } catch (RegistryException e) {
+// throw new PermissionManagementException("Error in retrieving registry resource : " +
+// e.getMessage(), e);
+// }
+// }
+//
+ public static boolean putPermission(String permissionPath)
+ throws PermissionManagementException {
+ boolean status;
+ try {
+ StringTokenizer tokenizer = new StringTokenizer(permissionPath, "/");
+ String lastToken = "", currentToken, tempPath;
+ while (tokenizer.hasMoreTokens()) {
+ currentToken = tokenizer.nextToken();
+ tempPath = lastToken + "/" + currentToken;
+ if (!checkResourceExists(tempPath)) {
createRegistryCollection(tempPath, currentToken);
- }
- lastToken = tempPath;
- }
- status = true;
- } catch (RegistryException e) {
- throw new PermissionManagementException(
- "Error occurred while persisting permission : " +
- permission.getName(), e);
- }
- return status;
- }
+ }
+ lastToken = tempPath;
+ }
+ status = true;
+ } catch (RegistryException e) {
+ throw new PermissionManagementException("Error occurred while persisting permission", e);
+ }
+ return status;
+ }
- public static void createRegistryCollection(String path, String resourceName)
- throws PermissionManagementException,
- RegistryException {
- Resource resource = PermissionUtils.getGovernanceRegistry().newCollection();
- resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName);
- PermissionUtils.getGovernanceRegistry().beginTransaction();
- PermissionUtils.getGovernanceRegistry().put(path, resource);
- PermissionUtils.getGovernanceRegistry().commitTransaction();
- }
+ public static void createRegistryCollection(String path, String resourceName)
+ throws PermissionManagementException,
+ RegistryException {
+ Resource resource = PermissionUtils.getGovernanceRegistry().newCollection();
+ resource.addProperty(PERMISSION_PROPERTY_NAME, resourceName);
+ PermissionUtils.getGovernanceRegistry().beginTransaction();
+ PermissionUtils.getGovernanceRegistry().put(path, resource);
+ PermissionUtils.getGovernanceRegistry().commitTransaction();
+ }
- public static boolean checkResourceExists(String path)
- throws PermissionManagementException,
- org.wso2.carbon.registry.core.exceptions.RegistryException {
- return PermissionUtils.getGovernanceRegistry().resourceExists(path);
- }
+ public static boolean checkResourceExists(String path)
+ throws PermissionManagementException,
+ org.wso2.carbon.registry.core.exceptions.RegistryException {
+ return PermissionUtils.getGovernanceRegistry().resourceExists(path);
+ }
public static Document convertToDocument(File file) throws PermissionManagementException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java
new file mode 100644
index 0000000000..59418e760f
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/ScopeManagementServiceImpl.java
@@ -0,0 +1,97 @@
+/*
+* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.device.mgt.core.scope.mgt;
+
+import org.wso2.carbon.apimgt.api.model.Scope;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementException;
+import org.wso2.carbon.device.mgt.common.scope.mgt.ScopeManagementService;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAO;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOException;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory;
+
+import java.lang.annotation.Inherited;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This is an implementation of a Scope Management Service.
+ */
+public class ScopeManagementServiceImpl implements ScopeManagementService {
+
+ private ScopeManagementDAO scopeManagementDAO;
+
+ public ScopeManagementServiceImpl() {
+ this.scopeManagementDAO = ScopeManagementDAOFactory.getScopeManagementDAO();
+ }
+
+ @Override
+ public void updateScopes(List scopes) throws ScopeManagementException {
+ try{
+ ScopeManagementDAOFactory.beginTransaction();
+ scopeManagementDAO.updateScopes(scopes);
+ ScopeManagementDAOFactory.commitTransaction();
+ } catch (TransactionManagementException e) {
+ ScopeManagementDAOFactory.rollbackTransaction();
+ throw new ScopeManagementException("Transactional error occurred while adding the scopes.", e);
+ } catch (ScopeManagementDAOException e) {
+ ScopeManagementDAOFactory.rollbackTransaction();
+ throw new ScopeManagementException("Error occurred while adding the scopes to database.", e);
+ } finally {
+ ScopeManagementDAOFactory.closeConnection();
+ }
+ }
+
+ @Override
+ public List getAllScopes() throws ScopeManagementException {
+ List scopes = new ArrayList<>();
+ try{
+ ScopeManagementDAOFactory.openConnection();
+ scopes = scopeManagementDAO.getAllScopes();
+ } catch (SQLException e) {
+ throw new ScopeManagementException("SQL error occurred while retrieving scopes from database.", e);
+ } catch (ScopeManagementDAOException e) {
+ throw new ScopeManagementException("Error occurred while retrieving scopes from database.", e);
+ } finally {
+ ScopeManagementDAOFactory.closeConnection();
+ }
+ return scopes;
+ }
+
+ @Override
+ public String getRolesOfScope(String scopeKey) throws ScopeManagementException {
+ String roles;
+ if (scopeKey == null || scopeKey.isEmpty()) {
+ throw new ScopeManagementException("Scope key is null or empty");
+ }
+ try {
+ ScopeManagementDAOFactory.openConnection();
+ roles = scopeManagementDAO.getRolesOfScope(scopeKey);
+ } catch (SQLException e) {
+ throw new ScopeManagementException("SQL error occurred while retrieving roles of scope from database.", e);
+ } catch (ScopeManagementDAOException e) {
+ throw new ScopeManagementException("Error occurred while retrieving roles of scope from database.", e);
+ } finally {
+ ScopeManagementDAOFactory.closeConnection();
+ }
+ return roles;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java
new file mode 100644
index 0000000000..38517f6c4e
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAO.java
@@ -0,0 +1,54 @@
+/*
+* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.device.mgt.core.scope.mgt.dao;
+
+import org.wso2.carbon.apimgt.api.model.Scope;
+
+import java.util.List;
+
+/**
+ * This interface contains the basic database operations related to scope management.
+ */
+public interface ScopeManagementDAO {
+
+ /**
+ * This method is used to update the list of scopes.
+ *
+ * @param scopes List of scopes to be updated.
+ * @throws ScopeManagementDAOException
+ */
+ void updateScopes(List scopes) throws ScopeManagementDAOException;
+
+ /**
+ * This method is used to retrieve all the scopes.
+ *
+ * @return List of scopes.
+ * @throws ScopeManagementDAOException
+ */
+ List getAllScopes() throws ScopeManagementDAOException;
+
+ /**
+ * This method is to retrieve the roles of the given scope
+ * @param scopeKey key of the scope
+ * @return List of roles
+ * @throws ScopeManagementDAOException
+ */
+ String getRolesOfScope(String scopeKey) throws ScopeManagementDAOException;
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java
new file mode 100644
index 0000000000..61ea7de2e2
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOException.java
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+package org.wso2.carbon.device.mgt.core.scope.mgt.dao;
+
+public class ScopeManagementDAOException extends Exception {
+
+ private static final long serialVersionUID = -315127931137771199L;
+
+ private String errorMessage;
+
+ public String getErrorMessage() {
+ return errorMessage;
+ }
+
+ public void setErrorMessage(String errorMessage) {
+ this.errorMessage = errorMessage;
+ }
+
+ public ScopeManagementDAOException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ setErrorMessage(msg);
+ }
+
+ public ScopeManagementDAOException(String message, Throwable cause) {
+ super(message, cause);
+ setErrorMessage(message);
+ }
+
+ public ScopeManagementDAOException(String msg) {
+ super(msg);
+ setErrorMessage(msg);
+ }
+
+ public ScopeManagementDAOException() {
+ super();
+ }
+
+ public ScopeManagementDAOException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java
new file mode 100644
index 0000000000..cb53d76f29
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOFactory.java
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.core.scope.mgt.dao;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
+import org.wso2.carbon.device.mgt.common.TransactionManagementException;
+import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.impl.ScopeManagementDAOImpl;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class ScopeManagementDAOFactory {
+
+ private static final Log log = LogFactory.getLog(ScopeManagementDAOFactory.class);
+ private static DataSource dataSource;
+ private static String databaseEngine;
+ private static ThreadLocal currentConnection = new ThreadLocal();
+
+ public static ScopeManagementDAO getScopeManagementDAO() {
+ return new ScopeManagementDAOImpl();
+ }
+
+ public static void init(String dataSourceName) {
+ dataSource = resolveDataSource(dataSourceName);
+ try {
+ databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
+ } catch (SQLException e) {
+ log.error("Error occurred while retrieving config.datasource connection", e);
+ }
+ }
+
+ public static void beginTransaction() throws TransactionManagementException {
+ try {
+ Connection conn = dataSource.getConnection();
+ conn.setAutoCommit(false);
+ currentConnection.set(conn);
+ } catch (SQLException e) {
+ throw new TransactionManagementException(
+ "Error occurred while retrieving config.datasource connection", e);
+ }
+ }
+
+ public static void openConnection() throws SQLException {
+ currentConnection.set(dataSource.getConnection());
+ }
+
+ public static Connection getConnection() throws SQLException {
+ if (currentConnection.get() == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ return currentConnection.get();
+ }
+
+ public static void closeConnection() {
+ Connection con = currentConnection.get();
+ if (con != null) {
+ try {
+ con.close();
+ } catch (SQLException e) {
+ log.error("Error occurred while close the connection");
+ }
+ currentConnection.remove();
+ }
+ }
+
+ public static void commitTransaction() {
+ try {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ conn.commit();
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Datasource connection associated with the current thread is null, hence commit " +
+ "has not been attempted");
+ }
+ }
+ } catch (SQLException e) {
+ log.error("Error occurred while committing the transaction", e);
+ }
+ }
+
+ public static void rollbackTransaction() {
+ try {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ conn.rollback();
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Datasource connection associated with the current thread is null, hence rollback " +
+ "has not been attempted");
+ }
+ }
+ } catch (SQLException e) {
+ log.error("Error occurred while roll-backing the transaction", e);
+ }
+ }
+
+ /**
+ * Resolve data source from the data source name.
+ *
+ * @param dataSourceName data source name
+ * @return data source resolved from the data source definition
+ */
+ private static DataSource resolveDataSource(String dataSourceName) {
+ DataSource dataSource;
+ if (dataSourceName == null || dataSourceName.isEmpty()) {
+ throw new RuntimeException("Scope Management Repository data source configuration is null and " +
+ "thus, is not initialized");
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("Initializing Scope Management Repository data source using the JNDI Lookup Definition");
+ }
+ dataSource = DeviceManagementDAOUtil.lookupDataSource(dataSourceName, null);
+ return dataSource;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java
new file mode 100644
index 0000000000..570b4ce07d
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/ScopeManagementDAOUtil.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ */
+package org.wso2.carbon.device.mgt.core.scope.mgt.dao;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+public class ScopeManagementDAOUtil {
+
+ private static final Log log = LogFactory.getLog(ScopeManagementDAOUtil.class);
+
+ public static void cleanupResources(Statement stmt, ResultSet rs) {
+ if (rs != null) {
+ try {
+ rs.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing the result set", e);
+ }
+ }
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing the statement", e);
+ }
+ }
+ }
+ public static void cleanupResources(Statement stmt) {
+ if (stmt != null) {
+ try {
+ stmt.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while closing the statement", e);
+ }
+ }
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java
new file mode 100644
index 0000000000..7e46392446
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/scope/mgt/dao/impl/ScopeManagementDAOImpl.java
@@ -0,0 +1,121 @@
+/*
+* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+*
+* WSO2 Inc. licenses this file to you under the Apache License,
+* Version 2.0 (the "License"); you may not use this file except
+* in compliance with the License.
+* You may obtain a copy of the License at
+*
+* http://www.apache.org/licenses/LICENSE-2.0
+*
+* Unless required by applicable law or agreed to in writing,
+* software distributed under the License is distributed on an
+* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+* KIND, either express or implied. See the License for the
+* specific language governing permissions and limitations
+* under the License.
+*/
+
+package org.wso2.carbon.device.mgt.core.scope.mgt.dao.impl;
+
+import org.wso2.carbon.apimgt.api.model.Scope;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAO;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOException;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.scope.mgt.dao.ScopeManagementDAOUtil;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
+
+public class ScopeManagementDAOImpl implements ScopeManagementDAO {
+
+ @Override
+ public void updateScopes(List scopes) throws ScopeManagementDAOException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+
+ try {
+ conn = this.getConnection();
+ String sql = "UPDATE IDN_OAUTH2_SCOPE SET ROLES=? WHERE SCOPE_KEY=?";
+ stmt = conn.prepareStatement(sql);
+
+ // creating a batch request
+ for (Scope scope : scopes) {
+ stmt.setString(1, scope.getRoles());
+ stmt.setString(2, scope.getKey());
+ stmt.addBatch();
+ }
+ stmt.executeBatch();
+ } catch (SQLException e) {
+ throw new ScopeManagementDAOException("Error occurred while updating the details of the scopes.", e);
+ } finally {
+ ScopeManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+
+ }
+
+
+ public List getAllScopes() throws ScopeManagementDAOException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ List scopes = new ArrayList<>();
+ Scope scope;
+
+ try {
+ conn = this.getConnection();
+ String sql = "SELECT * FROM IDN_OAUTH2_SCOPE";
+ stmt = conn.prepareStatement(sql);
+ rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ scope = new Scope();
+ scope.setKey(rs.getString("SCOPE_KEY"));
+ scope.setName(rs.getString("NAME"));
+ scope.setDescription(rs.getString("DESCRIPTION"));
+ scope.setRoles(rs.getString("ROLES"));
+ scopes.add(scope);
+ }
+ return scopes;
+ } catch (SQLException e) {
+ throw new ScopeManagementDAOException("Error occurred while fetching the details of the scopes.", e);
+ } finally {
+ ScopeManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+ }
+
+ @Override
+ public String getRolesOfScope(String scopeKey) throws ScopeManagementDAOException {
+ Connection conn;
+ PreparedStatement stmt = null;
+ ResultSet rs = null;
+ String roles = null;
+
+ try {
+ conn = this.getConnection();
+ String sql = "SELECT ROLES FROM IDN_OAUTH2_SCOPE WHERE SCOPE_KEY = ?";
+ stmt = conn.prepareStatement(sql);
+ stmt.setString(1, scopeKey);
+ rs = stmt.executeQuery();
+
+ if (rs.next()) {
+ roles = rs.getString("ROLES");
+ }
+ return roles;
+ } catch (SQLException e) {
+ throw new ScopeManagementDAOException("Error occurred while fetching the details of the scopes.", e);
+ } finally {
+ ScopeManagementDAOUtil.cleanupResources(stmt, rs);
+ }
+ }
+
+ private Connection getConnection() throws SQLException {
+ return ScopeManagementDAOFactory.getConnection();
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag
index ce0dbd1d41..05ca19906a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/api/data-tables-invoker-api.jag
@@ -39,18 +39,26 @@ if (uriMatcher.match("/{context}/api/data-tables/invoker")) {
for (var key in allParams) {
if (allParams.hasOwnProperty(key)) {
- if (key == "limit" || key == "offset" || key == "filter") {
+ if(key == "limit" || key == "offset"){
targetURL = appendQueryParam(targetURL, key, allParams[key]);
}
+ if(key == "filter"){
+ if(allParams[key]){
+ var searchPayload = JSON.parse(allParams[key]);
+ for (var key in searchPayload) {
+ targetURL = appendQueryParam(targetURL, key, searchPayload[key]);
+ }
+ }
+ }
}
}
serviceInvokers.XMLHttp.get(
- targetURL,
- // response callback
- function (backendResponse) {
- response["status"] = backendResponse["status"];
- response["content"] = backendResponse["responseText"];
- }
+ targetURL,
+ // response callback
+ function (backendResponse) {
+ response["status"] = backendResponse["status"];
+ response["content"] = backendResponse["responseText"];
+ }
);
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json
index ad95aa01d6..cf19f5ec5b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/conf/config.json
@@ -70,17 +70,53 @@
"copyrightSuffix" : " All Rights Reserved."
},
"scopes" : [
- "license-add", "license-view", "device-view",
- "device-info", "device-list", "device-view-own", "device-modify", "device-search",
- "operation-install", "operation-view", "operation-modify", "operation-uninstall",
- "group-add", "group-share", "group-modify", "group-view", "group-remove",
- "certificate-modify", "certificate-view",
- "configuration-view", "configuration-modify",
- "policy-view", "policy-modify",
- "device-notification-view", "device-notification-modify",
- "feature-view",
- "roles-view", "roles-modify", "roles-remove", "roles-add",
- "user-password-reset", "user-password-modify", "user-modify", "user-view", "user-invite", "user-remove", "user-add"
+ "user:manage",
+ "user:view",
+ "device-type:admin:view",
+ "device:view",
+ "notification:view",
+ "device:admin:view",
+ "application:manage",
+ "activity:view",
+ "user:admin:reset-password",
+ "policy:manage",
+ "policy:view",
+ "role:manage",
+ "role:view",
+ "configuration:view",
+ "configuration:modify",
+ "device:android:operation:reboot",
+ "device:android:operation:camera",
+ "device:android:operation:vpn",
+ "device:android:operation:lock",
+ "device:android:operation:ring",
+ "device:android:operation:update-app",
+ "device:android:operation:wipe",
+ "device:android:operation:encrypt",
+ "device:android:operation:blacklist-app",
+ "device:android:operation:applications",
+ "device:android:operation:enterprise-wipe",
+ "device:android:operation:info",
+ "device:android:operation:wifi",
+ "device:android:operation:uninstall-app",
+ "device:android:operation:change-lock",
+ "device:android:operation:notification",
+ "device:android:operation:upgrade",
+ "device:android:operation:unlock",
+ "device:android:operation:mute",
+ "device:android:operation:location",
+ "device:android:operation:webclip",
+ "device:android:operation:clear-password",
+ "device:android:operation:password-policy",
+ "device:android:operation:install-app",
+ "device:android:event:write",
+ "device:android:event:read",
+ "device:android:enroll",
+ "configuration:manage",
+ "configuration:view",
+ "device:android:enroll",
+ "certificate:view",
+ "certificate:manage"
],
"isOAuthEnabled" : true,
"backendRestEndpoints" : {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js
index 720cbc4629..8e885cd00b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/business-controllers/user.js
@@ -218,7 +218,8 @@ var userModule = function () {
}
try {
utility.startTenantFlow(carbonUser);
- var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/roles";
+ var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
+ "/roles?offset=0&limit=100";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content).roles;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js
index 6731dbd23a..f81849fe3b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/conf-reader/main.js
@@ -37,12 +37,6 @@ var conf = function () {
return value;
}
);
- if (conf.generalConfig.host) {
- //TODO: Move enrollment URL into app-conf.json
- var enrollmentHost = conf.generalConfig.host.replace(/https:\/\/localhost(:\d+)?/, conf.httpsURL).replace(
- /http:\/\/localhost(:\d+)?/, conf.httpURL);
- conf.enrollmentUrl = enrollmentHost + conf.enrollmentDir;
- }
application.put("CONF", conf);
}
return conf;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js
index f1ebedd948..38a3075064 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/constants.js
@@ -83,3 +83,4 @@ var HTTP_CONFLICT = 409;
var HTTP_CREATED = 201;
var CACHED_CREDENTIALS = "tenantBasedCredentials";
+var ALLOWED_SCOPES = "scopes";
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js
index 180438518f..ba7827173b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handler-utils.js
@@ -172,10 +172,11 @@ var utils = function () {
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
- var tokenPair = {};
- tokenPair["accessToken"] = responsePayload["access_token"];
- tokenPair["refreshToken"] = responsePayload["refresh_token"];
- return tokenPair;
+ var tokenData = {};
+ tokenData["accessToken"] = responsePayload["access_token"];
+ tokenData["refreshToken"] = responsePayload["refresh_token"];
+ tokenData["scopes"] = responsePayload["scope"];
+ return tokenData;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairByPasswordGrantType(a, b, c, d)");
@@ -224,10 +225,11 @@ var utils = function () {
if (xhr["status"] == 200 && xhr["responseText"]) {
var responsePayload = parse(xhr["responseText"]);
- var tokenPair = {};
- tokenPair["accessToken"] = responsePayload["access_token"];
- tokenPair["refreshToken"] = responsePayload["refresh_token"];
- return tokenPair;
+ var tokenData = {};
+ tokenData["accessToken"] = responsePayload["access_token"];
+ tokenData["refreshToken"] = responsePayload["refresh_token"];
+ tokenData["scopes"] = responsePayload["scope"];
+ return tokenData;
} else {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving access token " +
"by password grant type - getTokenPairBySAMLGrantType(x, y, z)");
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js
index af8a7e6674..fc1016eb85 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-handlers.js
@@ -45,23 +45,30 @@ var handlers = function () {
"password grant type. Encoded client credentials are " +
"missing - setupTokenPairByPasswordGrantType(x, y)");
} else {
- var tokenPair;
+ var tokenData;
// tokenPair will include current access token as well as current refresh token
var arrayOfScopes = devicemgtProps["scopes"];
var stringOfScopes = "";
arrayOfScopes.forEach(function (entry) {
stringOfScopes += entry + " ";
});
- tokenPair = tokenUtil.
+ tokenData = tokenUtil.
getTokenPairByPasswordGrantType(username,
encodeURIComponent(password), encodedClientAppCredentials, stringOfScopes);
- if (!tokenPair) {
+ if (!tokenData) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up " +
"token pair by password grant type. Error in token " +
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
} else {
- // setting up access token pair into session context as a string
+ var tokenPair = {};
+ tokenPair["accessToken"] = tokenData["accessToken"];
+ tokenPair["refreshToken"] = tokenData["refreshToken"];
+ // setting up token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
+
+ var scopes = tokenData.scopes.split(" ");
+ // adding allowed scopes to the session
+ session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
@@ -80,17 +87,24 @@ var handlers = function () {
"by saml grant type. Encoded client credentials are " +
"missing - setupTokenPairByPasswordGrantType(x, y)");
} else {
- var tokenPair;
+ var tokenData;
// accessTokenPair will include current access token as well as current refresh token
- tokenPair = tokenUtil.
+ tokenData = tokenUtil.
getTokenPairBySAMLGrantType(samlToken, encodedClientAppCredentials, "PRODUCTION");
- if (!tokenPair) {
+ if (!tokenData) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up token " +
"pair by password grant type. Error in token " +
"retrieval - setupTokenPairByPasswordGrantType(x, y)");
} else {
+ var tokenPair = {};
+ tokenPair["accessToken"] = tokenData["accessToken"];
+ tokenPair["refreshToken"] = tokenData["refreshToken"];
// setting up access token pair into session context as a string
session.put(constants["TOKEN_PAIR"], stringify(tokenPair));
+
+ var scopes = tokenData.scopes.split(" ");
+ // adding allowed scopes to the session
+ session.put(constants["ALLOWED_SCOPES"], scopes);
}
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs
index c6519777db..9d7f4445bd 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.hbs
@@ -2,20 +2,21 @@
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
- Version 2.0 (the "License"); you may not use this file except
- in compliance with the License.
- You may obtain a copy of the License at
+ Version 2.0 (the "License"); you may not use this file
+ except in compliance with the License. You may
+ obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
-{{unit "cdmf.unit.ui.title" pageTitle="Policy Management"}}
+
+{{unit "cdmf.unit.ui.title" pageTitle="Policy Management | Edit Policy"}}
{{#zone "breadcrumbs"}}
@@ -24,6 +25,7 @@
+
Policies
@@ -36,5 +38,6 @@
{{/zone}}
{{#zone "content"}}
- {{unit deviceTypePolicyEdit}}
+ {{unit "cdmf.unit.device.operation-mod"}}
+ {{unit "cdmf.unit.policy.edit"}}
{{/zone}}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js
index e39d8b9316..2bed273c68 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.js
@@ -16,8 +16,8 @@
* under the License.
*/
-function onRequest(context) {
- var utility = require("/app/modules/utility.js").utility;
- var deviceType = request.getParameter("type");
- return {"deviceTypePolicyEdit": utility.getTenantedDeviceUnitName(deviceType, "policy-edit")};
-}
+//function onRequest(context) {
+// var utility = require("/app/modules/utility.js").utility;
+// var deviceType = request.getParameter("type");
+// return {"deviceTypePolicyEdit": utility.getTenantedDeviceUnitName(deviceType, "policy-edit")};
+//}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json
index fcddd12965..f2122eb998 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.edit/edit.json
@@ -1,5 +1,5 @@
{
"version": "1.0.0",
- "uri": "/policy/edit",
+ "uri": "/policy/edit",
"layout": "cdmf.layout.default"
}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs
index f3113d2069..ad8f81f82a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.hbs
@@ -2,20 +2,21 @@
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
- Version 2.0 (the "License"); you may not use this file except
- in compliance with the License.
- You may obtain a copy of the License at
+ Version 2.0 (the "License"); you may not use this file
+ except in compliance with the License. You may
+ obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
+ http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- KIND, either express or implied. See the License for the
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
+ either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
-{{unit "cdmf.unit.ui.title" pageTitle="Policy Management"}}
+
+{{unit "cdmf.unit.ui.title" pageTitle="Policy Management | View Policy"}}
{{#zone "breadcrumbs"}}
@@ -24,6 +25,7 @@
+
Policies
@@ -36,5 +38,6 @@
{{/zone}}
{{#zone "content"}}
- {{unit deviceTypePolicyView}}
+ {{unit "cdmf.unit.device.operation-mod"}}
+ {{unit "cdmf.unit.policy.view"}}
{{/zone}}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js
index 58829242be..af7a8e700a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.js
@@ -16,8 +16,8 @@
* under the License.
*/
-function onRequest(context) {
- var utility = require("/app/modules/utility.js").utility;
- var deviceType = request.getParameter("type");
- return {"deviceTypePolicyView": utility.getTenantedDeviceUnitName(deviceType, "policy-view")};
-}
+//function onRequest(context) {
+// var utility = require("/app/modules/utility.js")["utility"];
+// var deviceType = request.getParameter("type");
+// return {"deviceTypePolicyView": utility.getTenantedDeviceUnitName(deviceType, "policy-view")};
+//}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json
index 77ddf10eaa..a4d19525f6 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.policy.view/view.json
@@ -1,5 +1,5 @@
{
"version": "1.0.0",
- "uri": "/policy/view",
+ "uri": "/policy/view",
"layout": "cdmf.layout.default"
}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js
index ffb86426bb..4528f4cba4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.user.view/view.js
@@ -20,7 +20,6 @@ function onRequest(context) {
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var username = request.getParameter("username");
var user = userModule.getUser(username)["content"];
- var userModule = require("/app/modules/user.js")["userModule"];
var userName = request.getParameter("username");
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js
index b2db97ca66..abd9c2da6d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/public/js/listing.js
@@ -1,54 +1,37 @@
/*
- * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
- * either express or implied. See the License for the
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
-var deviceMgtAPIsBasePath = "/api/device-mgt/v1.0";
-
-/**
- * Checks if provided input is valid against RegEx input.
- *
- * @param regExp Regular expression
- * @param inputString Input string to check
- * @returns {boolean} Returns true if input matches RegEx
- */
-function inputIsValid(regExp, inputString) {
- regExp = new RegExp(regExp);
- return regExp.test(inputString);
-}
-
-/**
- * Sorting function of users
- * listed on User Management page in WSO2 Devicemgt Console.
- */
$(function () {
var sortableElem = '.wr-sortable';
$(sortableElem).sortable({
beforeStop: function () {
- $(this).sortable('toArray');
+ var sortedIDs = $(this).sortable('toArray');
}
});
$(sortableElem).disableSelection();
});
+var apiBasePath = "/api/device-mgt/v1.0";
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
-//var isInit = true;
+var isInit = true;
$(".icon .text").res_text(0.2);
/*
@@ -90,11 +73,11 @@ function getSelectedUsernames() {
/**
* Following click function would execute
* when a user clicks on "Invite" link
- * on User Management page in WSO2 Devicemgt Console.
+ * on User Management page in WSO2 MDM Console.
*/
$("a.invite-user-link").click(function () {
var usernameList = getSelectedUsernames();
- var inviteUserAPI = deviceMgtAPIsBasePath + "/users/send-invitation";
+ var inviteUserAPI = apiBasePath + "/users/send-invitation";
if (usernameList.length == 0) {
$(modalPopupContent).html($("#errorUsers").html());
@@ -108,18 +91,13 @@ $("a.invite-user-link").click(function () {
invokerUtil.post(
inviteUserAPI,
usernameList,
- // success callback
- function (data, textStatus, jqXHR) {
- if (jqXHR.status == 200) {
- $(modalPopupContent).html($('#invite-user-success-content').html());
- $("a#invite-user-success-link").click(function () {
- hidePopup();
- });
- }
+ function () {
+ $(modalPopupContent).html($('#invite-user-success-content').html());
+ $("a#invite-user-success-link").click(function () {
+ hidePopup();
+ });
},
- // error callback
- function (jqXHR) {
- console.log("error in invite-user API, status code: " + jqXHR.status);
+ function () {
$(modalPopupContent).html($('#invite-user-error-content').html());
$("a#invite-user-error-link").click(function () {
hidePopup();
@@ -136,30 +114,31 @@ $("a.invite-user-link").click(function () {
/**
* Following click function would execute
* when a user clicks on "Remove" link
- * on User Listing page in WSO2 Devicemgt Console.
+ * on User Listing page in WSO2 MDM Console.
*/
-function removeUser(username) {
- var removeUserAPI = deviceMgtAPIsBasePath + "/users/" + username;
+function removeUser(uname, uid) {
+ var username = uname;
+ var userid = uid;
+ var removeUserAPI = apiBasePath + "/users/" + username;
$(modalPopupContent).html($('#remove-user-modal-content').html());
showPopup();
$("a#remove-user-yes-link").click(function () {
invokerUtil.delete(
removeUserAPI,
- // success callback
- function (data, textStatus, jqXHR) {
- if (jqXHR.status == 200) {
- // update modal-content with success message
- $(modalPopupContent).html($('#remove-user-success-content').html());
- $("a#remove-user-success-link").click(function () {
- hidePopup();
- location.reload();
- });
- }
+ function () {
+ $("#" + userid).remove();
+ // get new user-list-count
+ var newUserListCount = $(".user-list > span").length;
+ // update user-listing-status-msg with new user-count
+ $("#user-listing-status-msg").text("Total number of Users found : " + newUserListCount);
+ // update modal-content with success message
+ $(modalPopupContent).html($('#remove-user-success-content').html());
+ $("a#remove-user-success-link").click(function () {
+ hidePopup();
+ });
},
- // error callback
- function (jqXHR) {
- console.log("error in remove-user API, status code: " + jqXHR.status);
+ function () {
$(modalPopupContent).html($('#remove-user-error-content').html());
$("a#remove-user-error-link").click(function () {
hidePopup();
@@ -207,23 +186,19 @@ function resetPassword(uname) {
//resetPasswordFormData.username = user;
resetPasswordFormData.newPassword = unescape(confirmedPassword);
- var resetPasswordServiceURL = deviceMgtAPIsBasePath + "/admin/users/"+ user +"/credentials";
+ var resetPasswordServiceURL = apiBasePath + "/admin/users/"+ user +"/credentials";
invokerUtil.post(
resetPasswordServiceURL,
resetPasswordFormData,
- // success callback
- function (data, textStatus, jqXHR) {
+ function (data, textStatus, jqXHR) { // The success callback
if (jqXHR.status == 200) {
$(modalPopupContent).html($('#reset-password-success-content').html());
$("a#reset-password-success-link").click(function () {
hidePopup();
});
}
- },
- // error callback
- function (jqXHR) {
- console.log("error in reset-password API, status code: " + jqXHR.status);
+ }, function (jqXHR) { // The error callback
var payload = JSON.parse(jqXHR.responseText);
$(errorMsg).text(payload.message);
$(errorMsgWrapper).removeClass("hidden");
@@ -253,7 +228,7 @@ $("#search-btn").click(function () {
* when a user clicks on the list item
* initial mode and with out select mode.
*/
-function initiateViewOption() {
+function InitiateViewOption() {
if ($("#can-view").val()) {
$(location).attr('href', $(this).data("url"));
} else {
@@ -262,137 +237,172 @@ function initiateViewOption() {
}
}
-function loadUsers() {
- var loadingContentIcon = "#loading-content";
- $(loadingContentIcon).show();
+function loadUsers(searchParam) {
+
+
+ $("#loading-content").show();
- var dataFilter = function (data) {
+
+ var dataFilter = function(data){
data = JSON.parse(data);
var objects = [];
- $(data.users).each(
- function (index) {
- objects.push(
- {
- username: data.users[index].username,
- firstname: data.users[index].firstname ? data.users[index].firstname: '' ,
- lastname: data.users[index].lastname ? data.users[index].lastname : '',
- emailAddress : data.users[index].emailAddress ? data.users[index].emailAddress: '',
- DT_RowId : "user-" + data.users[index].username
- }
- )
- }
- );
+ $(data.users).each(function( index ) {
+ objects.push({
+ filter: data.users[index].username,
+ firstname: data.users[index].firstname ? data.users[index].firstname: '' ,
+ lastname: data.users[index].lastname ? data.users[index].lastname : '',
+ emailAddress : data.users[index].emailAddress ? data.users[index].emailAddress: '',
+ DT_RowId : "role-" + data.users[index].username})
+ });
- var json = {
+ json = {
"recordsTotal": data.count,
"recordsFiltered": data.count,
"data": objects
};
- return JSON.stringify(json);
- };
+ return JSON.stringify( json );
+ }
- var fnCreatedRow = function(nRow, aData, iDataIndex) {
- console.log(JSON.stringify(aData));
+ var fnCreatedRow = function( nRow, aData, iDataIndex ) {
$(nRow).attr('data-type', 'selectable');
$(nRow).attr('data-username', aData["username"]);
- };
+ }
var columns = [
{
class: "remove-padding icon-only content-fill",
data: null,
- defaultContent:
- '
' +
- '' +
- '
'
+ defaultContent: '
'
},
{
class: "fade-edge",
data: null,
- render: function (data, type, row, meta) {
+ render: function ( data, type, row, meta ) {
return '
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js
index df93724633..dab14ec3a4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.users/users.js
@@ -28,7 +28,7 @@ function onRequest(context) {
});
var page = {};
- var userModule = require("/app/modules/user.js")["userModule"];
+ var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var deviceMgtProps = require("/app/modules/conf-reader/main.js")["conf"];
page["adminUser"] = deviceMgtProps["adminUser"];
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js
index 1ac4db312d..8b6c1e3b71 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.data-tables-extended/public/js/dataTables.extended.serversidepaging.js
@@ -29,33 +29,41 @@
* For ex: $(this) means jQuery(this) and S.fn.x means jQuery.fn.x
*/
- $.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter,
- columns, fnCreatedRow, fnDrawCallback) {
+$.fn.datatables_extended_serverside_paging = function (settings , url, dataFilter,
+ columns, fnCreatedRow, fnDrawCallback, options) {
var elem = $(this);
// EMM related function
- if (initiateViewOption) {
- $(".viewEnabledIcon").bind("click", initiateViewOption);
+ if (InitiateViewOption) {
+ $(".viewEnabledIcon").bind("click", InitiateViewOption);
}
//--- End of EMM related codes
$(elem).DataTable(
$.extend({},{
serverSide: true,
+ processing: false,
+ searching: true,
+ ordering: false,
+ filter: false,
bSortCellsTop: true,
ajax : {
url: "/emm/api/data-tables/invoker",
data : function (params) {
- var filter = "";
var i;
+ var searchParams = {};
for (i = 0; i < params.columns.length; i++) {
- // console.log(i);
- filter += "&" + params.columns[i].data + "=" + params.columns[i].search.value;
+ searchParams[params.columns[i].data] = encodeURIComponent(params.columns[i].search.value);
}
- // console.log(filter);
+ if(options) {
+ searchParams[options.searchKey] = encodeURIComponent(params.search.value);
+ }
+ params.filter = JSON.stringify(searchParams);
params.offset = params.start;
params.limit = params.length;
- params.filter = filter;
+ // if(params.search.value){
+ // params.filter = params.search.value;
+ // }
params.url = url;
},
dataFilter: dataFilter
@@ -64,15 +72,15 @@
responsive: false,
autoWidth: false,
dom:'<"dataTablesTop"' +
- 'f' +
- '<"dataTables_toolbar">' +
- '>' +
- 'rt' +
- '<"dataTablesBottom"' +
- 'lip' +
- '>',
+ 'f' +
+ '<"dataTables_toolbar">' +
+ '>' +
+ 'rt' +
+ '<"dataTablesBottom"' +
+ 'lip' +
+ '>',
language: {
- searchPlaceholder: 'Search by Role name',
+ searchPlaceholder: options.placeholder,
search: ''
},
fnCreatedRow: fnCreatedRow,
@@ -216,7 +224,7 @@
$(button).addClass("active").html('Select');
$(button).parent().next().children().addClass("disabled");
// EMM related function
- $(".viewEnabledIcon").bind("click", initiateViewOption);
+ $(".viewEnabledIcon").bind("click", InitiateViewOption);
//--- End of EMM related codes
}
});
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs
index 3e59c7fe39..adfadb50ab 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.hbs
@@ -1,306 +1,85 @@
-{{#zone "content"}}
-
-
-
-
-
-
-
1
-
Select a platform
-
-
-
-
-
-
2
-
Configure profile
-
-
-
-
-
-
3
-
Assign to groups
-
-
-
-
-
-
4
-
Publish to devices
-
-
-
-
+{{!
+ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
-
-
-
Policy creation is successful.
- Please click "Add Another Policy", if you wish to add another policy or click
- "View policy list" to complete the process and go back to the policy list.
-
-
-
-
-
-
-
- Add another policy
-
-
-
+ 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
-
-
+ 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.
+}}
+{{#zone "content"}}
+
-{{/zone}}
-{{#zone "bottomJs"}}
-
-
-
-
-
-
- {{js "js/create.js"}}
-{{/zone}}
-
+{{/zone}}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js
index 1dc93a5984..28142c13eb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.create/create.js
@@ -17,46 +17,32 @@
*/
function onRequest(context) {
-// var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType";
-// var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label";
-//
-// var utility = require("/app/modules/utility.js").utility;
-// var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
-//
-// var types = {};
-// types["types"] = [];
-// var typesListResponse = userModule.getPlatforms();
-// if (typesListResponse["status"] == "success") {
-// for (var type in typesListResponse["content"]) {
-// var content = {};
-// var deviceType = typesListResponse["content"]["deviceTypes"][type];
-// content["name"] = deviceType;
-// var configs = utility.getDeviceTypeConfig(deviceType);
-// var deviceTypeLabel = deviceType;
-// if (configs && configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) {
-// deviceTypeLabel = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY];
-// }
-// var policyWizard = new File("/app/units/" + utility.getTenantedDeviceUnitName(deviceType, "policy-wizard"));
-// if(policyWizard.isExists()){
-// content["icon"] = utility.getDeviceThumb(deviceType);
-// content["label"] = deviceTypeLabel;
-// types["types"].push(content);
-// }
-// }
-// }
-// return types;
+ var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType";
+ var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label";
- //var log = new Log("units/policy-create/policy-create.js");
+ var utility = require("/app/modules/utility.js").utility;
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
- var result = userModule.getRolesByUserStore();
- if (result["status"] == "success") {
- context["roles"] = result["content"];
+ var types = {};
+ types["types"] = [];
+ var typesListResponse = userModule.getPlatforms();
+ if (typesListResponse["status"] == "success") {
+ for (var type in typesListResponse["content"]) {
+ var content = {};
+ var deviceType = typesListResponse["content"]["deviceTypes"][type];
+ content["name"] = deviceType;
+ var configs = utility.getDeviceTypeConfig(deviceType);
+ var deviceTypeLabel = deviceType;
+ if (configs && configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY]) {
+ deviceTypeLabel = configs[DTYPE_CONF_DEVICE_TYPE_KEY][DTYPE_CONF_DEVICE_TYPE_LABEL_KEY];
+ }
+ var policyWizard = new File("/app/units/" + utility.getTenantedDeviceUnitName(deviceType, "policy-wizard"));
+ if(policyWizard.isExists()){
+ content["icon"] = utility.getDeviceThumb(deviceType);
+ content["label"] = deviceTypeLabel;
+ types["types"].push(content);
+ }
+ }
}
-
- result = userModule.getPlatforms();
- if (result["status"] == "success") {
- context["deviceTypes"] = result["content"]["deviceTypes"];
- }
- return context;
+ return types;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs
new file mode 100644
index 0000000000..fbeb8f8eb3
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.policy.edit/edit.hbs
@@ -0,0 +1,233 @@
+{{#zone "content"}}
+
+
+
+
+
+
1
Edit current profile
+
+
+
+
2
Edit assignment groups
+
+
+
+
3
Republish to devices
+
+
+
+
+
+
+
Policy is successfully re-configured.
+ Please click "Add Another Policy", if you wish to add another policy or click
+ "View policy list" to complete the process and go back to the policy list.
+
+
+
+
+
+
+
+ Add another policy
+
+