Merge pull request #381 from ayyoob/st2

Fixed the issues related to apimgt integration
revert-70aa11f8
Ruwan 8 years ago committed by GitHub
commit 9687d554a6

@ -18,7 +18,6 @@
package org.wso2.carbon.apimgt.application.extension.api; 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 org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile;
import javax.ws.rs.*; import javax.ws.rs.*;
@ -28,9 +27,7 @@ import javax.ws.rs.core.Response;
/** /**
* This is the application registration service that exposed for apimApplicationRegistration * 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 { public interface ApiApplicationRegistrationService {
/** /**

@ -30,6 +30,7 @@ import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder; import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.governance.lcm.util.CommonUtil; import org.wso2.carbon.governance.lcm.util.CommonUtil;
@ -78,15 +79,17 @@ public class APIPublisherServiceImpl implements APIPublisherService {
+ api.getId().getVersion() + "'"); + api.getId().getVersion() + "'");
} }
} else { } else {
if (provider.getAPI(api.getId()).getStatus() == APIStatus.CREATED) { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION); if (provider.getAPI(api.getId()).getStatus() == APIStatus.CREATED) {
} provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
api.setStatus(APIStatus.PUBLISHED); }
provider.updateAPI(api); api.setStatus(APIStatus.PUBLISHED);
if (log.isDebugEnabled()) { provider.updateAPI(api);
log.debug("An API already exists with the name '" + api.getId().getApiName() + if (log.isDebugEnabled()) {
"', context '" + api.getContext() + "' and version '" log.debug("An API already exists with the name '" + api.getId().getApiName() +
+ api.getId().getVersion() + "'. Thus, the API config is updated"); "', context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'. Thus, the API config is updated");
}
} }
} }
provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api)); provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api));

@ -32,6 +32,7 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(APIPublisherStartupHandler.class); private static final Log log = LogFactory.getLog(APIPublisherStartupHandler.class);
private static int retryTime = 2000; private static int retryTime = 2000;
private static final int CONNECTION_RETRY_FACTOR = 2; private static final int CONNECTION_RETRY_FACTOR = 2;
private static final int MAX_RETRY_COUNT = 5;
private static Stack<API> failedAPIsStack = new Stack<>(); private static Stack<API> failedAPIsStack = new Stack<>();
private static Stack<API> currentAPIsStack; private static Stack<API> currentAPIsStack;
@ -44,33 +45,49 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
@Override @Override
public void completedServerStartup() { public void completedServerStartup() {
// APIPublisherDataHolder.getInstance().setServerStarted(true); APIPublisherDataHolder.getInstance().setServerStarted(true);
// currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis(); currentAPIsStack = APIPublisherDataHolder.getInstance().getUnpublishedApis();
// Thread t = new Thread(new Runnable() { Thread t = new Thread(new Runnable() {
// @Override @Override
// public void run() { public void run() {
// if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
// log.debug("Server has just started, hence started publishing unpublished APIs"); log.debug("Server has just started, hence started publishing unpublished APIs");
// log.debug("Total number of unpublished APIs: " log.debug("Total number of unpublished APIs: "
// + APIPublisherDataHolder.getInstance().getUnpublishedApis().size()); + APIPublisherDataHolder.getInstance().getUnpublishedApis().size());
// } }
// publisher = APIPublisherDataHolder.getInstance().getApiPublisherService(); publisher = APIPublisherDataHolder.getInstance().getApiPublisherService();
// while (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty()) { int retryCount = 0;
// try { while (retryCount < MAX_RETRY_COUNT && (!failedAPIsStack.isEmpty() || !currentAPIsStack.isEmpty())) {
// retryTime = retryTime * CONNECTION_RETRY_FACTOR; try {
// Thread.sleep(retryTime); retryTime = retryTime * CONNECTION_RETRY_FACTOR;
// } catch (InterruptedException te) { Thread.sleep(retryTime);
// log.error("Error occurred while sleeping", te); } catch (InterruptedException te) {
// } //do nothing.
// if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) { }
// publishAPIs(currentAPIsStack, failedAPIsStack); Stack<API> failedApis;
// } else { if (!APIPublisherDataHolder.getInstance().getUnpublishedApis().isEmpty()) {
// publishAPIs(failedAPIsStack, currentAPIsStack); publishAPIs(currentAPIsStack, failedAPIsStack);
// } failedApis = failedAPIsStack;
// } } else {
// } publishAPIs(failedAPIsStack, currentAPIsStack);
// }); failedApis = currentAPIsStack;
// t.start(); }
retryCount++;
if (retryCount == MAX_RETRY_COUNT && !failedApis.isEmpty()) {
StringBuilder error = new StringBuilder();
error.append("Error occurred while publishing API ['");
while (!failedApis.isEmpty()) {
API api = failedApis.pop();
error.append(api.getId().getApiName() + ",");
}
error.append("']");
log.error(error.toString());
}
}
}
});
t.start();
} }
private void publishAPIs(Stack<API> apis, Stack<API> failedStack) { private void publishAPIs(Stack<API> apis, Stack<API> failedStack) {
@ -79,7 +96,6 @@ public class APIPublisherStartupHandler implements ServerStartupObserver {
try { try {
publisher.publishAPI(api); publisher.publishAPI(api);
} catch (Exception e) { } catch (Exception e) {
log.error("Error occurred while publishing API '" + api.getId().getApiName() + "'");
failedStack.push(api); failedStack.push(api);
} }
} }

@ -24,15 +24,12 @@ import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource; 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.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.core.util.Utils; 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 javax.servlet.ServletContext;
import java.util.*; import java.util.*;
@ -117,8 +114,6 @@ public class APIPublisherUtil {
// adding scopes to the api // adding scopes to the api
Set<URITemplate> uriTemplates = config.getUriTemplates(); Set<URITemplate> uriTemplates = config.getUriTemplates();
Map<String, Scope> apiScopes = new HashMap<>(); Map<String, Scope> apiScopes = new HashMap<>();
Scope existingScope;
String existingPermissions;
if (uriTemplates != null) { if (uriTemplates != null) {
// this creates distinct scopes list // this creates distinct scopes list
for (URITemplate template : uriTemplates) { for (URITemplate template : uriTemplates) {
@ -130,13 +125,6 @@ public class APIPublisherUtil {
} }
} }
Set<Scope> scopes = new HashSet<>(apiScopes.values()); Set<Scope> 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 // set current scopes to API
api.setScopes(scopes); api.setScopes(scopes);
@ -152,6 +140,7 @@ public class APIPublisherUtil {
} }
api.setUriTemplates(uriTemplates); api.setUriTemplates(uriTemplates);
} }
api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
return api; return api;
} }
@ -324,34 +313,4 @@ public class APIPublisherUtil {
return apiConfig; return apiConfig;
} }
/**
* 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<Scope> 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);
}
}
}
} }

@ -18,16 +18,7 @@
package org.wso2.carbon.apimgt.webapp.publisher; 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.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.XMLConstants;
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilder;
@ -40,10 +31,6 @@ import java.io.File;
*/ */
public class WebappPublisherUtil { 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 { public static Document convertToDocument(File file) throws WebappPublisherConfigurationFailedException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); factory.setNamespaceAware(true);
@ -57,32 +44,4 @@ 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;
}
} }

