revert-70aa11f8
Rasika Perera 9 years ago
commit 07c0aa1045

@ -0,0 +1,45 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.annotations.api;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This class is the representation of custom developed Permission annotation.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Permission {
/**
* Represents the scope name.
* @return Returns scope name.
*/
String scope();
/**
* Represents the associated permissions.
* @return Returns list of permissions.
*/
String[] permissions();
}

@ -18,16 +18,17 @@
*/
package org.wso2.carbon.apimgt.webapp.publisher;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIStatus;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -38,10 +39,7 @@ import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.xml.stream.XMLStreamException;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* This class represents the concrete implementation of the APIPublisherService that corresponds to providing all
@ -50,96 +48,123 @@ import java.util.Map;
public class APIPublisherServiceImpl implements APIPublisherService {
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
private static final String PUBLISH_ACTION = "Publish";
@Override
public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException {
String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner());
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
// Below code snippet is added to load API Lifecycle in tenant mode.
RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService();
CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId),
CommonUtil.getRootSystemRegistry(tenantId));
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner());
MultitenantUtils.getTenantDomain(api.getApiOwner());
if (provider != null) {
if (provider.isDuplicateContextTemplate(api.getContext())) {
throw new APIManagementException(
"Error occurred while adding the API. A duplicate API" +
" context already exists for " + api.getContext());
}
if (!provider.isAPIAvailable(api.getId())) {
provider.addAPI(api);
provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
if (log.isDebugEnabled()) {
log.debug("Successfully published API '" + api.getId().getApiName() +
"' with context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'");
}
} else {
api.setStatus(APIStatus.PUBLISHED);
provider.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("An API already exists with the name '" + api.getId().getApiName() +
"', context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'. Thus, the API config is updated");
}
}
provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api));
} else {
throw new APIManagementException("API provider configured for the given API configuration " +
"is null. Thus, the API is not published");
}
} catch (FileNotFoundException e) {
throw new APIManagementException("Failed to retrieve life cycle file ", e);
} catch (RegistryException e) {
throw new APIManagementException("Failed to access the registry ", e);
} catch (XMLStreamException e) {
throw new APIManagementException("Failed parsing the lifecycle xml.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
private String createSwaggerDefinition(API api) {
Map<String, JsonObject> httpVerbsMap = new HashMap<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
JsonObject response = new JsonObject();
response.addProperty("200", "");
JsonObject responses = new JsonObject();
responses.add("responses", response);
JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate());
if (httpVerbs == null) {
httpVerbs = new JsonObject();
}
httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), responses);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
Iterator it = httpVerbsMap.entrySet().iterator();
JsonObject paths = new JsonObject();
while (it.hasNext()) {
Map.Entry<String, JsonObject> pair = (Map.Entry) it.next();
paths.add(pair.getKey(), pair.getValue());
it.remove();
}
JsonObject info = new JsonObject();
info.addProperty("title", api.getId().getApiName());
info.addProperty("version", api.getId().getVersion());
JsonObject swaggerDefinition = new JsonObject();
swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
swaggerDefinition.add("info", info);
return swaggerDefinition.toString();
}
private static final String PUBLISH_ACTION = "Publish";
@Override
public void publishAPI(final API api) throws APIManagementException, FaultGatewaysException {
String tenantDomain = MultitenantUtils.getTenantDomain(api.getApiOwner());
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
try {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
// Below code snippet is added to load API Lifecycle in tenant mode.
RegistryService registryService = APIPublisherDataHolder.getInstance().getRegistryService();
CommonUtil.addDefaultLifecyclesIfNotAvailable(registryService.getConfigSystemRegistry(tenantId),
CommonUtil.getRootSystemRegistry(tenantId));
APIProvider provider = APIManagerFactory.getInstance().getAPIProvider(api.getApiOwner());
MultitenantUtils.getTenantDomain(api.getApiOwner());
if (provider != null) {
if (provider.isDuplicateContextTemplate(api.getContext())) {
throw new APIManagementException(
"Error occurred while adding the API. A duplicate API" +
" context already exists for " + api.getContext());
}
if (!provider.isAPIAvailable(api.getId())) {
provider.addAPI(api);
provider.changeLifeCycleStatus(api.getId(), PUBLISH_ACTION);
if (log.isDebugEnabled()) {
log.debug("Successfully published API '" + api.getId().getApiName() +
"' with context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'");
}
} else {
api.setStatus(provider.getAPI(api.getId()).getStatus());
provider.updateAPI(api);
if (log.isDebugEnabled()) {
log.debug("An API already exists with the name '" + api.getId().getApiName() +
"', context '" + api.getContext() + "' and version '"
+ api.getId().getVersion() + "'. Thus, the API config is updated");
}
}
provider.saveSwagger20Definition(api.getId(), createSwaggerDefinition(api));
} else {
throw new APIManagementException("API provider configured for the given API configuration " +
"is null. Thus, the API is not published");
}
} catch (FileNotFoundException e) {
throw new APIManagementException("Failed to retrieve life cycle file ", e);
} catch (RegistryException e) {
throw new APIManagementException("Failed to access the registry ", e);
} catch (XMLStreamException e) {
throw new APIManagementException("Failed parsing the lifecycle xml.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
private String createSwaggerDefinition(API api) {
Map<String, JsonObject> httpVerbsMap = new HashMap<>();
List<Scope> scopes = new ArrayList<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
JsonObject response = new JsonObject();
response.addProperty("200", "");
JsonObject responses = new JsonObject();
responses.add("responses", response);
JsonObject httpVerbs = httpVerbsMap.get(uriTemplate.getUriTemplate());
if (httpVerbs == null) {
httpVerbs = new JsonObject();
}
JsonObject httpVerb = new JsonObject();
httpVerb.add("responses", response);
httpVerb.addProperty("x-auth-type", "Application%20%26%20Application%20User");
httpVerb.addProperty("x-throttling-tier", "Unlimited");
if (uriTemplate.getScope() != null) {
httpVerb.addProperty("x-scope", uriTemplate.getScope().getName());
scopes.add(uriTemplate.getScope());
}
httpVerbs.add(uriTemplate.getHTTPVerb().toLowerCase(), httpVerb);
httpVerbsMap.put(uriTemplate.getUriTemplate(), httpVerbs);
}
Iterator it = httpVerbsMap.entrySet().iterator();
JsonObject paths = new JsonObject();
while (it.hasNext()) {
Map.Entry<String, JsonObject> pair = (Map.Entry) it.next();
paths.add(pair.getKey(), pair.getValue());
it.remove();
}
JsonObject info = new JsonObject();
info.addProperty("title", api.getId().getApiName());
info.addProperty("version", api.getId().getVersion());
JsonObject swaggerDefinition = new JsonObject();
swaggerDefinition.add("paths", paths);
swaggerDefinition.addProperty("swagger", "2.0");
swaggerDefinition.add("info", info);
// adding scopes to swagger definition
if (!api.getScopes().isEmpty()) {
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(api.getScopes(), new TypeToken<Set<Scope>>() {
}.getType());
if (element != null) {
JsonArray apiScopes = element.getAsJsonArray();
JsonObject apim = new JsonObject();
apim.add("x-wso2-scopes", apiScopes);
JsonObject wso2Security = new JsonObject();
wso2Security.add("apim", apim);
swaggerDefinition.add("x-wso2-security", wso2Security);
}
}
if (log.isDebugEnabled()) {
log.debug("API swagger definition: " + swaggerDefinition.toString());
}
return swaggerDefinition.toString();
}
@Override
public void removeAPI(APIIdentifier id) throws APIManagementException {
@ -169,4 +194,5 @@ public class APIPublisherServiceImpl implements APIPublisherService {
log.debug("End of publishing the batch of APIs");
}
}
}

@ -18,47 +18,45 @@
package org.wso2.carbon.apimgt.webapp.publisher;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
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.internal.APIPublisherDataHolder;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.user.api.TenantManager;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.ServletContext;
import java.util.*;
public class APIPublisherUtil {
private static final Log log = LogFactory.getLog(APIPublisherUtil.class);
private static final String DEFAULT_API_VERSION = "1.0.0";
public static final String API_VERSION_PARAM="{version}";
public static final String API_PUBLISH_ENVIRONEMENT = "Production and Sandbox";
public static final String API_VERSION_PARAM = "{version}";
public static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox";
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint";
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner";
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports";
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
enum HTTPMethod {
GET, POST, DELETE, PUT, OPTIONS
}
private static List<HTTPMethod> httpMethods;
static {
httpMethods = new ArrayList<HTTPMethod>(5);
httpMethods.add(HTTPMethod.GET);
httpMethods.add(HTTPMethod.POST);
httpMethods.add(HTTPMethod.DELETE);
httpMethods.add(HTTPMethod.PUT);
httpMethods.add(HTTPMethod.OPTIONS);
}
public static API getAPI(APIConfig config) throws APIManagementException {
APIProvider provider = config.getProvider();
String apiVersion = config.getVersion();
APIIdentifier id = new APIIdentifier(replaceEmailDomain(config.getOwner()), config.getName(), apiVersion);
API api = new API(id);
api.setApiOwner(config.getOwner());
String context = config.getContext();
context = context.startsWith("/") ? context : ("/" + context);
@ -67,25 +65,28 @@ public class APIPublisherUtil {
//Create tenant aware context for API
context = "/t/" + providerDomain + context;
}
// This is to support the new Pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
context = checkAndSetVersionParam(context);
api.setContextTemplate(context);
context = updateContextWithVersion(config.getVersion(), context);
api.setContext(context);
api.setUrl(config.getEndpoint());
api.addAvailableTiers(provider.getTiers());
api.setEndpointSecured(true);
api.setStatus(APIStatus.CREATED);
api.setTransports(config.getTransports());
api.setContextTemplate(config.getContextTemplate());
api.setUriTemplates(config.getUriTemplates());
Set<String> environements = new HashSet<>();
environements.add(API_PUBLISH_ENVIRONEMENT);
api.setEnvironments(environements);
Set<Tier> tiers = new HashSet<Tier>();
Set<String> environments = new HashSet<>();
environments.add(API_PUBLISH_ENVIRONMENT);
api.setEnvironments(environments);
Set<Tier> tiers = new HashSet<>();
tiers.add(new Tier(APIConstants.UNLIMITED_TIER));
api.addAvailableTiers(tiers);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS);
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY);
@ -95,7 +96,9 @@ public class APIPublisherUtil {
}
api.setResponseCache(APIConstants.DISABLED);
String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() + "\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
String endpointConfig = "{\"production_endpoints\":{\"url\":\" " + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
api.setEndpointConfig(endpointConfig);
if ("".equals(id.getVersion()) || (DEFAULT_API_VERSION.equals(id.getVersion()))) {
@ -106,35 +109,37 @@ public class APIPublisherUtil {
Set<String> tags = new HashSet<>(Arrays.asList(config.getTags()));
api.addTags(tags);
}
return api;
}
private static Set<URITemplate> getURITemplates(String endpoint, String authType) {
Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
if (APIConstants.AUTH_NO_AUTHENTICATION.equals(authType)) {
for (HTTPMethod method : httpMethods) {
URITemplate template = new URITemplate();
template.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
template.setHTTPVerb(method.toString());
template.setResourceURI(endpoint);
template.setUriTemplate("/*");
uriTemplates.add(template);
// adding scopes to the api
Set<URITemplate> uriTemplates = config.getUriTemplates();
Map<String, Scope> apiScopes = new HashMap<>();
if (uriTemplates != null) {
// this creates distinct scopes list
for (URITemplate template : uriTemplates) {
Scope scope = template.getScope();
if (scope != null) {
if (apiScopes.get(scope.getKey()) == null) {
apiScopes.put(scope.getKey(), scope);
}
}
}
} else {
for (HTTPMethod method : httpMethods) {
URITemplate template = new URITemplate();
if (HTTPMethod.OPTIONS.equals(method)) {
template.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
} else {
template.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
Set<Scope> scopes = new HashSet<>(apiScopes.values());
api.setScopes(scopes);
// this has to be done because of the use of pass by reference
// where same object reference of scope should be available for both
// api scope and uri template scope
for (Scope scope : scopes) {
for (URITemplate template : uriTemplates) {
if (scope.getKey().equals(template.getScope().getKey())) {
template.setScope(scope);
}
}
template.setHTTPVerb(method.toString());
template.setResourceURI(endpoint);
template.setUriTemplate("/*");
uriTemplates.add(template);
}
api.setUriTemplates(uriTemplates);
}
return uriTemplates;
return api;
}
public static String getServerBaseUrl() {
@ -163,13 +168,15 @@ public class APIPublisherUtil {
}
/**
* When an input is having '@',replace it with '-AT-' [This is required to persist API data in registry,as registry paths don't allow '@' sign.]
* When an input is having '@',replace it with '-AT-'
* [This is required to persist API data in registry,as registry paths don't allow '@' sign.]
*
* @param input inputString
* @return String modifiedString
*/
private static String replaceEmailDomain(String input){
if(input!=null&& input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR) ){
input=input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR,APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
private static String replaceEmailDomain(String input) {
if (input != null && input.contains(APIConstants.EMAIL_DOMAIN_SEPARATOR)) {
input = input.replace(APIConstants.EMAIL_DOMAIN_SEPARATOR, APIConstants.EMAIL_DOMAIN_SEPARATOR_REPLACEMENT);
}
return input;
}
@ -184,13 +191,131 @@ public class APIPublisherUtil {
private static String checkAndSetVersionParam(String context) {
// This is to support the new Pluggable version strategy
// if the context does not contain any {version} segment, we use the default version strategy.
if(!context.contains(API_VERSION_PARAM)){
if(!context.endsWith("/")){
if (!context.contains(API_VERSION_PARAM)) {
if (!context.endsWith("/")) {
context = context + "/";
}
context = context +API_VERSION_PARAM;
context = context + API_VERSION_PARAM;
}
return context;
}
/**
* Build the API Configuration to be passed to APIM, from a given list of URL templates
*
* @param servletContext
* @param apiDef
* @return
*/
public static APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apiDef) {
APIConfig apiConfig = new APIConfig();
String name = apiDef.getName();
if (name == null || name.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("API Name not set in @API Annotation");
}
name = servletContext.getServletContextName();
}
apiConfig.setName(name);
String version = apiDef.getVersion();
if (version == null || version.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Version not set in @API Annotation'");
}
version = API_CONFIG_DEFAULT_VERSION;
}
apiConfig.setVersion(version);
String context = apiDef.getContext();
if (context == null || context.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Context not set in @API Annotation'");
}
context = servletContext.getContextPath();
}
apiConfig.setContext(context);
String[] tags = apiDef.getTags();
if (tags == null || tags.length == 0) {
if (log.isDebugEnabled()) {
log.debug("'API tag not set in @API Annotation'");
}
} else {
apiConfig.setTags(tags);
}
String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN);
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured");
}
String endpointContext = servletContext.getContextPath();
endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
}
apiConfig.setEndpoint(endpoint);
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-owner' attribute is not configured");
}
}
apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured;
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which is 'https'");
}
transports = "https";
}
apiConfig.setTransports(transports);
String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty())
&& Boolean.parseBoolean(sharingValueParam));
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
Set<URITemplate> uriTemplates = new LinkedHashSet<>();
for (APIResource apiResource : apiDef.getResources()) {
URITemplate template = new URITemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());
template.setScope(apiResource.getScope());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
}

@ -18,70 +18,71 @@
package org.wso2.carbon.apimgt.webapp.publisher.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Resource")
public class APIResource{
private String AuthType;
private String HttpVerb;
private String Uri;
private String UriTemplate;
private String consumes;
private String produces;
public String getAuthType() {
return AuthType;
}
@XmlElement(name = "AuthType", required = true)
public void setAuthType(String authType) {
AuthType = authType;
}
public String getHttpVerb() {
return HttpVerb;
}
@XmlElement(name = "HttpVerb", required = true)
public void setHttpVerb(String httpVerb) {
HttpVerb = httpVerb;
}
public String getUri() {
return Uri;
}
@XmlElement(name = "Uri", required = true)
public void setUri(String uri) {
Uri = uri;
}
public String getUriTemplate() {
return UriTemplate;
}
@XmlElement(name = "UriTemplate", required = true)
public void setUriTemplate(String uriTemplate) {
UriTemplate = uriTemplate;
}
public String getConsumes() {
return consumes;
}
@XmlElement(name = "Consumes", required = true)
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
@XmlElement(name = "Produces", required = true)
public void setProduces(String produces) {
this.produces = produces;
}
import org.wso2.carbon.apimgt.api.model.Scope;
public class APIResource {
private String AuthType;
private String HttpVerb;
private String Uri;
private String UriTemplate;
private String consumes;
private String produces;
private Scope scope;
public String getAuthType() {
return AuthType;
}
public void setAuthType(String authType) {
AuthType = authType;
}
public String getHttpVerb() {
return HttpVerb;
}
public void setHttpVerb(String httpVerb) {
HttpVerb = httpVerb;
}
public String getUri() {
return Uri;
}
public void setUri(String uri) {
Uri = uri;
}
public String getUriTemplate() {
return UriTemplate;
}
public void setUriTemplate(String uriTemplate) {
UriTemplate = uriTemplate;
}
public String getConsumes() {
return consumes;
}
public void setConsumes(String consumes) {
this.consumes = consumes;
}
public String getProduces() {
return produces;
}
public void setProduces(String produces) {
this.produces = produces;
}
public Scope getScope() {
return scope;
}
public void setScope(Scope scope) {
this.scope = scope;
}
}

@ -0,0 +1,45 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.apimgt.webapp.publisher.config;
/**
* This class represents the information related to permissions.
*/
public class PermissionConfiguration {
private String scopeName;
private String[] permissions;
public String getScopeName() {
return scopeName;
}
public void setScopeName(String scope) {
this.scopeName = scope;
}
public String[] getPermissions() {
return permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
}

@ -0,0 +1,60 @@
/*
* 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);
}
}

@ -24,206 +24,85 @@ import org.apache.catalina.LifecycleListener;
import org.apache.catalina.core.StandardContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.model.*;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.webapp.publisher.*;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResource;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherUtil;
import org.wso2.carbon.apimgt.webapp.publisher.config.APIResourceConfiguration;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util.AnnotationUtil;
import org.wso2.carbon.base.MultitenantConstants;
import javax.servlet.ServletContext;
import java.io.IOException;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
@SuppressWarnings("unused")
public class APIPublisherLifecycleListener implements LifecycleListener {
private static final String API_CONFIG_DEFAULT_VERSION = "1.0.0";
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
private static final String PARAM_MANAGED_API_NAME = "managed-api-name";
private static final String PARAM_MANAGED_API_VERSION = "managed-api-version";
private static final String PARAM_MANAGED_API_CONTEXT = "managed-api-context";
private static final String PARAM_MANAGED_API_ENDPOINT = "managed-api-endpoint";
private static final String PARAM_MANAGED_API_OWNER = "managed-api-owner";
private static final String PARAM_MANAGED_API_TRANSPORTS = "managed-api-transports";
private static final String PARAM_MANAGED_API_IS_SECURED = "managed-api-isSecured";
private static final String PARAM_MANAGED_API_APPLICATION = "managed-api-application";
private static final String PARAM_SHARED_WITH_ALL_TENANTS = "isSharedWithAllTenants";
private static final String PARAM_PROVIDER_TENANT_DOMAIN = "providerTenantDomain";
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
try {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil.
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext, annotatedAPIClasses);
for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = this.buildApiConfig(servletContext, apiDefinition);
try {
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().getTenantId(apiConfig.getTenantDomain());
boolean isTenantActive = APIPublisherDataHolder.getInstance().getTenantManager().isTenantActive(tenantId);
if (isTenantActive) {
apiConfig.init();
API api = APIPublisherUtil.getAPI(apiConfig);
APIPublisherService apiPublisherService =
APIPublisherDataHolder.getInstance().getApiPublisherService();
if (apiPublisherService == null) {
throw new IllegalStateException(
"API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(api);
} else {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] found when publishing the webapp");
}
} catch (Throwable e) {
log.error("Error occurred while publishing API '" + apiConfig.getName() +
"' with the context '" + apiConfig.getContext() +
"' and version '" + apiConfig.getVersion() + "'", e);
}
}
} catch (IOException e) {
log.error("Error enconterd while discovering annotated classes", e);
} catch (ClassNotFoundException e) {
log.error("Error while scanning class for annotations", e);
}
}
}
}
private List<APIResourceConfiguration> mergeAPIDefinitions(List<APIResourceConfiguration> inputList) {
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two
// classes
return null;
}
/**
* Build the API Configuration to be passed to APIM, from a given list of URL templates
*
* @param servletContext
* @return
*/
private APIConfig buildApiConfig(ServletContext servletContext, APIResourceConfiguration apidef) {
APIConfig apiConfig = new APIConfig();
String name = apidef.getName();
if (name == null || name.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("API Name not set in @API Annotation");
}
name = servletContext.getServletContextName();
}
apiConfig.setName(name);
String version = apidef.getVersion();
if (version == null || version.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Version not set in @API Annotation'");
}
version = API_CONFIG_DEFAULT_VERSION;
}
apiConfig.setVersion(version);
String context = apidef.getContext();
if (context == null || context.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'API Context not set in @API Annotation'");
}
context = servletContext.getContextPath();
}
apiConfig.setContext(context);
String[] tags = apidef.getTags();
if (tags == null || tags.length == 0) {
if (log.isDebugEnabled()) {
log.debug("'API tag not set in @API Annotation'");
}
} else {
apiConfig.setTags(tags);
}
String tenantDomain = servletContext.getInitParameter(PARAM_PROVIDER_TENANT_DOMAIN);
tenantDomain = (tenantDomain != null && !tenantDomain.isEmpty()) ? tenantDomain :
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
apiConfig.setTenantDomain(tenantDomain);
String contextTemplate = context + "/" + APIConstants.VERSION_PLACEHOLDER;
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextTemplate = context + "/t/" + tenantDomain + "/" + APIConstants.VERSION_PLACEHOLDER;
}
apiConfig.setContextTemplate(contextTemplate);
String endpoint = servletContext.getInitParameter(PARAM_MANAGED_API_ENDPOINT);
if (endpoint == null || endpoint.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-endpoint' attribute is not configured");
}
String endpointContext = servletContext.getContextPath();
endpoint = APIPublisherUtil.getApiEndpointUrl(endpointContext);
}
apiConfig.setEndpoint(endpoint);
String owner = servletContext.getInitParameter(PARAM_MANAGED_API_OWNER);
if (owner == null || owner.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-owner' attribute is not configured");
}
}
apiConfig.setOwner(owner);
String isSecuredParam = servletContext.getInitParameter(PARAM_MANAGED_API_IS_SECURED);
boolean isSecured;
if (isSecuredParam == null || isSecuredParam.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-isSecured' attribute is not configured. Therefore, using the default, " +
"which is 'true'");
}
isSecured = false;
} else {
isSecured = Boolean.parseBoolean(isSecuredParam);
}
apiConfig.setSecured(isSecured);
String transports = servletContext.getInitParameter(PARAM_MANAGED_API_TRANSPORTS);
if (transports == null || transports.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("'managed-api-transports' attribute is not configured. Therefore using the default, " +
"which is 'https'");
}
transports = "https";
}
apiConfig.setTransports(transports);
String sharingValueParam = servletContext.getInitParameter(PARAM_SHARED_WITH_ALL_TENANTS);
boolean isSharedWithAllTenants = (sharingValueParam == null || (!sharingValueParam.isEmpty()) && Boolean.parseBoolean(
sharingValueParam));
apiConfig.setSharedWithAllTenants(isSharedWithAllTenants);
Set<URITemplate> uriTemplates = new LinkedHashSet<URITemplate>();
for (APIResource apiResource : apidef.getResources()) {
URITemplate template = new URITemplate();
template.setAuthType(apiResource.getAuthType());
template.setHTTPVerb(apiResource.getHttpVerb());
template.setResourceURI(apiResource.getUri());
template.setUriTemplate(apiResource.getUriTemplate());
uriTemplates.add(template);
}
apiConfig.setUriTemplates(uriTemplates);
return apiConfig;
}
private static final Log log = LogFactory.getLog(APIPublisherLifecycleListener.class);
private static final String PARAM_MANAGED_API_ENABLED = "managed-api-enabled";
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
StandardContext context = (StandardContext) lifecycleEvent.getLifecycle();
ServletContext servletContext = context.getServletContext();
String param = servletContext.getInitParameter(PARAM_MANAGED_API_ENABLED);
boolean isManagedApi = (param != null && !param.isEmpty()) && Boolean.parseBoolean(param);
if (isManagedApi) {
try {
AnnotationUtil annotationUtil = new AnnotationUtil(context);
Set<String> annotatedAPIClasses = annotationUtil.
scanStandardContext(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
List<APIResourceConfiguration> apiDefinitions = annotationUtil.extractAPIInfo(servletContext,
annotatedAPIClasses);
for (APIResourceConfiguration apiDefinition : apiDefinitions) {
APIConfig apiConfig = APIPublisherUtil.buildApiConfig(servletContext, apiDefinition);
try {
int tenantId = APIPublisherDataHolder.getInstance().getTenantManager().
getTenantId(apiConfig.getTenantDomain());
boolean isTenantActive = APIPublisherDataHolder.getInstance().
getTenantManager().isTenantActive(tenantId);
if (isTenantActive) {
apiConfig.init();
API api = APIPublisherUtil.getAPI(apiConfig);
APIPublisherService apiPublisherService =
APIPublisherDataHolder.getInstance().getApiPublisherService();
if (apiPublisherService == null) {
throw new IllegalStateException(
"API Publisher service is not initialized properly");
}
apiPublisherService.publishAPI(api);
} else {
log.error("No tenant [" + apiConfig.getTenantDomain() + "] " +
"found when publishing the Web app");
}
} catch (Throwable e) {
log.error("Error occurred while publishing API '" + apiConfig.getName() +
"' with the context '" + apiConfig.getContext() +
"' and version '" + apiConfig.getVersion() + "'", e);
}
}
} catch (IOException e) {
log.error("Error encountered while discovering annotated classes", e);
} catch (ClassNotFoundException e) {
log.error("Error while scanning class for annotations", e);
}
}
}
}
//TODO : Need to implemented, to merge API Definitions in cases where implementation of an API Lies in two classes
private List<APIResourceConfiguration> mergeAPIDefinitions(List<APIResourceConfiguration> inputList) {
return null;
}
}