@ -40,6 +40,7 @@ public class WebappPublisherConfig {
private String host; private String host;
private boolean isPublished; private boolean isPublished;
private boolean isEnabledUpdateApi;
private Profiles profiles; private Profiles profiles;
private static WebappPublisherConfig config; private static WebappPublisherConfig config;
@ -77,6 +78,15 @@ public class WebappPublisherConfig {
return profiles; return profiles;
} }
@XmlElement(name = "EnabledUpdateApi", required = true)
public boolean isEnabledUpdateApi() {
return isEnabledUpdateApi;
}
public void setEnabledUpdateApi(boolean isEnabledUpdateApi) {
this.isEnabledUpdateApi = isEnabledUpdateApi;
}
public void setPublished(boolean published) { public void setPublished(boolean published) {
isPublished = published; isPublished = published;
} }

@ -49,72 +49,72 @@ public class APIPublisherLifecycleListener implements LifecycleListener {
@Override @Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) { public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
// if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance() if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType()) && WebappPublisherConfig.getInstance()
// .isPublished()) { .isPublished()) {
// StandardContext context = (StandardContext) lifecycleEvent.getLifecycle(); StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
// ServletContext servletContext = context.getServletContext(); ServletContext servletContext = context.getServletContext();
// String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED); String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
// boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param); boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
//
// String profile = System.getProperty(PROPERTY_PROFILE); String profile = System.getProperty(PROPERTY_PROFILE);
//
// if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase()) if (WebappPublisherConfig.getInstance().getProfiles().getProfile().contains(profile.toLowerCase())
// && isManagedApi) { && isManagedApi) {
// try { try {
// AnnotationProcessor annotationProcessor = new AnnotationProcessor(context); AnnotationProcessor annotationProcessor = new AnnotationProcessor(context);
// Set<String> annotatedAPIClasses = annotationProcessor. Set<String> annotatedAPIClasses = annotationProcessor.
// scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName()); scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
//
// List<APIResourceConfiguration> apiDefinitions = annotationProcessor.extractAPIInfo(servletContext, List<APIResourceConfiguration> apiDefinitions = annotationProcessor.extractAPIInfo(servletContext,
// annotatedAPIClasses); annotatedAPIClasses);
//
// for (APIResourceConfiguration apiDefinition : apiDefinitions) { for (APIResourceConfiguration apiDefinition : apiDefinitions) {
//
// APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition); APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
//
// try { try {
// int tenantId = APIPublisherDataHolder.getInstance().getTenantManager(). int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().
// getTenantId(apiConfig.getTenantDomain()); getTenantId(apiConfig.getTenantDomain());
//
// boolean isTenantActive = APIPublisherDataHolder.getInstance(). boolean isTenantActive = APIPublisherDataHolder.getInstance().
// getTenantManager().isTenantActive(tenantId); getTenantManager().isTenantActive(tenantId);
//
// if (isTenantActive) { if (isTenantActive) {
// apiConfig.init(); apiConfig.init();
// API api = APIPublisherUtil.getAPI(apiConfig); API api = APIPublisherUtil.getAPI(apiConfig);
// boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted(); boolean isServerStarted = APIPublisherDataHolder.getInstance().isServerStarted();
// if (isServerStarted) { if (isServerStarted) {
// APIPublisherService apiPublisherService = APIPublisherService apiPublisherService =
// APIPublisherDataHolder.getInstance().getApiPublisherService(); APIPublisherDataHolder.getInstance().getApiPublisherService();
// if (apiPublisherService == null) { if (apiPublisherService == null) {
// throw new IllegalStateException( throw new IllegalStateException(
// "API Publisher service is not initialized properly"); "API Publisher service is not initialized properly");
// } }
// apiPublisherService.publishAPI(api); apiPublisherService.publishAPI(api);
// } else { } else {
// if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
// log.debug("Server has not started yet. Hence adding API '" + log.debug("Server has not started yet. Hence adding API '" +
// api.getId().getApiName() + "' to the queue"); api.getId().getApiName() + "' to the queue");
// } }
// APIPublisherDataHolder.getInstance().getUnpublishedApis().push(api); APIPublisherDataHolder.getInstance().getUnpublishedApis().push(api);
// } }
// } else { } else {
// log.error("No tenant [" + apiConfig.getTenantDomain() + "] " + log.error("No tenant [" + apiConfig.getTenantDomain() + "] " +
// "found when publishing the Web app"); "found when publishing the Web app");
// } }
// } catch (Throwable e) { } catch (Throwable e) {
// log.error("Error occurred while publishing API '" + apiConfig.getName() + log.error("Error occurred while publishing API '" + apiConfig.getName() +
// "' with the context '" + apiConfig.getContext() + "' with the context '" + apiConfig.getContext() +
// "' and version '" + apiConfig.getVersion() + "'", e); "' and version '" + apiConfig.getVersion() + "'", e);
// } }
// } }
// } catch (IOException e) { } catch (IOException e) {
// log.error("Error encountered while discovering annotated classes", e); log.error("Error encountered while discovering annotated classes", e);
// } catch (ClassNotFoundException e) { } catch (ClassNotFoundException e) {
// log.error("Error while scanning class for annotations", e); log.error("Error while scanning class for annotations", e);
// } }
// } }
// } }
} }
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes //TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes

@ -33,7 +33,7 @@ import javax.ws.rs.core.Response;
/** /**
* Activity related REST-API implementation. * Activity related REST-API implementation.
*/ */
@API(name = "Activity Info Provider", version = "1.0.0", context = "/api/device-mgt/v1.0/activities", tags = {"devicemgt_admin"}) @API(name = "ActivityInfoProvider", version = "1.0.0", context = "/api/device-mgt/v1.0/activities", tags = {"device_management"})
@Path("/activities") @Path("/activities")
@Api(value = "Activity Info Provider", description = "Activity related information manipulation. For example operation details " + @Api(value = "Activity Info Provider", description = "Activity related information manipulation. For example operation details " +

@ -31,7 +31,7 @@ import javax.ws.rs.core.Response;
/** /**
* General Tenant Configuration REST-API. * General Tenant Configuration REST-API.
*/ */
@API(name = "Configuration Management", version = "1.0.0", context = "/api/device-mgt/v1.0/configuration", tags = {"devicemgt_admin"}) @API(name = "ConfigurationManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/configuration", tags = {"device_management"})
@Path("/configuration") @Path("/configuration")
@Api(value = "Configuration Management", description = "The general platform configuration management capabilities are exposed " + @Api(value = "Configuration Management", description = "The general platform configuration management capabilities are exposed " +

@ -30,8 +30,8 @@ import javax.ws.rs.core.Response;
/** /**
* Device Analytics Dashboard related REST-APIs. This can be used to obtain device related analytics. * Device Analytics Dashboard related REST-APIs. This can be used to obtain device related analytics.
*/ */
@API(name = "Device Analytics Dashboard", @API(name = "DeviceAnalyticsDashboard",
version = "1.0.0", context = "/api/device-mgt/v1.0/dashboard", tags = {"devicemgt_admin"}) version = "1.0.0", context = "/api/device-mgt/v1.0/dashboard", tags = {"device_management"})
@Path("/dashboard") @Path("/dashboard")
@Api(value = "Device Analytics Dashboard", @Api(value = "Device Analytics Dashboard",

@ -39,7 +39,7 @@ import javax.ws.rs.core.Response;
/** /**
* Device related REST-API. This can be used to manipulated device related details. * Device related REST-API. This can be used to manipulated device related details.
*/ */
@API(name = "Device Management", version = "1.0.0", context = "/api/device-mgt/v1.0/devices", tags = {"devicemgt_admin"}) @API(name = "DeviceManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/devices", tags = {"device_management"})
@Path("/devices") @Path("/devices")
@Api(value = "Device Management", description = "This API carries all device management related operations " + @Api(value = "Device Management", description = "This API carries all device management related operations " +

@ -39,8 +39,8 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "Device Type Management", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/device-types", @API(name = "DeviceTypeManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/device-types",
tags = {"devicemgt_admin"}) tags = {"device_management"})
@Path("/device-types") @Path("/device-types")
@Api(value = "Device Type Management", description = "This API corresponds to all tasks related to device " + @Api(value = "Device Type Management", description = "This API corresponds to all tasks related to device " +

@ -35,7 +35,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "Group Management", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"devicemgt_admin"}) @API(name = "GroupManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"device_management"})
@Path("/groups") @Path("/groups")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)

@ -35,8 +35,8 @@ import javax.ws.rs.core.Response;
/** /**
* Notifications related REST-API. * Notifications related REST-API.
*/ */
@API(name = "Device Notification Management", version = "1.0.0", context = "/api/device-mgt/v1.0/notifications", @API(name = "DeviceNotificationManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/notifications",
tags = {"devicemgt_admin"}) tags = {"device_management"})
@Api(value = "Device Notification Management", description = "Device notification related operations can be found here.") @Api(value = "Device Notification Management", description = "Device notification related operations can be found here.")
@Path("/notifications") @Path("/notifications")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)

@ -37,8 +37,8 @@ import java.util.List;
* Policy related REST-API. This can be used to manipulated policies and associate them with devices, users, roles, * Policy related REST-API. This can be used to manipulated policies and associate them with devices, users, roles,
* groups. * groups.
*/ */
@API(name = "Device Policy Management", version = "1.0.0", context = "/api/device-mgt/v1.0/policies", @API(name = "DevicePolicyManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/policies",
tags = {"devicemgt_admin"}) tags = {"device_management"})
@Api(value = "Device Policy Management", description = "This API carries all the necessary functionalities " + @Api(value = "Device Policy Management", description = "This API carries all the necessary functionalities " +
"around device policy management") "around device policy management")

@ -32,7 +32,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@API(name = "Role Management", version = "1.0.0", context = "/api/device-mgt/v1.0/roles", tags = {"devicemgt_admin"}) @API(name = "RoleManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/roles", tags = {"device_management"})
@Path("/roles") @Path("/roles")
@Api(value = "Role Management", description = "Role management related operations can be found here.") @Api(value = "Role Management", description = "Role management related operations can be found here.")

@ -29,7 +29,7 @@ import javax.ws.rs.core.Response;
import java.util.List; import java.util.List;
@API(name = "User Management", version = "1.0.0", context = "/api/device-mgt/v1.0/users", tags = {"devicemgt_admin"}) @API(name = "UserManagement", version = "1.0.0", context = "/api/device-mgt/v1.0/users", tags = {"device_management"})
@Path("/users") @Path("/users")
@Api(value = "User Management", description = "User management related operations can be found here.") @Api(value = "User Management", description = "User management related operations can be found here.")

@ -33,7 +33,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "Application Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/applications", tags = {"devicemgt_admin"}) @API(name = "ApplicationManagementAdmin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/applications", tags = {"device_management"})
@Path("/admin/applications") @Path("/admin/applications")
@Api(value = "Application Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "Application Management Administrative Service", description = "This an API intended to be used by " +

@ -29,8 +29,8 @@ import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "Device Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/devices", @API(name = "DeviceManagementAdmin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/devices",
tags = {"devicemgt_admin"}) tags = {"device_management"})
@Path("/admin/devices") @Path("/admin/devices")
@Api(value = "Device Management Administrative Service", description = "This an API intended to be used by " + @Api(value = "Device Management Administrative Service", description = "This an API intended to be used by " +
"'internal' components to log in as an admin user and do a selected number of operations. " + "'internal' components to log in as an admin user and do a selected number of operations. " +

@ -37,7 +37,7 @@ import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "Group Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/groups", tags = {"devicemgt_admin"}) @API(name = "GroupManagementAdmin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/groups", tags = {"device_management"})
@Path("/admin/groups") @Path("/admin/groups")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)

@ -30,7 +30,7 @@ import javax.ws.rs.*;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@API(name = "User Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/users", tags = {"devicemgt_admin"}) @API(name = "UserManagementAdmin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/users", tags = {"device_management"})
@Path("/admin/users") @Path("/admin/users")
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)

@ -57,14 +57,6 @@ public class DeviceManagementDataHolder {
private EmailSenderService emailSenderService; private EmailSenderService emailSenderService;
private PushNotificationProviderRepository pushNotificationProviderRepository; private PushNotificationProviderRepository pushNotificationProviderRepository;
public APIManagerConfiguration getApiManagerConfiguration() {
return apiManagerConfiguration;
}
public void setApiManagerConfiguration(APIManagerConfiguration apiManagerConfiguration) {
this.apiManagerConfiguration = apiManagerConfiguration;
}
private APIManagerConfiguration apiManagerConfiguration; private APIManagerConfiguration apiManagerConfiguration;
private DeviceManagementDataHolder() {} private DeviceManagementDataHolder() {}

@ -21,7 +21,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.impl.APIManagerConfiguration;
import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService; import org.wso2.carbon.apimgt.impl.APIManagerConfigurationService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
@ -33,7 +32,6 @@ 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.permission.mgt.PermissionManagerService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl; import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagerProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig; import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
@ -51,7 +49,6 @@ import org.wso2.carbon.device.mgt.core.operation.mgt.OperationManagerImpl;
import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory; import org.wso2.carbon.device.mgt.core.operation.mgt.dao.OperationManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionManagerServiceImpl; 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.push.notification.mgt.PushNotificationProviderRepository;
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.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
@ -61,10 +58,8 @@ import org.wso2.carbon.email.sender.core.service.EmailSenderService;
import org.wso2.carbon.ndatasource.core.DataSourceService; import org.wso2.carbon.ndatasource.core.DataSourceService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import java.io.File;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -120,10 +115,6 @@ public class DeviceManagementServiceComponent {
private static List<PluginInitializationListener> listeners = new ArrayList<>(); private static List<PluginInitializationListener> listeners = new ArrayList<>();
private static List<DeviceManagementService> deviceManagers = new ArrayList<>(); private static List<DeviceManagementService> deviceManagers = new ArrayList<>();
private static List<DeviceManagerStartupListener> startupListeners = new ArrayList<>(); private static List<DeviceManagerStartupListener> 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) { public static void registerPluginInitializationListener(PluginInitializationListener listener) {
synchronized (LOCK) { synchronized (LOCK) {
@ -157,18 +148,11 @@ public class DeviceManagementServiceComponent {
DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig(); DataSourceConfig dsConfig = config.getDeviceManagementConfigRepository().getDataSourceConfig();
APIManagerConfiguration apiManagerConfiguration = new APIManagerConfiguration();
apiManagerConfiguration.load(APIM_CONFIGURATION_PATH);
DeviceManagementDataHolder.getInstance().setApiManagerConfiguration(apiManagerConfiguration);
DeviceManagementDAOFactory.init(dsConfig); DeviceManagementDAOFactory.init(dsConfig);
GroupManagementDAOFactory.init(dsConfig); GroupManagementDAOFactory.init(dsConfig);
NotificationManagementDAOFactory.init(dsConfig); NotificationManagementDAOFactory.init(dsConfig);
OperationManagementDAOFactory.init(dsConfig); OperationManagementDAOFactory.init(dsConfig);
String apiManagerDataSource = apiManagerConfiguration.getFirstProperty(DATA_SOURCE_NAME);
ScopeManagementDAOFactory.init(apiManagerDataSource);
/* Initialize Operation Manager */ /* Initialize Operation Manager */
this.initOperationsManager(); this.initOperationsManager();

@ -1,173 +0,0 @@
/*
* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.core.scope.mgt;
import org.apache.commons.lang.StringUtils;
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<Scope> 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 void updateScopes(List<String> scopeKeys, String roleName) throws ScopeManagementException {
List<Scope> scopes = new ArrayList<>();
try {
List<Scope> allScopes = this.getAllScopes();
for (Scope scope : allScopes) {
for (String key : scopeKeys) {
if (scope.getKey().equals(key)) {
scope.setRoles(scope.getRoles() + "," + roleName);
scopes.add(scope);
}
}
}
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<Scope> getAllScopes() throws ScopeManagementException {
List<Scope> 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;
}
@Override
public List<Scope> getScopesOfRole(String roleName) throws ScopeManagementException {
if (roleName == null || roleName.isEmpty()) {
throw new ScopeManagementException("Role name is null or empty");
}
List<Scope> filteredScopes = new ArrayList<>();
try {
ScopeManagementDAOFactory.openConnection();
List<Scope> allScopes = scopeManagementDAO.getScopesHavingRole(roleName);
String roles[];
for (Scope scope : allScopes) {
roles = scope.getRoles().split(",");
for (String role : roles) {
if (roleName.equals(role.trim())) {
filteredScopes.add(scope);
}
}
}
} catch (SQLException e) {
throw new ScopeManagementException("SQL error occurred while retrieving scopes of role from database.", e);
} catch (ScopeManagementDAOException e) {
throw new ScopeManagementException("Error occurred while retrieving scopes of role from database.", e);
} finally {
ScopeManagementDAOFactory.closeConnection();
}
return filteredScopes;
}
@Override
public void removeScopes(String roleName) throws ScopeManagementException {
List<Scope> scopes = this.getScopesOfRole(roleName);
String roles[];
ArrayList<String> filteredRoles = new ArrayList<>();
for (Scope scope : scopes) {
roles = scope.getRoles().split(",");
for (String role : roles) {
if (!roleName.equals(role.trim())) {
filteredRoles.add(role);
}
}
scope.setRoles(StringUtils.join(filteredRoles, ","));
filteredRoles.clear();
}
this.updateScopes(scopes);
}
}

@ -1,64 +0,0 @@
/*
* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.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<Scope> scopes) throws ScopeManagementDAOException;
/**
* This method is used to retrieve all the scopes.
*
* @return List of scopes.
* @throws ScopeManagementDAOException
*/
List<Scope> 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;
/**
* This method is to retrieve all the scopes of the given role name.
* Thus it returns the scopes even if the part of the given name is matched.
*
* @param roleName Role name
* @return List of scopes
* @throws ScopeManagementDAOException
*/
List<Scope> getScopesHavingRole(String roleName) throws ScopeManagementDAOException;
}

@ -1,57 +0,0 @@
/*
* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.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);
}
}

@ -1,139 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.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<Connection> currentConnection = new ThreadLocal<Connection>();
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;
}
}

@ -1,57 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.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);
}
}
}
}

@ -1,148 +0,0 @@
/*
* Copyright (c) 2016 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.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<Scope> 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<Scope> getAllScopes() throws ScopeManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Scope> scopes;
try {
conn = this.getConnection();
String sql = "SELECT * FROM IDN_OAUTH2_SCOPE";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
scopes = this.getScopesFromResultSet(rs);
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);
}
}
@Override
public List<Scope> getScopesHavingRole(String roleName) throws ScopeManagementDAOException {
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Scope> scopes;
try {
conn = this.getConnection();
String sql = "SELECT * FROM IDN_OAUTH2_SCOPE WHERE ROLES LIKE ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, "%" + roleName + "%");
rs = stmt.executeQuery();
scopes = this.getScopesFromResultSet(rs);
return scopes;
} catch (SQLException e) {
throw new ScopeManagementDAOException("Error occurred while fetching the details of the scopes.", e);
} finally {
ScopeManagementDAOUtil.cleanupResources(stmt, rs);
}
}
private Connection getConnection() throws SQLException {
return ScopeManagementDAOFactory.getConnection();
}
private List<Scope> getScopesFromResultSet(ResultSet rs) throws SQLException {
List<Scope> scopes = new ArrayList<>();
Scope scope;
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;
}
}

@ -0,0 +1,32 @@
/*
* 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.oauth.extensions.handlers.grant;
import org.wso2.carbon.device.mgt.oauth.extensions.OAuthExtUtils;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
@SuppressWarnings("unused")
public class ExtendedPasswordGrantHandler extends org.wso2.carbon.apimgt.keymgt.handlers.ExtendedPasswordGrantHandler {
@Override
public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) {
return OAuthExtUtils.setScopes(tokReqMsgCtx);
}
}

@ -28,6 +28,10 @@
<!-- If it is true, the APIs of this instance will be published to the defined host --> <!-- If it is true, the APIs of this instance will be published to the defined host -->
<PublishAPI>true</PublishAPI> <PublishAPI>true</PublishAPI>
<!-- If it is true, the APIs of this instance will be updated when the webapps are redeployed -->
<EnabledUpdateApi>true</EnabledUpdateApi>
<!--Webapp will be published only when running below profiles--> <!--Webapp will be published only when running below profiles-->
<Profiles> <Profiles>
<Profile>default</Profile> <Profile>default</Profile>

Loading…
Cancel
Save