@ -20,12 +20,19 @@ 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.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.*;
import java.io.IOException;
@ -36,7 +43,9 @@ import java.lang.reflect.Proxy;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class AnnotationUtil {
@ -45,17 +54,18 @@ public class AnnotationUtil {
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 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";
public static final String DIR_WEB_INF_LIB = "/WEB-INF/lib";
public static final String STRING_ARR = "string_arr";
public static final String STRING = "string";
private static final String STRING_ARR = "string_arr";
private static final String STRING = "string";
private StandardContext context;
private Method[] pathClazzMethods;
private Class<Path> pathClazz;
Class<API> apiClazz;
private ClassLoader classLoader;
private ServletContext servletContext;
@ -68,6 +78,7 @@ public class AnnotationUtil {
/**
* Scan the context for classes with annotations
*
* @return
* @throws IOException
*/
@ -89,6 +100,7 @@ public class AnnotationUtil {
/**
* Method identifies the URL templates and context by reading the annotations of a class
*
* @param entityClasses
* @return
*/
@ -107,38 +119,22 @@ public class AnnotationUtil {
APIResourceConfiguration apiResourceConfig = null;
try {
clazz = classLoader.loadClass(className);
Class<Path> apiClazz = (Class<Path>)
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API.class.getName());
Annotation apiAnno = clazz.getAnnotation(apiClazz);
apiClazz = (Class<API>)
classLoader.loadClass(org.wso2.carbon.apimgt.annotations.api.API
.class.getName());
Annotation apiAnno = clazz.getAnnotation(apiClazz);
List<APIResource> resourceList;
apiResourceConfig = new APIResourceConfiguration();
if (apiAnno != null) {
Method[] apiClazzMethods = apiClazz.getMethods();
if (log.isDebugEnabled()) {
log.debug("Application Context root = " + servletContext.getContextPath());
}
try {
for(int k=0;k<apiClazzMethods.length;k++){
switch (apiClazzMethods[k].getName()){
case "name" :
apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "version" :
apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "context" :
apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "tags" :
apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno));
break;
}
}
apiResourceConfig = processAPIAnnotation(apiAnno);
// All the apis should map to same root "/"
String rootContext = servletContext.getContextPath();
pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName());
@ -177,7 +173,45 @@ public class AnnotationUtil {
return apiResourceConfigs;
}
private List<APIResource> getApiResources(String resourceRootContext, String apiRootContext, Method[] annotatedMethods) throws Throwable {
/**
* Iterate API annotation and build API Configuration
* @param apiAnno
* @return
* @throws Throwable
*/
private APIResourceConfiguration processAPIAnnotation(Annotation apiAnno) throws Throwable {
Method[] apiClazzMethods = apiClazz.getMethods();
APIResourceConfiguration apiResourceConfig = new APIResourceConfiguration();
for (int k = 0; k < apiClazzMethods.length; k++) {
switch (apiClazzMethods[k].getName()) {
case "name":
apiResourceConfig.setName(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "version":
apiResourceConfig.setVersion(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "context":
apiResourceConfig.setContext(invokeMethod(apiClazzMethods[k], apiAnno, STRING));
break;
case "tags":
apiResourceConfig.setTags(invokeMethod(apiClazzMethods[k], apiAnno));
break;
}
}
return apiResourceConfig;
}
/**
* Get Resources for each API
* @param resourceRootContext
* @param apiRootContext
* @param annotatedMethods
* @return
* @throws Throwable
*/
private List<APIResource> getApiResources(String resourceRootContext, String apiRootContext,
Method[] annotatedMethods) throws Throwable {
List<APIResource> resourceList;
resourceList = new ArrayList<APIResource>();
for (Method method : annotatedMethods) {
@ -195,35 +229,34 @@ public class AnnotationUtil {
resource.setAuthType(AUTH_TYPE);
Annotation[] annotations = method.getDeclaredAnnotations();
for(int i=0; i<annotations.length; i++){
if(annotations[i].annotationType().getName().equals(GET.class.getName())){
resource.setHttpVerb(HttpMethod.GET);
}
if(annotations[i].annotationType().getName().equals(POST.class.getName())){
resource.setHttpVerb(HttpMethod.POST);
}
if(annotations[i].annotationType().getName().equals(OPTIONS.class.getName())){
resource.setHttpVerb(HttpMethod.OPTIONS);
}
if(annotations[i].annotationType().getName().equals(DELETE.class.getName())){
resource.setHttpVerb(HttpMethod.DELETE);
}
if(annotations[i].annotationType().getName().equals(PUT.class.getName())){
resource.setHttpVerb(HttpMethod.PUT);
}
if(annotations[i].annotationType().getName().equals(Consumes.class.getName())){
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(Consumes.class.getName());
for (int i = 0; i < annotations.length; i++) {
processHTTPMethodAnnotation(resource, annotations[i]);
if (annotations[i].annotationType().getName().equals(Consumes.class.getName())) {
Class<Consumes> consumesClass = (Class<Consumes>) classLoader.loadClass(
Consumes.class.getName());
Method[] consumesClassMethods = consumesClass.getMethods();
Annotation consumesAnno = method.getAnnotation(consumesClass);
resource.setConsumes(invokeMethod(consumesClassMethods[0], consumesAnno, STRING_ARR));
}
if(annotations[i].annotationType().getName().equals(Produces.class.getName())){
Class<Produces> producesClass = (Class<Produces>) classLoader.loadClass(Produces.class.getName());
if (annotations[i].annotationType().getName().equals(Produces.class.getName())) {
Class<Produces> producesClass = (Class<Produces>) classLoader.loadClass(
Produces.class.getName());
Method[] producesClassMethods = producesClass.getMethods();
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);
resource.setScope(scope);
}
}
}
resourceList.add(resource);
}
@ -231,12 +264,40 @@ public class AnnotationUtil {
return resourceList;
}
private String makeContextURLReady(String context){
if(context != null && !context.equalsIgnoreCase("")){
if(context.startsWith("/")){
/**
* Read Method annotations indicating HTTP Methods
* @param resource
* @param annotation
*/
private void processHTTPMethodAnnotation(APIResource resource, Annotation annotation) {
if (annotation.annotationType().getName().equals(GET.class.getName())) {
resource.setHttpVerb(HttpMethod.GET);
}
if (annotation.annotationType().getName().equals(POST.class.getName())) {
resource.setHttpVerb(HttpMethod.POST);
}
if (annotation.annotationType().getName().equals(OPTIONS.class.getName())) {
resource.setHttpVerb(HttpMethod.OPTIONS);
}
if (annotation.annotationType().getName().equals(DELETE.class.getName())) {
resource.setHttpVerb(HttpMethod.DELETE);
}
if (annotation.annotationType().getName().equals(PUT.class.getName())) {
resource.setHttpVerb(HttpMethod.PUT);
}
}
/**
* Append '/' to the context and make it URL ready
* @param context
* @return
*/
private String makeContextURLReady(String context) {
if (context != null && !context.equalsIgnoreCase("")) {
if (context.startsWith("/")) {
return context;
}else{
return "/"+context;
} else {
return "/" + context;
}
}
return "";
@ -244,6 +305,7 @@ public class AnnotationUtil {
/**
* When an annotation and method is passed, this method invokes that executes said method against the annotation
*
* @param method
* @param annotation
* @param returnType
@ -252,11 +314,11 @@ public class AnnotationUtil {
*/
private String invokeMethod(Method method, Annotation annotation, String returnType) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
switch (returnType){
switch (returnType) {
case STRING:
return (String) methodHandler.invoke(annotation, method, null);
case STRING_ARR:
return ((String[])methodHandler.invoke(annotation, method, null))[0];
return ((String[]) methodHandler.invoke(annotation, method, null))[0];
default:
return null;
}
@ -267,6 +329,36 @@ public class AnnotationUtil {
*/
private String[] invokeMethod(Method method, Annotation annotation) throws Throwable {
InvocationHandler methodHandler = Proxy.getInvocationHandler(annotation);
return ((String[])methodHandler.invoke(annotation, method, null));
return ((String[]) methodHandler.invoke(annotation, method, null));
}
private PermissionConfiguration getPermission(Method currentMethod) throws Throwable {
Class<Permission> permissionClass = (Class<Permission>) classLoader.loadClass(Permission.class.getName());
Annotation permissionAnnotation = currentMethod.getAnnotation(permissionClass);
if (permissionClass != null) {
Method[] permissionClassMethods = permissionClass.getMethods();
PermissionConfiguration permissionConf = new PermissionConfiguration();
for (Method method : permissionClassMethods) {
switch (method.getName()) {
case "scope":
permissionConf.setScopeName(invokeMethod(method, permissionAnnotation, STRING));
break;
case "permissions":
String permissions[] = invokeMethod(method, permissionAnnotation);
this.addPermission(permissions);
permissionConf.setPermissions(permissions);
break;
}
}
return permissionConf;
}
return null;
}
private void addPermission(String[] permissions) throws PermissionManagementException {
for (String permission : permissions) {
PermissionUtils.addPermission(permission);
}
}
}

@ -0,0 +1,91 @@
/*
* 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;
}
}

@ -18,6 +18,10 @@
package org.wso2.carbon.device.mgt.analytics.dashboard;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List;
import java.util.Map;
/**
@ -26,30 +30,61 @@ import java.util.Map;
public interface GadgetDataService {
@SuppressWarnings("unused")
int getTotalDeviceCount(Map<String, Object> filters);
int getTotalDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getActiveDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getInactiveDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getRemovedDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getNonCompliantDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getUnmonitoredDeviceCount() throws GadgetDataServiceException;
@SuppressWarnings("unused")
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getActiveDeviceCount();
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getInactiveDeviceCount();
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getRemovedDeviceCount();
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getNonCompliantDeviceCount();
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
int getUnmonitoredDeviceCount();
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
PaginationRequest paginationRequest) throws GadgetDataServiceException;
@SuppressWarnings("unused")
Map<String, Integer> getNonCompliantDeviceCountsByFeatures();
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters);
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters);
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException;
}

@ -0,0 +1,82 @@
/*
* 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.analytics.dashboard;
/**
* Custom exception class for GadgetDataService layer.
*/
public class GadgetDataServiceException extends Exception {
private String errorMessage;
private static final long serialVersionUID = 2021891706072918864L;
/**
* Constructs a new exception with the specific error message and nested exception.
*
* @param errorMessage specific error message.
* @param nestedException Nested exception.
*/
public GadgetDataServiceException(String errorMessage, Exception nestedException) {
super(errorMessage, nestedException);
setErrorMessage(errorMessage);
}
/**
* Constructs a new exception with the specific error message and cause.
*
* @param errorMessage Specific error message.
* @param cause Cause of this exception.
*/
@SuppressWarnings("unused")
public GadgetDataServiceException(String errorMessage, Throwable cause) {
super(errorMessage, cause);
setErrorMessage(errorMessage);
}
/**
* Constructs a new exception with the specific error message.
*
* @param errorMessage Specific error message.
*/
@SuppressWarnings("unused")
public GadgetDataServiceException(String errorMessage) {
super(errorMessage);
setErrorMessage(errorMessage);
}
/**
* Constructs a new exception with the specific error message and cause.
*
* @param cause Cause of this exception.
*/
@SuppressWarnings("unused")
public GadgetDataServiceException(Throwable cause) {
super(cause);
}
@SuppressWarnings("unused")
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -18,6 +18,9 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List;
import java.util.Map;
@ -26,57 +29,72 @@ public interface GadgetDataServiceDAO {
/**
* Method to get total filtered device count from a particular tenant.
*
* @param filters List of filters to be applied in getting
* total filtered device count.
*
* @return Total filtered device count.
*/
int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
int getTotalDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get active device count from a particular tenant.
*
* @return active device count.
*/
int getActiveDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get inactive device count from a particular tenant.
*
* @return inactive device count.
*/
int getInactiveDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get removed device count from a particular tenant.
*
* @return removed device count.
*/
int getRemovedDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get non-compliant device count.
* Method to get non-compliant device count from a particular tenant.
*
* @return Non-compliant device count.
*/
@SuppressWarnings("unused")
int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException;
/**
* Method to get unmonitored device count.
* Method to get unmonitored device count from a particular tenant.
*
* @return Unmonitored device count.
*/
@SuppressWarnings("unused")
int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
throws GadgetDataServiceDAOException;
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException;
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException;
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException;
}

@ -18,11 +18,11 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
@SuppressWarnings("unused")
/**
* Custom exception class for data access related exceptions.
* Custom exception class for GadgetDataServiceDAO layer.
*/
public class GadgetDataServiceDAOException extends Exception {
private String errorMessage;
private static final long serialVersionUID = 2021891706072918864L;
@ -43,6 +43,7 @@ public class GadgetDataServiceDAOException extends Exception {
* @param errorMessage Specific error message.
* @param cause Cause of this exception.
*/
@SuppressWarnings("unused")
public GadgetDataServiceDAOException(String errorMessage, Throwable cause) {
super(errorMessage, cause);
setErrorMessage(errorMessage);
@ -53,6 +54,7 @@ public class GadgetDataServiceDAOException extends Exception {
*
* @param errorMessage Specific error message.
*/
@SuppressWarnings("unused")
public GadgetDataServiceDAOException(String errorMessage) {
super(errorMessage);
setErrorMessage(errorMessage);
@ -63,10 +65,12 @@ public class GadgetDataServiceDAOException extends Exception {
*
* @param cause Cause of this exception.
*/
@SuppressWarnings("unused")
public GadgetDataServiceDAOException(Throwable cause) {
super(cause);
}
@SuppressWarnings("unused")
public String getErrorMessage() {
return errorMessage;
}
@ -74,4 +78,5 @@ public class GadgetDataServiceDAOException extends Exception {
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -33,6 +33,7 @@ import java.util.List;
@SuppressWarnings("unused")
public class GadgetDataServiceDAOFactory {
private static final Log log = LogFactory.getLog(GadgetDataServiceDAOFactory.class);
private static DataSource dataSource;
private static String databaseEngine;
@ -47,7 +48,7 @@ public class GadgetDataServiceDAOFactory {
try {
databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
log.error("Error occurred while retrieving config.datasource connection.", e);
}
}
@ -56,7 +57,7 @@ public class GadgetDataServiceDAOFactory {
try {
databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
log.error("Error occurred while retrieving config.datasource connection.", e);
}
}
@ -64,8 +65,8 @@ public class GadgetDataServiceDAOFactory {
Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("A transaction is already active within the context of " +
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling");
"this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
"transaction is already active is a sign of improper transaction handling.");
}
conn = dataSource.getConnection();
currentConnection.set(conn);
@ -75,8 +76,8 @@ public class GadgetDataServiceDAOFactory {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods.");
}
return conn;
}
@ -85,36 +86,35 @@ public class GadgetDataServiceDAOFactory {
Connection conn = currentConnection.get();
if (conn == null) {
throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods");
"This might have ideally been caused by not properly initiating the transaction via " +
"'beginTransaction'/'openConnection' methods.");
}
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while close the connection");
log.warn("Error occurred while close the connection.");
}
currentConnection.remove();
}
/**
* Resolve data source from the data source definition
* Resolve data source from the data source definition.
*
* @param config data source configuration
* @return data source resolved from the data source definition
* @param config data source configuration.
* @return data source resolved from the data source definition.
*/
private static DataSource resolveDataSource(DataSourceConfig config) {
DataSource dataSource = null;
if (config == null) {
throw new RuntimeException(
"Device Management Repository data source configuration " + "is null and " +
"thus, is not initialized");
"Device Management Repository data source configuration " + "is null and " +
"thus, is not initialized.");
}
JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
if (jndiConfig != null) {
if (log.isDebugEnabled()) {
log.debug("Initializing Device Management Repository data source using the JNDI " +
"Lookup Definition");
log.debug("Initializing Device Management Repository data source using the JNDI Lookup Definition.");
}
List<JNDILookupDefinition.JNDIProperty> jndiPropertyList = jndiConfig.getJndiProperties();
if (jndiPropertyList != null) {

@ -18,9 +18,9 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import java.sql.Connection;
@ -33,126 +33,146 @@ import java.util.List;
import java.util.Map;
class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(GadgetDataServiceDAOImpl.class);
@Override
public int getTotalDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCount(filteringViewID, filters);
}
@Override
public int getFeatureNonCompliantDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCount(filteringViewID, filters);
public int getTotalDeviceCount() throws GadgetDataServiceDAOException {
return this.getDeviceCount(null);
}
@Override
public int getActiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "ACTIVE");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getInactiveDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "INACTIVE");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getRemovedDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("CONNECTIVITY_STATUS", "REMOVED");
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("IS_COMPLIANT", 0);
return this.getDeviceCount(filteringViewID, filters);
return this.getDeviceCount(filters);
}
@Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() throws GadgetDataServiceDAOException {
public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException {
Map<String, Object> filters = new HashMap<>();
filters.put("POLICY_ID", -1);
return this.getDeviceCount(filters);
}
@Override
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredNonCompliantDeviceCountsByFeatures = new HashMap<>();
List<Map<String, Object>> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
int totalRecordsCount = 0;
try {
con = this.getConnection();
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE";
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setInt(2, paginationRequest.getStartIndex());
stmt.setInt(3, paginationRequest.getRowCount());
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredNonCompliantDeviceCountByFeature;
while (rs.next()) {
filteredNonCompliantDeviceCountsByFeatures.
put(rs.getString("FEATURE_CODE"), rs.getInt("DEVICE_COUNT"));
filteredNonCompliantDeviceCountByFeature = new HashMap<>();
filteredNonCompliantDeviceCountByFeature.put("FEATURE_CODE", rs.getString("FEATURE_CODE"));
filteredNonCompliantDeviceCountByFeature.put("DEVICE_COUNT", rs.getInt("DEVICE_COUNT"));
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
}
// fetching total records count
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?)";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting non compliant device counts by features.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredNonCompliantDeviceCountsByFeatures;
}
@Override
public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException {
int filteringViewID = 1;
Map<String, Object> filters = new HashMap<>();
filters.put("POLICY_ID", -1);
return this.getDeviceCount(filteringViewID, filters);
}
@Override
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCountsByPlatforms(filteringViewID, filters);
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCountsByPlatforms(filteringViewID, filters);
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
paginationResult.setRecordsTotal(totalRecordsCount);
return paginationResult;
}
@Override
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters);
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDeviceCountsByOwnershipTypes(filteringViewID, filters);
}
@Override
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 1;
return this.getDevicesWithDetails(filteringViewID, filters);
}
@Override
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
int filteringViewID = 2;
return this.getDevicesWithDetails(filteringViewID, filters);
public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
int filteredDeviceCount = 0;
try {
con = this.getConnection();
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
sql = sql + " AND " + column + " = ?";
}
}
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
if (filters != null && filters.values().size() > 0) {
int i = 2;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered device count.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCount;
}
private int getDeviceCount(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -160,13 +180,7 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
int filteredDeviceCount = 0;
try {
con = this.getConnection();
String sql;
if (filteringViewID == 1) {
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
} else {
// if filteringViewID == 2
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?";
}
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns
if (filters != null && filters.size() > 0) {
@ -177,8 +191,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 2;
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
@ -195,14 +210,16 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered device count, " +
"non compliant by a particular feature.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCount;
}
private Map<String, Integer> getDeviceCountsByPlatforms(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
@ -218,14 +235,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
if (filteringViewID == 1) {
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
} else {
// if filteringViewID == 2
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
}
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY PLATFORM";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
@ -247,19 +258,20 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of device counts by platforms.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByPlatforms;
}
private Map<String, Integer> getDeviceCountsByOwnershipTypes(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
@ -270,14 +282,56 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
if (filteringViewID == 1) {
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
} else {
// if filteringViewID == 2
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
sql = "SELECT PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a set of feature non-compliant device counts by platforms.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByPlatforms;
}
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
advancedSqlFiltering + "GROUP BY OWNERSHIP";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
@ -299,29 +353,229 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of device counts by ownership types.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByOwnershipTypes;
}
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY OWNERSHIP";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of feature " +
"non-compliant device counts by ownership types.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDeviceCountsByOwnershipTypes;
}
private List<Map<String, Object>> getDevicesWithDetails(int filteringViewID, Map<String, Object> filters) throws GadgetDataServiceDAOException {
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Object> filteredDeviceWithDetails = new HashMap<>();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
int totalRecordsCount = 0;
try {
con = this.getConnection();
String sql;
if (filteringViewID == 1) {
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " +
"WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
if (filters != null && filters.values().size() > 0) {
int i = 2;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
stmt.setInt(i, paginationRequest.getStartIndex());
stmt.setInt(++i, paginationRequest.getRowCount());
} else {
// if filteringViewID == 2
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?";
stmt.setInt(2, paginationRequest.getStartIndex());
stmt.setInt(3, paginationRequest.getRowCount());
}
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
}
// fetching total records count
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
totalRecordsCount = rs.getInt("DEVICE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of devices " +
"with details when pagination is enabled.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(filteredDevicesWithDetails);
paginationResult.setRecordsTotal(totalRecordsCount);
return paginationResult;
}
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
int totalRecordsCount = 0;
try {
con = this.getConnection();
String sql, advancedSqlFiltering = "";
// appending filters if exist, to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
}
}
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?";
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
stmt.setInt(i, paginationRequest.getStartIndex());
stmt.setInt(++i, paginationRequest.getRowCount());
} else {
stmt.setInt(3, paginationRequest.getStartIndex());
stmt.setInt(4, paginationRequest.getRowCount());
}
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
}
// fetching total records count
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
// executing query
rs = stmt.executeQuery();
// fetching query results
while (rs.next()) {
totalRecordsCount = rs.getInt("DEVICE_COUNT");
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of feature non-compliant devices " +
"with details when pagination is enabled.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(filteredDevicesWithDetails);
paginationResult.setRecordsTotal(totalRecordsCount);
return paginationResult;
}
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
try {
con = this.getConnection();
String sql;
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
@ -346,7 +600,64 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting a filtered set of devices with details.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}
return filteredDevicesWithDetails;
}
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException {
Connection con;
PreparedStatement stmt = null;
ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
try {
con = this.getConnection();
String sql;
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
// appending filters to support advanced filtering options
// [1] appending filter columns, if exist
if (filters != null && filters.size() > 0) {
for (String column : filters.keySet()) {
sql = sql + " AND " + column + " = ?";
}
}
stmt = con.prepareStatement(sql);
// [2] appending filter column values, if exist
stmt.setInt(1, tenantId);
stmt.setString(2, nonCompliantFeatureCode);
if (filters != null && filters.values().size() > 0) {
int i = 3;
for (Object value : filters.values()) {
if (value instanceof Integer) {
stmt.setInt(i, (Integer) value);
} else if (value instanceof String) {
stmt.setString(i, (String) value);
}
i++;
}
}
// executing query
rs = stmt.executeQuery();
// fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
@ -354,7 +665,8 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
}
} catch (SQLException e) {
throw new GadgetDataServiceDAOException("Error occurred while executing a selection query to the database", e);
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
"execute relevant SQL queries for getting filtered set of feature non-compliant devices with details.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
}

@ -39,6 +39,7 @@ import org.wso2.carbon.ndatasource.core.DataSourceService;
* unbind="unsetDataSourceService"
*/
public class GadgetDataServiceComponent {
private static final Log log = LogFactory.getLog(GadgetDataServiceComponent.class);
protected void activate(ComponentContext componentContext) {
@ -56,10 +57,10 @@ public class GadgetDataServiceComponent {
componentContext.getBundleContext().
registerService(GadgetDataService.class.getName(), new GadgetDataServiceImpl(), null);
if (log.isDebugEnabled()) {
log.debug("Device Management Dashboard Analytics Bundle has been started successfully");
log.debug("Device Management Dashboard Analytics Bundle has been started successfully.");
}
} catch (Throwable e) {
log.error("Error occurred while initializing the bundle", e);
log.error("Error occurred while initializing the bundle.", e);
}
}
@ -70,11 +71,18 @@ public class GadgetDataServiceComponent {
//do nothing
}
public void setDataSourceService(DataSourceService dataSourceService){
public void setDataSourceService(DataSourceService dataSourceService) {
if (log.isDebugEnabled()) {
log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService...");
}
//do nothing
}
public void unsetDataSourceService(DataSourceService dataSourceService){
public void unsetDataSourceService(DataSourceService dataSourceService) {
if (log.isDebugEnabled()) {
log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService...");
}
//do nothing
}
}

@ -18,13 +18,15 @@
package org.wso2.carbon.device.mgt.analytics.dashboard.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataServiceException;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException;
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
@ -32,19 +34,18 @@ import java.util.Map;
*/
class GadgetDataServiceImpl implements GadgetDataService {
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(GadgetDataServiceImpl.class);
@Override
public int getTotalDeviceCount(Map<String, Object> filters) {
public int getTotalDeviceCount() throws GadgetDataServiceException {
int totalDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
totalDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getTotalDeviceCount(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
totalDeviceCount = -1;
return totalDeviceCount;
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for total device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -52,15 +53,17 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public int getActiveDeviceCount() {
public int getActiveDeviceCount() throws GadgetDataServiceException {
int activeDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
activeDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getActiveDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
activeDeviceCount = -1;
return activeDeviceCount;
activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for active device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -68,15 +71,17 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public int getInactiveDeviceCount() {
public int getInactiveDeviceCount() throws GadgetDataServiceException {
int inactiveDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
inactiveDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getInactiveDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
inactiveDeviceCount = -1;
return inactiveDeviceCount;
inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for inactive device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -84,15 +89,17 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public int getRemovedDeviceCount() {
public int getRemovedDeviceCount() throws GadgetDataServiceException {
int removedDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
removedDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getRemovedDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
removedDeviceCount = -1;
return removedDeviceCount;
removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for removed device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -100,15 +107,17 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public int getNonCompliantDeviceCount() {
public int getNonCompliantDeviceCount() throws GadgetDataServiceException {
int nonCompliantDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getNonCompliantDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
nonCompliantDeviceCount = -1;
return nonCompliantDeviceCount;
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for non-compliant device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -116,15 +125,17 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public int getUnmonitoredDeviceCount() {
public int getUnmonitoredDeviceCount() throws GadgetDataServiceException {
int unmonitoredDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
} catch (GadgetDataServiceDAOException | SQLException e) {
unmonitoredDeviceCount = -1;
return unmonitoredDeviceCount;
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for unmonitored device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -132,29 +143,77 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public Map<String, Integer> getNonCompliantDeviceCountsByFeatures() {
Map<String, Integer> nonCompliantDeviceCountsByFeatures = null;
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
throws GadgetDataServiceException {
PaginationResult paginationResult;
try {
GadgetDataServiceDAOFactory.openConnection();
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getNonCompliantDeviceCountsByFeatures(paginationRequest);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for non-compliant device counts by features.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return paginationResult;
}
@Override
public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceException {
int deviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in calling DAO function for getting a filtered device count.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return deviceCount;
}
@Override
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters)
throws GadgetDataServiceException {
int featureNonCompliantDeviceCount;
try {
GadgetDataServiceDAOFactory.openConnection();
nonCompliantDeviceCountsByFeatures =
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCountsByFeatures();
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting a filtered device count, non compliant by a particular feature.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return nonCompliantDeviceCountsByFeatures;
return featureNonCompliantDeviceCount;
}
@Override
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) {
Map<String, Integer> deviceCountsByPlatforms = null;
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters)
throws GadgetDataServiceException {
Map<String, Integer> deviceCountsByPlatforms;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getDeviceCountsByPlatforms(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getDeviceCountsByPlatforms(filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered device counts by platforms.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
@ -162,18 +221,143 @@ class GadgetDataServiceImpl implements GadgetDataService {
}
@Override
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) {
Map<String, Integer> deviceCountsByOwnershipTypes = null;
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException {
Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getDeviceCountsByOwnershipTypes(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered device counts by platforms, non compliant by a particular feature.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDeviceCountsByPlatforms;
}
@Override
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
throws GadgetDataServiceException {
Map<String, Integer> deviceCountsByOwnershipTypes;
try {
GadgetDataServiceDAOFactory.openConnection();
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getDeviceCountsByOwnershipTypes(filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered device counts by ownership types.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return deviceCountsByOwnershipTypes;
}
@Override
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException {
Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDeviceCountsByOwnershipTypes =
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection.", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered device counts by ownership types, non compliant by a particular feature.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDeviceCountsByOwnershipTypes;
}
@Override
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
PaginationRequest paginationRequest) throws GadgetDataServiceException {
PaginationResult paginationResult;
try {
GadgetDataServiceDAOFactory.openConnection();
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getDevicesWithDetails(filters, paginationRequest);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered devices with details when pagination is enabled.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return paginationResult;
}
@Override
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceException {
PaginationResult paginationResult;
try {
GadgetDataServiceDAOFactory.openConnection();
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, paginationRequest);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered devices with details, non compliant by feature when pagination is enabled.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return paginationResult;
}
@Override
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters)
throws GadgetDataServiceException {
List<Map<String, Object>> devicesWithDetails;
try {
GadgetDataServiceDAOFactory.openConnection();
devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered devices with details.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return devicesWithDetails;
}
@Override
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceException {
List<Map<String, Object>> featureNonCompliantDevicesWithDetails;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters);
} catch (SQLException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
"in opening database connection", e);
} catch (GadgetDataServiceDAOException e) {
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
"for getting filtered devices with details, non compliant by feature.", e);
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDevicesWithDetails;
}
}

@ -1,5 +1,5 @@
/*
* 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
@ -11,12 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -25,12 +25,12 @@ import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.beans.EnrollmentCertificate;
import org.wso2.carbon.mdm.exception.Message;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
import org.wso2.carbon.device.mgt.jaxrs.exception.Message;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
@ -24,9 +24,9 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAppConstants;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
import javax.ws.rs.Consumes;

@ -16,21 +16,24 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@ -231,4 +234,52 @@ public class Device {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}
/**
* Update device.
*
* @return update status.
*/
@PUT
@Path("type/{type}/id/{deviceId}")
public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
org.wso2.carbon.device.mgt.common.Device updatedDevice) {
try {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(deviceType);
deviceIdentifier.setId(deviceId);
org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier);
device.setName(updatedDevice.getName());
device.setDescription(updatedDevice.getDescription());
Boolean response = deviceManagementService.modifyEnrollment(device);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
/**
* disenroll device.
*
* @return disenrollment status.
*/
@DELETE
@Path("type/{type}/id/{deviceId}")
public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) {
try {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setType(deviceType);
deviceIdentifier.setId(deviceId);
Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
String msg = "Error occurred while fetching the list of device types.";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
}

@ -17,7 +17,7 @@
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -26,7 +26,7 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@ -16,15 +16,15 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;

@ -17,7 +17,7 @@
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.GET;
import javax.ws.rs.core.Response;

@ -16,13 +16,13 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;

@ -16,20 +16,20 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@ -141,6 +141,26 @@ public class Group {
}
}
@Path("/all")
@GET
@Produces("application/json")
public Response getAllGroups() {
try {
GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils
.getGroupManagementProviderService();
PaginationResult paginationResult = groupManagementProviderService
.getGroups(0, groupManagementProviderService.getGroupCount());
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult.getData()).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Path("/user/{user}")
@GET
@Produces("application/json")
@ -364,16 +384,18 @@ public class Group {
}
@GET
@Path("/owner/{owner}/name/{groupName}/devices/all")
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
public Response getDevices(@PathParam("groupName") String groupName,
@PathParam("owner") String owner) {
public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
try {
List<Device> devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices(
groupName, owner);
Device[] deviceArray = new Device[devices.size()];
devices.toArray(deviceArray);
return Response.status(Response.Status.OK).entity(deviceArray).build();
PaginationResult paginationResult = DeviceMgtAPIUtils
.getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length);
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -394,15 +416,12 @@ public class Group {
}
}
@PUT
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
@POST
@Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json")
public Response addDevice(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType,
@FormParam("userName") String userName) {
@PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
deviceIdentifier, groupName, owner);
if (isAdded) {

@ -16,14 +16,14 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.GET;
import javax.ws.rs.POST;

@ -16,11 +16,16 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
@ -31,14 +36,9 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.context.DeviceOperationContext;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.MDMAndroidOperationUtil;
import org.wso2.carbon.mdm.api.util.MDMIOSOperationUtil;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.ApplicationWrapper;
import org.wso2.carbon.mdm.beans.MobileApp;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;

@ -16,18 +16,18 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.PolicyWrapper;
import org.wso2.carbon.mdm.beans.PriorityUpdatedPolicyWrapper;
import org.wso2.carbon.mdm.util.MDMUtil;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
@ -62,7 +62,7 @@ public class Policy {
policy.setPolicyName(policyWrapper.getPolicyName());
policy.setProfileId(policyWrapper.getProfileId());
policy.setDescription(policyWrapper.getDescription());
policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile()));
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
policy.setOwnershipType(policyWrapper.getOwnershipType());
policy.setRoles(policyWrapper.getRoles());
policy.setUsers(policyWrapper.getUsers());
@ -82,7 +82,7 @@ public class Policy {
policy.setPolicyName(policyWrapper.getPolicyName());
policy.setProfileId(policyWrapper.getProfileId());
policy.setDescription(policyWrapper.getDescription());
policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile()));
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
policy.setOwnershipType(policyWrapper.getOwnershipType());
policy.setRoles(policyWrapper.getRoles());
policy.setUsers(policyWrapper.getUsers());
@ -181,7 +181,7 @@ public class Policy {
policy.setId(policyId);
policy.setProfileId(policyWrapper.getProfileId());
policy.setDescription(policyWrapper.getDescription());
policy.setProfile(MDMUtil.convertProfile(policyWrapper.getProfile()));
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
policy.setOwnershipType(policyWrapper.getOwnershipType());
policy.setRoles(policyWrapper.getRoles());
policy.setUsers(policyWrapper.getUsers());

@ -16,12 +16,12 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;

@ -16,18 +16,18 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.RoleWrapper;
import org.wso2.carbon.mdm.util.SetReferenceTransformer;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.AuthorizationManager;
import org.wso2.carbon.user.api.Permission;
import org.wso2.carbon.user.api.UserRealm;

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.api;
package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
@ -24,18 +24,18 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.api.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.mdm.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.mdm.api.util.ResponsePayload;
import org.wso2.carbon.mdm.beans.UserCredentialWrapper;
import org.wso2.carbon.mdm.beans.UserWrapper;
import org.wso2.carbon.mdm.util.Constants;
import org.wso2.carbon.mdm.util.SetReferenceTransformer;
import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;

@ -1,5 +1,5 @@
/*
* 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
@ -11,11 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api.common;
package org.wso2.carbon.device.mgt.jaxrs.api.common;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

@ -1,5 +1,5 @@
/*
* 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
@ -11,11 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api.common;
package org.wso2.carbon.device.mgt.jaxrs.api.common;
public class ErrorMessage {

@ -1,5 +1,5 @@
/*
* 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
@ -11,12 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api.common;
package org.wso2.carbon.device.mgt.jaxrs.api.common;
/**
* Custom exception class for handling CDM API related exceptions.

@ -1,5 +1,5 @@
/*
* 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
@ -11,12 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api.context;
package org.wso2.carbon.device.mgt.jaxrs.api.context;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;

@ -16,14 +16,14 @@
* under the License.
*/
package org.wso2.carbon.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.beans.UserCredentialWrapper;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;

@ -16,13 +16,14 @@
* under the License.
*/
package org.wso2.carbon.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
@ -34,7 +35,6 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;

@ -1,5 +1,5 @@
/*
* 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
@ -11,17 +11,20 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
import org.wso2.carbon.device.mgt.jaxrs.beans.android.AppStoreApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.android.EnterpriseApplication;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.beans.MobileApp;
import org.wso2.carbon.mdm.beans.android.WebApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.android.WebApplication;
/**
*
@ -45,15 +48,15 @@ public class MDMAndroidOperationUtil {
switch (application.getType()) {
case ENTERPRISE:
org.wso2.carbon.mdm.beans.android.EnterpriseApplication enterpriseApplication =
new org.wso2.carbon.mdm.beans.android.EnterpriseApplication();
EnterpriseApplication enterpriseApplication =
new EnterpriseApplication();
enterpriseApplication.setType(application.getType().toString());
enterpriseApplication.setUrl(application.getLocation());
operation.setPayLoad(enterpriseApplication.toJSON());
break;
case PUBLIC:
org.wso2.carbon.mdm.beans.android.AppStoreApplication appStoreApplication =
new org.wso2.carbon.mdm.beans.android.AppStoreApplication();
AppStoreApplication appStoreApplication =
new AppStoreApplication();
appStoreApplication.setType(application.getType().toString());
appStoreApplication.setAppIdentifier(application.getIdentifier());
operation.setPayLoad(appStoreApplication.toJSON());
@ -86,15 +89,15 @@ public class MDMAndroidOperationUtil {
switch (application.getType()) {
case ENTERPRISE:
org.wso2.carbon.mdm.beans.android.EnterpriseApplication enterpriseApplication =
new org.wso2.carbon.mdm.beans.android.EnterpriseApplication();
EnterpriseApplication enterpriseApplication =
new EnterpriseApplication();
enterpriseApplication.setType(application.getType().toString());
enterpriseApplication.setAppIdentifier(application.getAppIdentifier());
operation.setPayLoad(enterpriseApplication.toJSON());
break;
case PUBLIC:
org.wso2.carbon.mdm.beans.android.AppStoreApplication appStoreApplication =
new org.wso2.carbon.mdm.beans.android.AppStoreApplication();
AppStoreApplication appStoreApplication =
new AppStoreApplication();
appStoreApplication.setType(application.getType().toString());
appStoreApplication.setAppIdentifier(application.getAppIdentifier());
operation.setPayLoad(appStoreApplication.toJSON());

@ -1,20 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* 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
*
* 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.
* 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.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
/**
* This class holds all the constants used for IOS and Android.

@ -1,26 +1,31 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* 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
*
* 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.
* 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.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.AppStoreApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.EnterpriseApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.RemoveApplication;
import org.wso2.carbon.device.mgt.jaxrs.beans.ios.WebClip;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import org.wso2.carbon.mdm.beans.MobileApp;
import org.wso2.carbon.mdm.beans.ios.WebClip;
import java.util.Properties;
@ -43,8 +48,8 @@ public class MDMIOSOperationUtil {
switch (application.getType()) {
case ENTERPRISE:
org.wso2.carbon.mdm.beans.ios.EnterpriseApplication enterpriseApplication =
new org.wso2.carbon.mdm.beans.ios.EnterpriseApplication();
EnterpriseApplication enterpriseApplication =
new EnterpriseApplication();
enterpriseApplication.setBundleId(application.getId());
enterpriseApplication.setIdentifier(application.getIdentifier());
enterpriseApplication.setManifestURL(application.getLocation());
@ -59,8 +64,8 @@ public class MDMIOSOperationUtil {
operation.setType(Operation.Type.COMMAND);
break;
case PUBLIC:
org.wso2.carbon.mdm.beans.ios.AppStoreApplication appStoreApplication =
new org.wso2.carbon.mdm.beans.ios.AppStoreApplication();
AppStoreApplication appStoreApplication =
new AppStoreApplication();
appStoreApplication.setRemoveAppUponMDMProfileRemoval((Boolean) application.getProperties().
get(MDMAppConstants.IOSConstants.IS_REMOVE_APP));
appStoreApplication.setIdentifier(application.getIdentifier());
@ -96,8 +101,8 @@ public class MDMIOSOperationUtil {
operation.setCode(MDMAppConstants.IOSConstants.OPCODE_REMOVE_APPLICATION);
operation.setType(Operation.Type.PROFILE);
org.wso2.carbon.mdm.beans.ios.RemoveApplication removeApplication =
new org.wso2.carbon.mdm.beans.ios.RemoveApplication();
RemoveApplication removeApplication =
new RemoveApplication();
removeApplication.setBundleId(application.getIdentifier());
operation.setPayLoad(removeApplication.toJSON());

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.api.util;
package org.wso2.carbon.device.mgt.jaxrs.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@ -1,23 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* 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
* specific language governing permissions and limitations
* under the License.
* 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.mdm.beans;
package org.wso2.carbon.device.mgt.jaxrs.beans;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.util.List;

@ -1,5 +1,5 @@
/*
* 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
@ -11,14 +11,13 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.beans;
import java.util.HashMap;
import java.util.Map;
package org.wso2.carbon.device.mgt.jaxrs.beans;
import java.util.Properties;
/**

@ -1,5 +1,5 @@
/*
* 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
@ -11,11 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.beans;
package org.wso2.carbon.device.mgt.jaxrs.beans;
public enum MobileAppTypes {
ENTERPRISE,WEBAPP,PUBLIC

@ -1,5 +1,5 @@
/*
* 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
@ -11,12 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.beans;
package org.wso2.carbon.device.mgt.jaxrs.beans;
import org.wso2.carbon.device.mgt.common.Device;
import java.util.List;

@ -1,22 +1,22 @@
/*
* 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.
*/
package org.wso2.carbon.mdm.beans;
package org.wso2.carbon.device.mgt.jaxrs.beans;
public class PriorityUpdatedPolicyWrapper {

@ -1,22 +1,22 @@
/*
* 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.mdm.beans;
* 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.beans;

@ -1,26 +1,25 @@
/*
* Copyright (c) 2015 WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.beans;
* 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.beans;
import com.google.gson.Gson;
import java.io.Serializable;
import java.util.LinkedHashMap;
public class ProfileFeature implements Serializable {

@ -1,24 +1,25 @@
package org.wso2.carbon.mdm.beans;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
/*
* 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.
*/
package org.wso2.carbon.device.mgt.jaxrs.beans;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
public class RoleWrapper {
private String roleName;
private String[] permissions;

@ -1,22 +1,22 @@
/*
* 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.
*/
package org.wso2.carbon.mdm.beans;
package org.wso2.carbon.device.mgt.jaxrs.beans;
public class UserCredentialWrapper {

@ -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.jaxrs.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
/**
* This class represents the Appstore Application information.
*/
public class AppStoreApplication implements Serializable {
private String type;
private String appIdentifier;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -0,0 +1,63 @@
/*
* 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.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
/**
* This class represents the Enterprise Application information.
*/
public class EnterpriseApplication implements Serializable {
private String type;
private String url;
private String appIdentifier;
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -0,0 +1,63 @@
/*
* 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.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
/**
* This class represents the Web Application information.
*/
public class WebApplication implements Serializable {
private String name;
private String url;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,5 +1,5 @@
/*
* 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
@ -11,15 +11,16 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.beans.ios;
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
public class AppStoreApplication implements Serializable {

@ -1,5 +1,5 @@
/*
* 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
@ -11,16 +11,16 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.mdm.beans.ios;
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
public class EnterpriseApplication implements Serializable {

@ -16,20 +16,27 @@
* under the License.
*/
function onRequest(context) {
var groupId = request.getParameter("groupId");
var title;
if (groupId) {
title = request.getParameter("groupName") + " Group";
} else {
groupId = 0;
var deviceId = request.getParameter("deviceId");
var deviceType = request.getParameter("deviceType");
var deviceName = request.getParameter("deviceName");
//title = deviceModule.getDevice(deviceType, deviceId).name;
title = deviceName;
package org.wso2.carbon.device.mgt.jaxrs.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
import java.io.Serializable;
public class RemoveApplication implements Serializable {
private String bundleId;
public String getBundleId() {
return bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
return {"title": title, "groupId": groupId};
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,8 +1,25 @@
package org.wso2.carbon.mdm.beans.ios;
/*
* 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.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
public class WebClip {

@ -1,23 +1,22 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* 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
* specific language governing permissions and limitations
* under the License.
* 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.mdm.common;
package org.wso2.carbon.device.mgt.jaxrs.common;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;

@ -1,5 +1,5 @@
/*
* Copyright (c) 2014, 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
@ -11,12 +11,12 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.mdm.common;
package org.wso2.carbon.device.mgt.jaxrs.common;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.exception;
package org.wso2.carbon.device.mgt.jaxrs.exception;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.mdm.util;
package org.wso2.carbon.device.mgt.jaxrs.util;
/**
* Holds the constants used by Device Management Admin web application.

@ -15,17 +15,18 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.mdm.util;
import org.wso2.carbon.mdm.beans.ProfileFeature;
package org.wso2.carbon.device.mgt.jaxrs.util;
import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature;
import org.wso2.carbon.policy.mgt.common.Profile;
import java.util.ArrayList;
import java.util.List;
public class MDMUtil {
public class DeviceMgtUtil {
public static Profile convertProfile(org.wso2.carbon.mdm.beans.Profile mdmProfile) {
public static Profile convertProfile(org.wso2.carbon.device.mgt.jaxrs.beans.Profile mdmProfile) {
Profile profile = new Profile();
profile.setTenantId(mdmProfile.getTenantId());
profile.setCreatedDate(mdmProfile.getCreatedDate());

@ -1,52 +0,0 @@
/*
*
* Copyright (c) 2015, 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.mdm.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import java.io.Serializable;
/**
* This class represents the Appstore Application information.
*/
public class AppStoreApplication implements Serializable {
private String type;
private String appIdentifier;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,61 +0,0 @@
/*
*
* Copyright (c) 2015, 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.mdm.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import java.io.Serializable;
/**
* This class represents the Enterprise Application information.
*/
public class EnterpriseApplication implements Serializable {
private String type;
private String url;
private String appIdentifier;
public String getAppIdentifier() {
return appIdentifier;
}
public void setAppIdentifier(String appIdentifier) {
this.appIdentifier = appIdentifier;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,61 +0,0 @@
/*
*
* Copyright (c) 2015, 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.mdm.beans.android;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import java.io.Serializable;
/**
* This class represents the Web Application information.
*/
public class WebApplication implements Serializable {
private String name;
private String url;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -1,24 +0,0 @@
package org.wso2.carbon.mdm.beans.ios;
import com.google.gson.Gson;
import org.wso2.carbon.mdm.api.common.MDMAPIException;
import java.io.IOException;
import java.io.Serializable;
public class RemoveApplication implements Serializable {
private String bundleId;
public String getBundleId() {
return bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
public String toJSON() throws MDMAPIException {
Gson gson = new Gson();
return gson.toJson(this);
}
}

@ -206,6 +206,20 @@
<method>GET</method>
</Permission>
<Permission>
<name>Modify user device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/type/*/id/*</url>
<method>PUT</method>
</Permission>
<Permission>
<name>Remove user device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/type/*/id/*</url>
<method>DELETE</method>
</Permission>
<!--<Permission>-->
<!--<name>Get device</name>-->
<!--<path>/device-mgt/devices/view</path>-->
@ -241,6 +255,13 @@
<url>/devices/name/*/*</url>
<method>GET</method>
</Permission>
<Permission>
<name>List All Own Devices</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/user/*</url>
<method>GET</method>
</Permission>
<!-- End of Device related APIs -->
<!-- Notification related APIs -->
@ -938,12 +959,19 @@
</Permission>
<Permission>
<name>List All Groups</name>
<name>List All Groups with Pagination</name>
<path>/device-mgt/admin/groups/list</path>
<url>/groups</url>
<method>GET</method>
</Permission>
<Permission>
<name>List All Groups</name>
<path>/device-mgt/admin/groups/list</path>
<url>/groups/all</url>
<method>GET</method>
</Permission>
<Permission>
<name>List Groups</name>
<path>/device-mgt/user/groups/list</path>
@ -1059,7 +1087,7 @@
<Permission>
<name>List Group Devices</name>
<path>/device-mgt/user/groups/devices/list</path>
<url>/groups/owner/*/name/*/devices/all</url>
<url>/groups/owner/*/name/*/devices</url>
<method>GET</method>
</Permission>
@ -1073,8 +1101,8 @@
<Permission>
<name>Add Device to Group</name>
<path>/device-mgt/user/groups/devices/add</path>
<url>/groups/owner/*/name/*/devices/*/*</url>
<method>PUT</method>
<url>/groups/owner/*/name/*/devices</url>
<method>POST</method>
</Permission>
<Permission>

@ -163,26 +163,24 @@
</jaxrs:providers>
</jaxrs:server>
-->
<bean id="operationServiceBean" class="org.wso2.carbon.mdm.api.Operation"/>
<bean id="deviceServiceBean" class="org.wso2.carbon.mdm.api.Device"/>
<bean id="groupServiceBean" class="org.wso2.carbon.mdm.api.Group"/>
<bean id="userServiceBean" class="org.wso2.carbon.mdm.api.User"/>
<bean id="roleServiceBean" class="org.wso2.carbon.mdm.api.Role"/>
<bean id="featureServiceBean" class="org.wso2.carbon.mdm.api.Feature"/>
<bean id="configurationServiceBean" class="org.wso2.carbon.mdm.api.Configuration"/>
<bean id="notificationServiceBean" class="org.wso2.carbon.mdm.api.DeviceNotification"/>
<bean id="licenseServiceBean" class="org.wso2.carbon.mdm.api.License"/>
<bean id="certificateServiceBean" class="org.wso2.carbon.mdm.api.Certificate"/>
<bean id="informationServiceBean" class="org.wso2.carbon.mdm.api.DeviceInformation"/>
<bean id="searchingServiceBean" class="org.wso2.carbon.mdm.api.DeviceSearch"/>
<bean id="operationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Operation"/>
<bean id="deviceServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Device"/>
<bean id="groupServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Group"/>
<bean id="userServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.User"/>
<bean id="roleServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Role"/>
<bean id="featureServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Feature"/>
<bean id="configurationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Configuration"/>
<bean id="notificationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceNotification"/>
<bean id="licenseServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.License"/>
<bean id="certificateServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Certificate"/>
<bean id="informationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation"/>
<bean id="searchingServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceSearch"/>
<!--
<bean id="authenticationServiceBean" class="org.wso2.carbon.mdm.api.Authentication"/>
<bean id="authenticationServiceBean" class="Authentication"/>
-->
<bean id="policyServiceBean" class="org.wso2.carbon.mdm.api.Policy"/>
<bean id="profileServiceBean" class="org.wso2.carbon.mdm.api.Profile"/>
<bean id="jsonProvider" class="org.wso2.mdm.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.mdm.api.common.ErrorHandler"/>
<bean id="policyServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Policy"/>
<bean id="profileServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Profile"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.api.common.ErrorHandler"/>
</beans>

@ -0,0 +1,39 @@
/*
* 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;
public class ProvisioningConfig {
private String providerTenantDomain;
private boolean isSharedWithAllTenants;
public ProvisioningConfig(String providerTenantDomain, boolean sharedWithAllTenants) {
this.providerTenantDomain = providerTenantDomain;
isSharedWithAllTenants = sharedWithAllTenants;
}
public String getProviderTenantDomain() {
return providerTenantDomain;
}
public boolean isSharedWithAllTenants() {
return isSharedWithAllTenants;
}
}

@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@ -51,6 +52,7 @@ public class DeviceInfo implements Serializable {
private Double totalRAMMemory;
private Double availableRAMMemory;
private boolean pluggedIn;
private Date updatedTime;
private Map<String, String> deviceDetailsMap = new HashMap<>();
@ -290,6 +292,17 @@ public class DeviceInfo implements Serializable {
this.pluggedIn = pluggedIn;
}
public Date getUpdatedTime() {
if(updatedTime.equals(null)){
updatedTime = new Date();
}
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
public void setDeviceDetailsMap(Map<String, String> deviceDetailsMap) {
this.deviceDetailsMap = deviceDetailsMap;
}

@ -22,6 +22,7 @@ package org.wso2.carbon.device.mgt.common.device.details;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import java.io.Serializable;
import java.util.Date;
public class DeviceLocation implements Serializable {
@ -39,6 +40,7 @@ public class DeviceLocation implements Serializable {
private String state;
private String zip;
private String country;
private Date updatedTime;
public int getDeviceId() {
return deviceId;
@ -119,5 +121,16 @@ public class DeviceLocation implements Serializable {
public void setCountry(String country) {
this.country = country;
}
public Date getUpdatedTime() {
if(updatedTime.equals(null)){
updatedTime = new Date();
}
return updatedTime;
}
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
}

@ -28,6 +28,7 @@ import java.util.List;
@XmlRootElement
public class DeviceGroup implements Serializable {
private int id;
private String description;
private String name;
private Long dateOfCreation;
@ -36,6 +37,15 @@ public class DeviceGroup implements Serializable {
private List<GroupUser> users;
private List<String> roles;
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getDescription() {
return description;
@ -101,6 +111,7 @@ public class DeviceGroup implements Serializable {
protected DeviceGroup getGroup() {
DeviceGroup deviceGroup = new DeviceGroup();
deviceGroup.setId(getId());
deviceGroup.setDescription(getDescription());
deviceGroup.setName(getName());
deviceGroup.setDateOfCreation(getDateOfCreation());

@ -31,7 +31,11 @@ public class Operation implements Serializable {
}
public enum Status {
IN_PROGRESS, PENDING, COMPLETED, ERROR
IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED
}
public enum Control {
REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE
}
private String code;
@ -39,11 +43,13 @@ public class Operation implements Serializable {
private Type type;
private int id;
private Status status;
private Control control;
private String receivedTimeStamp;
private String createdTimeStamp;
private boolean isEnabled;
private Object payLoad;
private String operationResponse;
private String activityId;
@Override
public boolean equals(Object o) {
@ -87,6 +93,11 @@ public class Operation implements Serializable {
if (status != operation.status) {
return false;
}
if(control != operation.control){
return false;
}
if (type != operation.type) {
return false;
}
@ -151,6 +162,14 @@ public class Operation implements Serializable {
this.status = status;
}
public Control getControl() {
return control;
}
public void setControl(Control control) {
this.control = control;
}
public String getReceivedTimeStamp() {
return receivedTimeStamp;
}
@ -191,6 +210,14 @@ public class Operation implements Serializable {
this.operationResponse = operationResponse;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String toString() {
return "Operation{" +
@ -198,6 +225,7 @@ public class Operation implements Serializable {
", type=" + type +
", id=" + id +
", status=" + status +
", control=" + control +
", receivedTimeStamp='" + receivedTimeStamp + '\'' +
", createdTimeStamp='" + createdTimeStamp + '\'' +
", isEnabled=" + isEnabled +

@ -85,4 +85,6 @@ public interface OperationManager {
Operation getOperation(int operationId) throws OperationManagementException;
Operation getOperationByActivityId(String activity) throws OperationManagementException;
}

@ -0,0 +1,41 @@
/*
* 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.push.notification;
import java.util.Set;
public class PushNotificationConfig {
private String type;
private Set<String> properties;
public PushNotificationConfig(String type, Set<String> properties) {
this.type = type;
this.properties = properties;
}
public String getType() {
return type;
}
public Set<String> getProperties() {
return properties;
}
}

@ -18,13 +18,11 @@
*/
package org.wso2.carbon.device.mgt.common.spi;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import java.util.List;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
/**
* Composite interface that acts as the SPI exposing all device management as well as application management
@ -32,33 +30,16 @@ import java.util.List;
*/
public interface DeviceManagementService {
/**
* Method to retrieve the provider type that implements DeviceManager interface.
*
* @return Returns provider type
*/
String getType();
/**
* This returns the tenant domain of the provider.
* @return
*/
String getProviderTenantDomain();
/**
* returns true if the device type is shared between all tenants and false if its not.
*
* @return
*/
boolean isSharedWithAllTenants();
void init() throws DeviceManagementException;
String getType();
DeviceManager getDeviceManager();
ApplicationManager getApplicationManager();
void notifyOperationToDevices(Operation operation,
List<DeviceIdentifier> deviceIds) throws DeviceManagementException;
ProvisioningConfig getProvisioningConfig();
PushNotificationConfig getPushNotificationConfig();
}

@ -75,4 +75,9 @@ public final class DeviceManagementConstants {
public static final String DOWNLOAD_URL = "download-url";
}
public static final class OperationAttributes {
private OperationAttributes() {throw new AssertionError(); }
public static final String ACTIVITY = "ACTIVITY_";
}
}

@ -21,6 +21,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceTypeIdentifier;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
@ -44,8 +45,10 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
public void addDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException {
String deviceType = provider.getType();
String tenantDomain = provider.getProviderTenantDomain();
boolean isSharedWithAllTenants = provider.isSharedWithAllTenants();
ProvisioningConfig provisioningConfig = provider.getProvisioningConfig();
String tenantDomain = provisioningConfig.getProviderTenantDomain();
boolean isSharedWithAllTenants = provisioningConfig.isSharedWithAllTenants();
int tenantId = DeviceManagerUtil.getTenantId(tenantDomain);
if (tenantId == -1) {
throw new DeviceManagementException("No tenant available for tenant domain " + tenantDomain);
@ -57,7 +60,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
provider.init();
DeviceManagerUtil.registerDeviceType(deviceType, tenantId, isSharedWithAllTenants);
DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(deviceType,
provider.getDeviceManager().requireDeviceAuthorization());
provider.getDeviceManager().requireDeviceAuthorization());
}
} catch (DeviceManagementException e) {
@ -75,13 +78,15 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
}
public void removeDeviceManagementProvider(DeviceManagementService provider) throws DeviceManagementException {
String deviceTypeName=provider.getType();
if(provider.isSharedWithAllTenants()){
DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName);
String deviceTypeName = provider.getType();
ProvisioningConfig provisioningConfig = provider.getProvisioningConfig();
if (provisioningConfig.isSharedWithAllTenants()) {
DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName);
providers.remove(deviceTypeIdentifier);
}else{
int providerTenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain());
DeviceTypeIdentifier deviceTypeIdentifier =new DeviceTypeIdentifier(deviceTypeName, providerTenantId);
} else {
int providerTenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain());
DeviceTypeIdentifier deviceTypeIdentifier = new DeviceTypeIdentifier(deviceTypeName, providerTenantId);
providers.remove(deviceTypeIdentifier);
}
}
@ -113,15 +118,17 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
for (DeviceManagementService provider : providers.values()) {
try {
provider.init();
int tenantId=DeviceManagerUtil.getTenantId(provider.getProviderTenantDomain());
DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provider.isSharedWithAllTenants());
ProvisioningConfig provisioningConfig = provider.getProvisioningConfig();
int tenantId = DeviceManagerUtil.getTenantId(provisioningConfig.getProviderTenantDomain());
DeviceManagerUtil.registerDeviceType(provider.getType(), tenantId, provisioningConfig.isSharedWithAllTenants());
//TODO:
//This is a temporory fix.
//windows and IOS cannot resolve user info by extracting certs
//until fix that, use following variable to enable and disable of checking user authorization.
DeviceManagementDataHolder.getInstance().setRequireDeviceAuthorization(provider.getType(),
provider.getDeviceManager().requireDeviceAuthorization());
provider.getDeviceManager().requireDeviceAuthorization());
} catch (Throwable e) {
/* Throwable is caught intentionally as failure of one plugin - due to invalid start up parameters,
etc - should not block the initialization of other device management providers */

@ -32,16 +32,13 @@ import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
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.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.app.mgt.oauth.ServiceAuthenticator;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.dao.*;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
@ -56,9 +53,6 @@ import java.util.List;
*/
public class ApplicationManagerProviderServiceImpl implements ApplicationManagementProviderService {
private ConfigurationContext configCtx;
private ServiceAuthenticator authenticator;
private String oAuthAdminServiceUrl;
private DeviceDAO deviceDAO;
private ApplicationDAO applicationDAO;
private ApplicationMappingDAO applicationMappingDAO;
@ -67,19 +61,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
private static final Log log = LogFactory.getLog(ApplicationManagerProviderServiceImpl.class);
public ApplicationManagerProviderServiceImpl(AppManagementConfig appManagementConfig) {
IdentityConfigurations identityConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getDeviceManagementConfigRepository().getIdentityConfigurations();
this.authenticator =
new ServiceAuthenticator(identityConfig.getAdminUsername(), identityConfig.getAdminPassword());
this.oAuthAdminServiceUrl =
identityConfig.getServerUrl() + DeviceManagementConstants.AppManagement.OAUTH_ADMIN_SERVICE;
try {
this.configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
} catch (AxisFault e) {
throw new IllegalArgumentException("Error occurred while initializing Axis2 Configuration Context. " +
"Please check if an appropriate axis2.xml is provided", e);
}
this.deviceDAO = DeviceManagementDAOFactory.getDeviceDAO();
this.applicationDAO = DeviceManagementDAOFactory.getApplicationDAO();
this.applicationMappingDAO = DeviceManagementDAOFactory.getApplicationMappingDAO();
@ -112,7 +93,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> deviceIds)
throws ApplicationManagementException {
try {
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().addOperation(operation, deviceIds);
DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().notifyOperationToDevices
@ -207,50 +187,6 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
}
}
public void updateInstalledApplicationListOfDevice(
DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException {
}
private OAuthConsumerAppDTO getAppInfo() throws ApplicationManagementException {
OAuthConsumerAppDTO appInfo = null;
try {
OAuthAdminServiceStub oAuthAdminServiceStub =
new OAuthAdminServiceStub(configCtx, oAuthAdminServiceUrl);
authenticator.authenticate(oAuthAdminServiceStub._getServiceClient());
try {
appInfo = oAuthAdminServiceStub.getOAuthApplicationDataByAppName(
DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME);
}
//application doesn't exist. Due to the way getOAuthApplicationDataByAppName has been
//implemented, it throws an AxisFault if the App doesn't exist. Hence the catch.
catch (AxisFault fault) {
oAuthAdminServiceStub.registerOAuthApplicationData(this.getRequestDTO());
appInfo = oAuthAdminServiceStub.getOAuthApplicationDataByAppName(
DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME);
}
} catch (RemoteException e) {
handleException("Error occurred while retrieving app info", e);
} catch (OAuthAdminServiceException e) {
handleException("Error occurred while invoking OAuth admin service stub", e);
}
return appInfo;
}
private OAuthConsumerAppDTO getRequestDTO() {
OAuthConsumerAppDTO appDTO = new OAuthConsumerAppDTO();
appDTO.setApplicationName(DeviceManagementConstants.AppManagement.OAUTH_APPLICATION_NAME);
appDTO.setGrantTypes(
DeviceManagementConstants.AppManagement.OAUTH2_GRANT_TYPE_CLIENT_CREDENTIALS);
appDTO.setOAuthVersion(DeviceManagementConstants.AppManagement.OAUTH_VERSION_2);
return appDTO;
}
private void handleException(String msg, Exception e) throws ApplicationManagementException {
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
@Override
public void updateApplicationListInstalledInDevice(
DeviceIdentifier deviceIdentifier, List<Application> applications) throws ApplicationManagementException {

@ -17,8 +17,14 @@
*/
package org.wso2.carbon.device.mgt.core.config;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
import org.wso2.carbon.device.mgt.core.config.policy.PolicyConfiguration;
import org.wso2.carbon.device.mgt.core.config.task.TaskConfiguration;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.List;
/**
* Represents Device Mgt configuration.
@ -27,6 +33,10 @@ import javax.xml.bind.annotation.XmlRootElement;
public final class DeviceManagementConfig {
private DeviceManagementConfigRepository deviceManagementConfigRepository;
private TaskConfiguration taskConfiguration;
private IdentityConfigurations identityConfigurations;
private PolicyConfiguration policyConfiguration;
//private List<String> pushNotificationProviders;
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@ -37,4 +47,43 @@ public final class DeviceManagementConfig {
this.deviceManagementConfigRepository = deviceManagementConfigRepository;
}
@XmlElement(name = "IdentityConfiguration", required = true)
public IdentityConfigurations getIdentityConfigurations() {
return identityConfigurations;
}
public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) {
this.identityConfigurations = identityConfigurations;
}
@XmlElement(name = "PolicyConfiguration", required = true)
public PolicyConfiguration getPolicyConfiguration() {
return policyConfiguration;
}
public void setPolicyConfiguration(PolicyConfiguration policyConfiguration) {
this.policyConfiguration = policyConfiguration;
}
@XmlElement(name = "TaskConfiguration", required = true)
public TaskConfiguration getTaskConfiguration() {
return taskConfiguration;
}
public void setTaskConfiguration(TaskConfiguration taskConfiguration) {
this.taskConfiguration = taskConfiguration;
}
// @XmlElementWrapper(name = "PushNotificationProviders", required = true)
// @XmlElement(name = "Provider", required = true)
// public List<String> getPushNotificationProviders() {
// return pushNotificationProviders;
// }
//
// public void setPushNotificationProviders(List<String> pushNotificationProviders) {
// this.pushNotificationProviders = pushNotificationProviders;
// }
}

@ -31,12 +31,7 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "ManagementRepository")
public class DeviceManagementConfigRepository {
// private EmailConfigurations emailConfigurations;
private TaskConfiguration taskConfiguration;
private DataSourceConfig dataSourceConfig;
private IdentityConfigurations identityConfigurations;
private PolicyConfiguration policyConfiguration;
@XmlElement(name = "DataSourceConfiguration", required = true)
public DataSourceConfig getDataSourceConfig() {
@ -47,40 +42,4 @@ public class DeviceManagementConfigRepository {
this.dataSourceConfig = dataSourceConfig;
}
// @XmlElement(name = "EmailClientConfiguration", required = true)
// public EmailConfigurations getEmailConfigurations() {
// return emailConfigurations;
// }
//
// public void setEmailConfigurations(EmailConfigurations emailConfigurations) {
// this.emailConfigurations = emailConfigurations;
// }
@XmlElement(name = "IdentityConfiguration", required = true)
public IdentityConfigurations getIdentityConfigurations() {
return identityConfigurations;
}
public void setIdentityConfigurations(IdentityConfigurations identityConfigurations) {
this.identityConfigurations = identityConfigurations;
}
@XmlElement(name = "PolicyConfiguration", required = true)
public PolicyConfiguration getPolicyConfiguration() {
return policyConfiguration;
}
public void setPolicyConfiguration(PolicyConfiguration policyConfiguration) {
this.policyConfiguration = policyConfiguration;
}
@XmlElement(name = "TaskConfiguration", required = true)
public TaskConfiguration getTaskConfiguration() {
return taskConfiguration;
}
public void setTaskConfiguration(TaskConfiguration taskConfiguration) {
this.taskConfiguration = taskConfiguration;
}
}

@ -45,23 +45,23 @@ 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 Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class);
private static final String PERMISSION_CONFIG_PATH = "META-INF" + File.separator + "permissions.xml";
private static final Log log = LogFactory.getLog(WebAppDeploymentLifecycleListener.class);
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
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) {
@Override
public void lifecycleEvent(LifecycleEvent lifecycleEvent) {
if (Lifecycle.AFTER_START_EVENT.equals(lifecycleEvent.getType())) {
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);
JAXBContext cdmContext = JAXBContext.newInstance(PermissionConfiguration.class);
Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
PermissionConfiguration permissionConfiguration = (PermissionConfiguration)
unmarshaller.unmarshal(permissionStream);
List<Permission> permissions = permissionConfiguration.getPermissions();
String apiVersion = permissionConfiguration.getApiVersion();
if (permissionConfiguration != null && permissions != null) {
@ -69,22 +69,22 @@ public class WebAppDeploymentLifecycleListener implements LifecycleListener {
// update the permission path to absolute permission path
permission.setPath(PermissionUtils.getAbsolutePermissionPath(permission.getPath()));
permission.setUrl(PermissionUtils.getAbsoluteContextPathOfAPI(contextPath, apiVersion,
permission.getUrl()).toLowerCase());
permission.getUrl()).toLowerCase());
permission.setMethod(permission.getMethod().toUpperCase());
PermissionManagerServiceImpl.getInstance().addPermission(permission);
}
}
}
} catch (JAXBException e) {
}
}
} catch (JAXBException e) {
log.error(
"Exception occurred while parsing the permission configuration of webapp : "
+ context.getServletContext().getContextPath(), e);
+ context.getServletContext().getContextPath(), e);
} catch (PermissionManagementException e) {
log.error("Exception occurred while adding the permissions from webapp : "
+ servletContext.getContextPath(), e);
+ servletContext.getContextPath(), e);
}
}
}
}
}

@ -31,7 +31,7 @@ public class PolicyConfiguration {
private int minRetriesToMarkUnreachable;
private int minRetriesToMarkInactive;
@XmlElement(name = "monitoringClass", required = true)
@XmlElement(name = "MonitoringClass", required = true)
public String getMonitoringClass() {
return monitoringClass;
}
@ -40,7 +40,7 @@ public class PolicyConfiguration {
this.monitoringClass = monitoringClass;
}
@XmlElement(name = "maxRetries", required = true)
@XmlElement(name = "MaxRetries", required = true)
public int getMaxRetries() {
return maxRetries;
}
@ -49,7 +49,7 @@ public class PolicyConfiguration {
this.maxRetries = maxRetries;
}
@XmlElement(name = "minRetriesToMarkUnreachable", required = true)
@XmlElement(name = "MinRetriesToMarkUnreachable", required = true)
public int getMinRetriesToMarkUnreachable() {
return minRetriesToMarkUnreachable;
}
@ -58,7 +58,7 @@ public class PolicyConfiguration {
this.minRetriesToMarkUnreachable = minRetriesToMarkUnreachable;
}
@XmlElement(name = "monitoringEnable", required = true)
@XmlElement(name = "MonitoringEnable", required = true)
public boolean getMonitoringEnable() {
return monitoringEnable;
}
@ -67,7 +67,7 @@ public class PolicyConfiguration {
this.monitoringEnable = monitoringEnable;
}
@XmlElement(name = "minRetriesToMarkInactive", required = true)
@XmlElement(name = "MinRetriesToMarkInactive", required = true)
public int getMinRetriesToMarkInactive() {
return minRetriesToMarkInactive;
}
@ -76,7 +76,7 @@ public class PolicyConfiguration {
this.minRetriesToMarkInactive = minRetriesToMarkInactive;
}
@XmlElement(name = "monitoringFrequency", required = true)
@XmlElement(name = "MonitoringFrequency", required = true)
public int getMonitoringFrequency() {
return monitoringFrequency;
}
@ -84,4 +84,5 @@ public class PolicyConfiguration {
public void setMonitoringFrequency(int monitoringFrequency) {
this.monitoringFrequency = monitoringFrequency;
}
}

@ -50,8 +50,8 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_DETAIL (DEVICE_ID, DEVICE_MODEL, " +
"VENDOR, OS_VERSION, BATTERY_LEVEL, INTERNAL_TOTAL_MEMORY, INTERNAL_AVAILABLE_MEMORY, " +
"EXTERNAL_TOTAL_MEMORY, EXTERNAL_AVAILABLE_MEMORY, CONNECTION_TYPE, " +
"SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
"SSID, CPU_USAGE, TOTAL_RAM_MEMORY, AVAILABLE_RAM_MEMORY, PLUGGED_IN, UPDATE_TIMESTAMP) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, deviceInfo.getDeviceId());
stmt.setString(2, deviceInfo.getDeviceModel());
@ -68,6 +68,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
stmt.setDouble(13, deviceInfo.getTotalRAMMemory());
stmt.setDouble(14, deviceInfo.getAvailableRAMMemory());
stmt.setBoolean(15, deviceInfo.isPluggedIn());
stmt.setLong(16, System.currentTimeMillis());
stmt.execute();
@ -83,7 +84,9 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
public void addDeviceProperties(Map<String, String> propertyMap, int deviceId) throws DeviceDetailsMgtDAOException {
if (propertyMap.isEmpty()) {
log.warn("Property map of device id :" + deviceId + " is empty.");
if(log.isDebugEnabled()) {
log.debug("Property map of device id :" + deviceId + " is empty.");
}
return;
}
Connection conn;
@ -142,6 +145,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
deviceInfo.setTotalRAMMemory(rs.getDouble("TOTAL_RAM_MEMORY"));
deviceInfo.setAvailableRAMMemory(rs.getDouble("AVAILABLE_RAM_MEMORY"));
deviceInfo.setPluggedIn(rs.getBoolean("PLUGGED_IN"));
deviceInfo.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP")));
}
deviceInfo.setDeviceId(deviceId);
@ -224,7 +228,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
try {
conn = this.getConnection();
stmt = conn.prepareStatement("INSERT INTO DM_DEVICE_LOCATION (DEVICE_ID, LATITUDE, LONGITUDE, STREET1, " +
"STREET2, CITY, ZIP, STATE, COUNTRY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
"STREET2, CITY, ZIP, STATE, COUNTRY, UPDATE_TIMESTAMP) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setInt(1, deviceLocation.getDeviceId());
stmt.setDouble(2, deviceLocation.getLatitude());
stmt.setDouble(3, deviceLocation.getLongitude());
@ -234,6 +238,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
stmt.setString(7, deviceLocation.getZip());
stmt.setString(8, deviceLocation.getState());
stmt.setString(9, deviceLocation.getCountry());
stmt.setLong(10, System.currentTimeMillis());
stmt.execute();
} catch (SQLException e) {
throw new DeviceDetailsMgtDAOException("Error occurred while adding the device location to database.", e);
@ -266,6 +271,7 @@ public class DeviceDetailsDAOImpl implements DeviceDetailsDAO {
location.setZip(rs.getString("ZIP"));
location.setState(rs.getString("STATE"));
location.setCountry(rs.getString("COUNTRY"));
location.setUpdatedTime(new java.util.Date(rs.getLong("UPDATE_TIMESTAMP")));
}
location.setDeviceId(deviceId);

@ -34,4 +34,8 @@ public class CommandOperation extends Operation {
return Type.COMMAND;
}
public Control getControl(){
return Control.NO_REPEAT;
}
}

@ -77,4 +77,9 @@ public class ConfigOperation extends Operation {
return Type.CONFIG;
}
public Control getControl(){
return Control.REPEAT;
}
}

@ -18,8 +18,6 @@
*/
package org.wso2.carbon.device.mgt.core.dto.operation.mgt;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.Properties;
@ -30,7 +28,11 @@ public class Operation implements Serializable {
}
public enum Status {
IN_PROGRESS, PENDING, COMPLETED, ERROR
IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED
}
public enum Control {
REPEAT, NO_REPEAT, PAUSE_SEQUENCE, STOP_SEQUENCE
}
private String code;
@ -38,6 +40,7 @@ public class Operation implements Serializable {
private Type type;
private int id;
private Status status;
private Control control;
private String receivedTimeStamp;
private String createdTimeStamp;
private boolean isEnabled;
@ -84,6 +87,14 @@ public class Operation implements Serializable {
this.status = status;
}
public Control getControl() {
return control;
}
public void setControl(Control control) {
this.control = control;
}
public String getReceivedTimeStamp() {
return receivedTimeStamp;
}

@ -31,4 +31,8 @@ public class PolicyOperation extends Operation{
private List<ProfileOperation> profileOperations;
public Control getControl(){
return Control.REPEAT;
}
}

@ -26,4 +26,9 @@ public class ProfileOperation extends ConfigOperation implements Serializable {
return Type.PROFILE;
}
public Control getControl(){
return Control.REPEAT;
}
}

@ -36,6 +36,7 @@ public class DeviceGroupBuilder extends DeviceGroup {
* @param deviceGroup to decorate
*/
public DeviceGroupBuilder(DeviceGroup deviceGroup) {
this.setId(deviceGroup.getId());
this.setDescription(deviceGroup.getDescription());
this.setName(deviceGroup.getName());
this.setDateOfCreation(deviceGroup.getDateOfCreation());

@ -82,6 +82,14 @@ public interface GroupDAO {
*/
DeviceGroupBuilder getGroup(String groupName, String owner, int tenantId) throws GroupManagementDAOException;
/**
* Get the groups of device with device id provided
* @param deviceId
* @return
* @throws GroupManagementDAOException
*/
List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException;
/**
* Get the list of Device Groups in tenant.
*

@ -178,6 +178,32 @@ public class GroupDAOImpl implements GroupDAO {
}
}
@Override
public List<DeviceGroupBuilder> getGroups(int deviceId, int tenantId) throws GroupManagementDAOException {
PreparedStatement stmt = null;
ResultSet resultSet = null;
List<DeviceGroupBuilder> deviceGroupBuilders = new ArrayList<>();
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT G.ID, G.GROUP_NAME, G.DESCRIPTION, G.DATE_OF_CREATE, G.DATE_OF_LAST_UPDATE, \n" +
"G.OWNER FROM DM_GROUP AS G INNER JOIN DM_DEVICE_GROUP_MAP AS GM ON G.ID = GM.GROUP_ID " +
"WHERE GM.DEVICE_ID = ? AND GM.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, deviceId);
stmt.setInt(2, tenantId);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
deviceGroupBuilders.add(GroupManagementDAOUtil.loadGroup(resultSet));
}
} catch (SQLException e) {
throw new GroupManagementDAOException("Error occurred while obtaining information of Device Groups ", e);
} finally {
GroupManagementDAOUtil.cleanupResources(stmt, resultSet);
}
return deviceGroupBuilders;
}
@Override
public List<DeviceGroupBuilder> getGroups(int startIndex, int rowCount, int tenantId)
throws GroupManagementDAOException {
@ -356,9 +382,9 @@ public class GroupDAOImpl implements GroupDAO {
ResultSet resultSet = null;
try {
Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID as GROUP_ID " +
String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID " +
"FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " +
"WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?";
"WHERE gm.GROUP_ID = dg.ID AND gm.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName);
stmt.setString(2, owner);

@ -52,8 +52,9 @@ public class DeviceTaskManagerServiceComponent {
log.debug("Initializing device details retrieving task manager bundle.");
}
// This will start the device details retrieving task.
boolean taskEnable = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().
getDeviceManagementConfigRepository().getTaskConfiguration().isEnabled();
boolean taskEnable =
DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getTaskConfiguration().
isEnabled();
if (taskEnable) {
DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl();
taskManagerService.startTask();
@ -70,7 +71,6 @@ public class DeviceTaskManagerServiceComponent {
@SuppressWarnings("unused")
protected void deactivate(ComponentContext componentContext) {
try {
DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl();
taskManagerService.stopTask();
@ -93,6 +93,7 @@ public class DeviceTaskManagerServiceComponent {
}
DeviceManagementDataHolder.getInstance().setTaskService(null);
}
}

@ -35,5 +35,8 @@ public class CommandOperation extends Operation {
public Type getType() {
return Type.COMMAND;
}
public Control getControl(){
return Control.NO_REPEAT;
}
}

@ -78,4 +78,8 @@ public class ConfigOperation extends Operation {
return Type.CONFIG;
}
public Control getControl(){
return Control.REPEAT;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save