Merge branch 'kernel-4.6.2' into 'kernel-4.6.x'

Updating to Kernel 4.6.2

See merge request entgra/carbon-device-mgt!770
This commit is contained in:
Charitha Goonetilleke 2021-06-22 04:30:24 +00:00
commit 1b7db92e91
255 changed files with 5546 additions and 2535 deletions

View File

@ -22,13 +22,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Annotations</name> <name>WSO2 Carbon - API Management Annotations</name>
<description>WSO2 Carbon - API Management Custom Annotation Module</description> <description>WSO2 Carbon - API Management Custom Annotation Module</description>
@ -73,8 +72,8 @@
org.wso2.carbon.apimgt.annotations.* org.wso2.carbon.apimgt.annotations.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging, org.apache.commons.logging,
javax.servlet, javax.servlet,
javax.xml.*, javax.xml.*,

View File

@ -21,12 +21,11 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>4.1.16-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - API Application Management API</name> <name>WSO2 Carbon - API Application Management API</name>
@ -34,42 +33,24 @@
<url>http://wso2.org</url> <url>http://wso2.org</url>
<dependencies> <dependencies>
<!--CXF -->
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>io.swagger</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId> <artifactId>jackson-jaxrs</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-httpclient.wso2</groupId> <groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>

View File

@ -27,8 +27,6 @@ import org.wso2.carbon.apimgt.application.extension.api.util.RegistrationProfile
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor;
import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
@ -110,12 +108,10 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
if (username.equals(registrationProfile.getUsername())) { if (username.equals(registrationProfile.getUsername())) {
synchronized (ApiApplicationRegistrationServiceImpl.class) { synchronized (ApiApplicationRegistrationServiceImpl.class) {
StoreClient storeClient = new StoreClient(new OAuthRequestInterceptor(registrationProfile.getUsername(),
registrationProfile.getPassword()));
ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( ApiApplicationKey apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
applicationName, registrationProfile.getTags(), applicationName, registrationProfile.getTags(),
ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username, ApiApplicationConstants.DEFAULT_TOKEN_TYPE, username,
registrationProfile.isAllowedToAllDomains(), validityPeriod, storeClient); registrationProfile.isAllowedToAllDomains(), validityPeriod);
return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build(); return Response.status(Response.Status.CREATED).entity(apiApplicationKey.toString()).build();
} }
} }

View File

@ -25,7 +25,12 @@ import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.servlet.*; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBContext;

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -22,12 +22,11 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<version>4.1.16-SNAPSHOT</version>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Application Management</name> <name>WSO2 Carbon - API Application Management</name>
@ -51,14 +50,15 @@
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>org.wso2.carbon.logging</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId> <artifactId>org.wso2.carbon.apimgt.api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId> <artifactId>org.wso2.carbon.apimgt.impl</artifactId>
</dependency> <scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>com.googlecode.json-simple.wso2</groupId> <groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
@ -100,24 +100,32 @@
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version> <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
<Bundle-Description>API Management Application Bundle</Bundle-Description> <Bundle-Description>API Management Application Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.apimgt.application.extension.internal</Private-Package> <Private-Package>org.wso2.carbon.apimgt.application.extension.internal</Private-Package>
<Import-Package> <Import-Packages>
org.osgi.framework, org.apache.commons.lang;version="[2.6,3)",
org.osgi.service.component, org.apache.commons.logging;version="[1.2,2)",
org.apache.commons.logging.*,
org.wso2.carbon.user.core.*,
org.wso2.carbon.user.api,
org.wso2.carbon.utils.multitenancy,
org.json.simple, org.json.simple,
org.wso2.carbon.context, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.wso2.carbon.base, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.registry.core.*;resolution:=optional, org.wso2.carbon.apimgt.api;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}", org.wso2.carbon.apimgt.api.dto;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.integration.client.*, org.wso2.carbon.apimgt.api.model;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.apimgt.integration.generated.client.store.api, org.wso2.carbon.apimgt.application.extension.bean,
org.wso2.carbon.apimgt.integration.generated.client.store.model, org.wso2.carbon.apimgt.application.extension.dto,
org.wso2.carbon.identity.jwt.client.extension.*, org.wso2.carbon.apimgt.application.extension.exception,
feign org.wso2.carbon.apimgt.impl;version="${carbon.api.mgt.version.range}",
</Import-Package> org.wso2.carbon.apimgt.impl.utils;version="${carbon.api.mgt.version.range}",
org.wso2.carbon.context;version="${carbon.kernel.version.range}",
org.wso2.carbon.identity.jwt.client.extension,
org.wso2.carbon.identity.jwt.client.extension.dto,
org.wso2.carbon.identity.jwt.client.extension.exception,
org.wso2.carbon.identity.jwt.client.extension.service,
org.wso2.carbon.registry.core.exceptions;version="[1.0,2)",
org.wso2.carbon.registry.core.service;version="[1.0,2)",
org.wso2.carbon.registry.indexing.service;version="${carbon.registry.imp.pkg.version.range}",
org.wso2.carbon.user.api;version="[1.0,2)",
org.wso2.carbon.user.core.service;version="${carbon.kernel.version.range}",
org.wso2.carbon.user.core.tenant;version="${carbon.kernel.version.range}"
</Import-Packages>
<Export-Package> <Export-Package>
!org.wso2.carbon.apimgt.application.extension.internal, !org.wso2.carbon.apimgt.application.extension.internal,
org.wso2.carbon.apimgt.application.extension.* org.wso2.carbon.apimgt.application.extension.*

View File

@ -20,7 +20,6 @@ package org.wso2.carbon.apimgt.application.extension;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.apimgt.integration.client.store.StoreClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
/** /**
@ -51,28 +50,6 @@ public interface APIManagementProviderService {
String keyType, String username, boolean isAllowedAllDomains, String keyType, String username, boolean isAllowedAllDomains,
String validityTime) throws APIManagerException; String validityTime) throws APIManagerException;
/**
* Generate and retreive application keys. if the application does exist then
* create it and subscribe to apis that are grouped with the tags.
*
* @param apiApplicationName name of the application.
* @param tags tags of the apis that application needs to be subscribed.
* @param keyType of the application.
* @param username to whom the application is created
* @param isAllowedAllDomains application is allowed to all the tenants
* @param validityTime validity period of the application
* @param storeClient Specified store client
* @return consumerkey and secrete of the created application.
* @throws APIManagerException
*/
ApiApplicationKey generateAndRetrieveApplicationKeys(String apiApplicationName,
String tags[],
String keyType,
String username,
boolean isAllowedAllDomains,
String validityTime,
StoreClient storeClient) throws APIManagerException;
/** /**
* Remove APIM Application. * Remove APIM Application.
*/ */

View File

@ -18,18 +18,29 @@
package org.wso2.carbon.apimgt.application.extension; package org.wso2.carbon.apimgt.application.extension;
import feign.FeignException; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIAdmin;
import org.wso2.carbon.apimgt.api.APIConsumer;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.api.model.SubscribedAPI;
import org.wso2.carbon.apimgt.api.model.Subscriber;
import org.wso2.carbon.apimgt.application.extension.bean.APIRegistrationProfile; import org.wso2.carbon.apimgt.application.extension.bean.APIRegistrationProfile;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder; import org.wso2.carbon.apimgt.application.extension.internal.APIApplicationManagerExtensionDataHolder;
import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil; import org.wso2.carbon.apimgt.application.extension.util.APIManagerUtil;
import org.wso2.carbon.apimgt.integration.client.OAuthRequestInterceptor; import org.wso2.carbon.apimgt.impl.APIAdminImpl;
import org.wso2.carbon.apimgt.integration.client.store.StoreClient; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.integration.generated.client.store.model.*; import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
@ -39,7 +50,10 @@ import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
/** /**
* This class represents an implementation of APIManagementProviderService. * This class represents an implementation of APIManagementProviderService.
@ -47,51 +61,37 @@ import java.util.List;
public class APIManagementProviderServiceImpl implements APIManagementProviderService { public class APIManagementProviderServiceImpl implements APIManagementProviderService {
private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class); private static final Log log = LogFactory.getLog(APIManagementProviderServiceImpl.class);
private static final String CONTENT_TYPE = "application/json"; public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance();
private static final int MAX_API_PER_TAG = 200;
private static final String APP_TIER_TYPE = "application";
@Override
public boolean isTierLoaded() { public boolean isTierLoaded() {
StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
.getStoreClient(); String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain();
try { try {
storeClient.getIndividualTier().tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER, APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, tenantDomain);
APP_TIER_TYPE,
tenantDomain, CONTENT_TYPE, null, null);
return true; return true;
} catch (FeignException e) { } catch (APIManagementException e) {
log.error("Feign Exception", e);
if (e.status() == 401) {
OAuthRequestInterceptor oAuthRequestInterceptor = new OAuthRequestInterceptor();
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
oAuthRequestInterceptor.removeToken(username, tenantDomain);
try {
storeClient.getIndividualTier().tiersTierLevelTierNameGet(ApiApplicationConstants.DEFAULT_TIER,
APP_TIER_TYPE, tenantDomain, CONTENT_TYPE, null, null);
} catch (FeignException ex) {
log.error("Invalid Attempt : " + ex);
}
}
} catch (Exception e) {
log.error("APIs not ready", e); log.error("APIs not ready", e);
} }
return false; return false;
} }
@Override @Override
public void removeAPIApplication(String applicationName, String username) throws APIManagerException { public void removeAPIApplication(String applicationName, String username) throws APIManagerException {
StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService() try {
.getStoreClient(); APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username);
ApplicationList applicationList = storeClient.getApplications() Application application = apiConsumer.getApplicationsByName(username, applicationName, "");
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); if (application != null) {
if (applicationList.getList() != null && applicationList.getList().size() > 0) { apiConsumer.removeApplication(application, username);
ApplicationInfo applicationInfo = applicationList.getList().get(0); }
storeClient.getIndividualApplication().applicationsApplicationIdDelete(applicationInfo.getApplicationId(), } catch (APIManagementException e) {
null, null); throw new APIManagerException("Failed to remove api application : " + applicationName, e);
} }
} }
/** /**
@ -99,95 +99,83 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
*/ */
@Override @Override
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[], public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[],
String keyType, String username, String keyType, String username, boolean isAllowedAllDomains, String validityTime)
boolean isAllowedAllDomains, String validityTime, throws APIManagerException {
StoreClient sClient) throws APIManagerException {
StoreClient storeClient; String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (StringUtils.isEmpty(username)) {
if (sClient == null) { username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
.getStoreClient();
} else {
storeClient = sClient;
} }
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getTenantDomain();
try { try {
ApplicationList applicationList = storeClient.getApplications() APIConsumer apiConsumer = API_MANAGER_FACTORY.getAPIConsumer(username);
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null); Application application = apiConsumer.getApplicationsByName(username, applicationName, "");
Application application;
if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) { int applicationId = 0;
//create application; Subscriber subscriber = null;
application = new Application();
application.setName(applicationName);
application.setSubscriber(username);
application.setDescription("");
application.setThrottlingTier(ApiApplicationConstants.DEFAULT_TIER);
application.setGroupId("");
application = storeClient.getIndividualApplication().applicationsPost(application, CONTENT_TYPE);
} else {
ApplicationInfo applicationInfo = applicationList.getList().get(0);
application = storeClient.getIndividualApplication()
.applicationsApplicationIdGet(applicationInfo.getApplicationId(), CONTENT_TYPE, null, null);
}
if (application == null) { if (application == null) {
throw new APIManagerException( subscriber = apiConsumer.getSubscriber(username);
"Api application creation failed for " + applicationName + " to the user " + username); if (subscriber == null) {
// create subscriber
apiConsumer.addSubscriber(username, "");
subscriber = apiConsumer.getSubscriber(username);
}
//create application
application = new Application(applicationName, subscriber);
application.setTier(ApiApplicationConstants.DEFAULT_TIER);
application.setGroupId("");
application.setTokenType("OAUTH");
apiConsumer.addApplication(application, username);
application = apiConsumer.getApplicationsByName(username, applicationName, "");
} else {
subscriber = apiConsumer.getSubscriber(username);
} }
SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet Set<SubscribedAPI> subscribedAPIs =
(null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null); apiConsumer.getSubscribedAPIs(subscriber, applicationName, "");
List<Subscription> needToSubscribe = new ArrayList<>();
log.info("Already subscribed API count: " + subscribedAPIs.size());
// subscribe to apis. // subscribe to apis.
Set<String> tempApiIds = new HashSet<>();
if (tags != null && tags.length > 0) { if (tags != null && tags.length > 0) {
for (String tag : tags) { for (String tag : tags) {
APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag Set<API> apisWithTag = apiConsumer.getAPIsWithTag(tag, tenantDomain);
, CONTENT_TYPE, null); if (apisWithTag == null || apisWithTag.size() == 0) {
if (apiList.getList() == null || apiList.getList().size() == 0) { apisWithTag = apiConsumer.getAPIsWithTag(tag, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0
, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null);
} }
if (apiList.getList() != null && apiList.getList().size() > 0) { if (apisWithTag != null && apisWithTag.size() > 0) {
for (APIInfo apiInfo : apiList.getList()) { for (API apiInfo : apisWithTag) {
String id = apiInfo.getProvider().replace("@", "-AT-") String id = apiInfo.getId().getProviderName().replace("@", "-AT-")
+ "-" + apiInfo.getName() + "-" + apiInfo.getVersion(); + "-" + apiInfo.getId().getName() + "-" + apiInfo.getId().getVersion();
id = id.replace(" ", "+"); // todo: amalka will this break old apis?
boolean subscriptionExist = false; boolean subscriptionExist = false;
if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) { if (subscribedAPIs.size() > 0) {
for (Subscription subs : subscriptionList.getList()) { for (SubscribedAPI subscribedAPI : subscribedAPIs) {
if (subs.getApiIdentifier().equals(id)) { if (String.valueOf(subscribedAPI.getApiId().toString()).equals(id)) {
subscriptionExist = true; subscriptionExist = true;
break; break;
} }
} }
} }
if (!subscriptionExist) { if (!subscriptionExist && !tempApiIds.contains(id)) {
Subscription subscription = new Subscription(); ApiTypeWrapper apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(
//fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0 apiInfo.getUuid(), tenantDomain);
apiTypeWrapper.setTier(ApiApplicationConstants.DEFAULT_TIER);
subscription.setApiIdentifier(id); apiConsumer.addSubscription(apiTypeWrapper, username, application);
subscription.setApplicationId(application.getApplicationId()); tempApiIds.add(id);
subscription.tier(ApiApplicationConstants.DEFAULT_TIER);
if (!needToSubscribe.contains(subscription)) {
needToSubscribe.add(subscription);
}
} }
} }
} }
} }
} }
if (!needToSubscribe.isEmpty()) {
storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE);
}
//end of subscription //end of subscription
List<ApplicationKey> applicationKeys = application.getKeys(); List<APIKey> applicationKeys = application.getKeys();
if (applicationKeys != null) { if (applicationKeys != null) {
for (ApplicationKey applicationKey : applicationKeys) { for (APIKey applicationKey : applicationKeys) {
if (keyType.equals(applicationKey.getKeyType().toString())) { if (keyType.equals(applicationKey.getType())) {
if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
@ -198,45 +186,51 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
} }
} }
ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest();
List<String> allowedDomains = new ArrayList<>(); List<String> allowedDomains = new ArrayList<>();
if (isAllowedAllDomains) { if (isAllowedAllDomains) {
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS); allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
} else { } else {
allowedDomains.add(APIManagerUtil.getTenantDomain()); allowedDomains.add(APIManagerUtil.getTenantDomain());
} }
applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains);
applicationKeyGenerateRequest.setCallbackUrl("");
applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION);
applicationKeyGenerateRequest.setValidityTime(validityTime);
ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost( APIAdmin apiAdmin = new APIAdminImpl();
application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null); String keyManagerId = null;
if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) { try {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey(); List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiAdmin
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey()); .getKeyManagerConfigurationsByTenant(tenantDomain);
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret()); if (keyManagerConfigurations != null) {
return apiApplicationKey; for (KeyManagerConfigurationDTO keyManagerConfigurationDTO : keyManagerConfigurations) {
keyManagerId = keyManagerConfigurationDTO.getUuid();
}
}
String jsonString = "{\"grant_types\":\"refresh_token,urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," +
"\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +
"\"username\":\"" + username + "\"}";
Map<String, Object> keyDetails = apiConsumer
.requestApprovalForApplicationRegistration(username, applicationName, keyType, "",
allowedDomains.toArray(new String[allowedDomains.size()]), validityTime, "default", "",
jsonString, keyManagerId, tenantDomain);
if (keyDetails != null) {
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
apiApplicationKey.setConsumerKey((String) keyDetails.get("consumerKey"));
apiApplicationKey.setConsumerSecret((String) keyDetails.get("consumerSecret"));
return apiApplicationKey;
}
throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain);
} catch (APIManagementException e) {
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
} }
throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain); } catch (APIManagementException e) {
} catch (FeignException e) {
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e); throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
} }
} }
/**
* {@inheritDoc}
*/
@Override
public synchronized ApiApplicationKey generateAndRetrieveApplicationKeys(String applicationName, String tags[],
String keyType, String username,
boolean isAllowedAllDomains,
String validityTime)
throws APIManagerException {
return this.generateAndRetrieveApplicationKeys(applicationName, tags, keyType, username,
isAllowedAllDomains, validityTime, null);
}
@Override @Override
public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType, public AccessTokenInfo getAccessToken(String scopes, String[] tags, String applicationName, String tokenType,
String validityPeriod) throws APIManagerException { String validityPeriod) throws APIManagerException {
@ -311,7 +305,7 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) { if (registrationProfile.getUsername() == null || registrationProfile.getUsername().isEmpty()) {
info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), info = generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(),
registrationProfile.getTags(), tokenType, registrationProfile.getApplicationName(), registrationProfile.getTags(), tokenType, null,
registrationProfile.isAllowedToAllDomains(), validityPeriod); registrationProfile.isAllowedToAllDomains(), validityPeriod);
} }
} finally { } finally {

View File

@ -18,7 +18,6 @@
package org.wso2.carbon.apimgt.application.extension.internal; package org.wso2.carbon.apimgt.application.extension.internal;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
@ -35,7 +34,6 @@ public class APIApplicationManagerExtensionDataHolder {
private TenantManager tenantManager; private TenantManager tenantManager;
private TenantRegistryLoader tenantRegistryLoader; private TenantRegistryLoader tenantRegistryLoader;
private TenantIndexingLoader indexLoader; private TenantIndexingLoader indexLoader;
private IntegrationClientService integrationClientService;
private JWTClientManagerService jwtClientManagerService; private JWTClientManagerService jwtClientManagerService;
private APIApplicationManagerExtensionDataHolder() { private APIApplicationManagerExtensionDataHolder() {
@ -94,15 +92,6 @@ public class APIApplicationManagerExtensionDataHolder {
return indexLoader; return indexLoader;
} }
public IntegrationClientService getIntegrationClientService() {
return integrationClientService;
}
public void setIntegrationClientService(
IntegrationClientService integrationClientService) {
this.integrationClientService = integrationClientService;
}
public JWTClientManagerService getJwtClientManagerService() { public JWTClientManagerService getJwtClientManagerService() {
if (jwtClientManagerService == null) { if (jwtClientManagerService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();

View File

@ -23,7 +23,6 @@ import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;; import org.osgi.service.component.ComponentContext;;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderServiceImpl;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.registry.core.service.TenantRegistryLoader; import org.wso2.carbon.registry.core.service.TenantRegistryLoader;
import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader; import org.wso2.carbon.registry.indexing.service.TenantIndexingLoader;
import org.wso2.carbon.user.core.service.RealmService; import org.wso2.carbon.user.core.service.RealmService;
@ -49,12 +48,6 @@ import org.wso2.carbon.user.core.service.RealmService;
* policy="dynamic" * policy="dynamic"
* bind="setRealmService" * bind="setRealmService"
* unbind="unsetRealmService" * unbind="unsetRealmService"
* @scr.reference name="integration.client.service"
* interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService"
* cardinality="1..1"
* policy="dynamic"
* bind="setIntegrationClientService"
* unbind="unsetIntegrationClientService"
*/ */
public class APIApplicationManagerExtensionServiceComponent { public class APIApplicationManagerExtensionServiceComponent {
@ -97,17 +90,6 @@ public class APIApplicationManagerExtensionServiceComponent {
APIApplicationManagerExtensionDataHolder.getInstance().setIndexLoaderService(null); APIApplicationManagerExtensionDataHolder.getInstance().setIndexLoaderService(null);
} }
protected void setIntegrationClientService(IntegrationClientService integrationClientService) {
if (integrationClientService != null && log.isDebugEnabled()) {
log.debug("integrationClientService initialized");
}
APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(integrationClientService);
}
protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) {
APIApplicationManagerExtensionDataHolder.getInstance().setIntegrationClientService(null);
}
/** /**
* Sets Realm Service. * Sets Realm Service.
* *

View File

@ -21,13 +21,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId> <artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Security Handler Component</name> <name>WSO2 Carbon - API Security Handler Component</name>
<description>WSO2 Carbon - API Management Security Handler Module</description> <description>WSO2 Carbon - API Management Security Handler Module</description>

View File

@ -13,13 +13,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId> <artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Client</name> <name>WSO2 Carbon - API Management Integration Client</name>
<description>WSO2 Carbon - API Management Integration Client</description> <description>WSO2 Carbon - API Management Integration Client</description>

View File

@ -13,13 +13,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId> <artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Integration Generated Client</name> <name>WSO2 Carbon - API Management Integration Generated Client</name>
<description>WSO2 Carbon - API Management Integration Client</description> <description>WSO2 Carbon - API Management Integration Client</description>

View File

@ -22,13 +22,12 @@
<parent> <parent>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId> <artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - API Management Webapp Publisher</name> <name>WSO2 Carbon - API Management Webapp Publisher</name>
<description>WSO2 Carbon - API Management Webapp Publisher</description> <description>WSO2 Carbon - API Management Webapp Publisher</description>
@ -109,8 +108,14 @@
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId> <artifactId>org.wso2.carbon.apimgt.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.apimgt</groupId>
<artifactId>org.wso2.carbon.apimgt.impl</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.h2database.wso2</groupId> <groupId>com.h2database.wso2</groupId>
@ -144,41 +149,46 @@
org.wso2.carbon.apimgt.webapp.publisher.* org.wso2.carbon.apimgt.webapp.publisher.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.osgi.framework, com.google.gson;version="2.3",
org.osgi.service.component, com.google.gson.reflect;version="2.3",
org.apache.commons.logging,
javax.servlet,
javax.xml.*,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
com.google.gson.*,
org.apache.catalina,
org.apache.catalina.core,
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.wso2.carbon.core,
org.apache.commons.lang,
org.wso2.carbon.utils,
org.wso2.carbon.apimgt.annotations.*,
org.wso2.carbon.governance.lcm.util.*,
org.wso2.carbon.registry.core.*,
io.swagger.annotations, io.swagger.annotations,
javax.net.ssl, javax.servlet;version="2.6",
org.scannotation, javax.xml,
org.scannotation.archiveiterator, javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers,
org.apache.catalina;version="9.0",
org.apache.catalina.core;version="9.0",
org.apache.commons.logging;version="1.2",
org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.scannotation;version="1.0",
org.scannotation.archiveiterator;version="1.0",
org.w3c.dom, org.w3c.dom,
org.wso2.carbon.apimgt.integration.client.*, org.wso2.carbon.apimgt.annotations.api,
org.wso2.carbon.context, org.wso2.carbon.apimgt.api,
org.wso2.carbon.core.util, org.wso2.carbon.apimgt.api.model,
org.wso2.carbon.user.api, org.wso2.carbon.apimgt.impl,
org.wso2.carbon.user.core.*, org.wso2.carbon.apimgt.webapp.publisher,
org.wso2.carbon.utils.multitenancy, org.wso2.carbon.apimgt.webapp.publisher.config,
org.wso2.carbon.apimgt.integration.generated.client.publisher.api, org.wso2.carbon.apimgt.webapp.publisher.dto,
org.wso2.carbon.apimgt.integration.generated.client.publisher.model org.wso2.carbon.apimgt.webapp.publisher.exception,
org.wso2.carbon.apimgt.webapp.publisher.lifecycle.listener,
org.wso2.carbon.apimgt.webapp.publisher.lifecycle.util,
org.wso2.carbon.base;version="1.0",
org.wso2.carbon.context;version="4.6",
org.wso2.carbon.core;version="4.6",
org.wso2.carbon.core.util;version="4.6",
org.wso2.carbon.registry.core.service;version="1.0",
org.wso2.carbon.user.api;version="1.0",
org.wso2.carbon.user.core.service;version="4.6",
org.wso2.carbon.user.core.tenant;version="4.6",
org.wso2.carbon.utils;version="4.6",
org.wso2.carbon.utils.multitenancy;version="4.6"
</Import-Package> </Import-Package>
<Embed-Dependency> <Embed-Dependency>
javax.ws.rs-api, jsr311-api;scope=compile|runtime;inline=false
scribe;scope=compile|runtime;inline=false;
</Embed-Dependency> </Embed-Dependency>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>
@ -210,4 +220,5 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>

View File

@ -18,15 +18,31 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher; package org.wso2.carbon.apimgt.webapp.publisher;
import feign.FeignException; import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.integration.generated.client.publisher.model.*; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.integration.client.publisher.PublisherClient; 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.APIRevision;
import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment;
import org.wso2.carbon.apimgt.api.model.CORSConfiguration;
import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig; import org.wso2.carbon.apimgt.webapp.publisher.config.WebappPublisherConfig;
import org.wso2.carbon.apimgt.webapp.publisher.dto.ApiUriTemplate;
import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException; import org.wso2.carbon.apimgt.webapp.publisher.exception.APIManagerPublisherException;
import org.wso2.carbon.apimgt.webapp.publisher.internal.APIPublisherDataHolder;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/** /**
* This class represents the concrete implementation of the APIPublisherService that corresponds to providing all * This class represents the concrete implementation of the APIPublisherService that corresponds to providing all
@ -34,11 +50,10 @@ import java.util.*;
*/ */
public class APIPublisherServiceImpl implements APIPublisherService { public class APIPublisherServiceImpl implements APIPublisherService {
private static final String UNLIMITED_TIER = "Unlimited"; private static final String UNLIMITED_TIER = "Unlimited";
private static final String API_PUBLISH_ENVIRONMENT = "Production and Sandbox"; private static final String API_PUBLISH_ENVIRONMENT = "Default";
private static final String CONTENT_TYPE = "application/json";
private static final String PUBLISHED_STATUS = "PUBLISHED";
private static final String CREATED_STATUS = "CREATED"; private static final String CREATED_STATUS = "CREATED";
private static final String PUBLISH_ACTION = "Publish"; private static final String PUBLISH_ACTION = "Publish";
public static final APIManagerFactory API_MANAGER_FACTORY = APIManagerFactory.getInstance();
@Override @Override
public void publishAPI(APIConfig apiConfig) throws APIManagerPublisherException { public void publishAPI(APIConfig apiConfig) throws APIManagerPublisherException {
@ -47,99 +62,124 @@ public class APIPublisherServiceImpl implements APIPublisherService {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner()); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(apiConfig.getOwner());
try { try {
PublisherClient publisherClient = APIPublisherDataHolder.getInstance().getIntegrationClientService() APIProvider apiProvider = API_MANAGER_FACTORY.getAPIProvider(apiConfig.getOwner());
.getPublisherClient();
API api = getAPI(apiConfig); API api = getAPI(apiConfig);
APIList apiList = publisherClient.getApis().apisGet(100, 0, "name:" + api.getName(), CONTENT_TYPE, null);
if (!isExist(api, apiList)) { if (!apiProvider.isAPIAvailable(api.getId())) {
api = publisherClient.getApi().apisPost(api, CONTENT_TYPE, null); API createdAPI = apiProvider.addAPI(api);
if (CREATED_STATUS.equals(api.getStatus())) { if (CREATED_STATUS.equals(createdAPI.getStatus())) {
publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, null); apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null);
APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(createdAPI.getUuid());
apiRevision.setDescription("Initial Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain);
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost("localhost");
apiRevisionDeployment.setDisplayOnDevportal(true);
List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>();
apiRevisionDeploymentList.add(apiRevisionDeployment);
apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList);
} }
} else { } else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
for (APIInfo apiInfo : apiList.getList()) { API existingAPI = apiProvider.getAPI(api.getId());
if (api.getName().equals(apiInfo.getName()) && api.getVersion().equals(apiInfo.getVersion())) { api.setStatus(existingAPI.getStatus());
api = publisherClient.getApi().apisApiIdPut(apiInfo.getId(), api, CONTENT_TYPE, null, null); apiProvider.updateAPI(api);
if (api != null && CREATED_STATUS.equals(api.getStatus())) { if (api.getId().getName().equals(existingAPI.getId().getName()) &&
publisherClient.getApi().apisChangeLifecyclePost(PUBLISH_ACTION, api.getId(), null, null, api.getId().getVersion().equals(existingAPI.getId().getVersion())) {
null); if (CREATED_STATUS.equals(existingAPI.getStatus())) {
} apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null);
} }
} }
} }
} }
} catch (FeignException e) {
} catch (FaultGatewaysException | APIManagementException e) {
throw new APIManagerPublisherException(e); throw new APIManagerPublisherException(e);
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();
} }
} }
private boolean isExist(API api, APIList apiList) {
if (apiList == null || apiList.getList() == null || apiList.getList().size() == 0) {
return false;
}
for (APIInfo existingApi : apiList.getList()) {
if (existingApi.getName() != null && existingApi.getName().equals(api.
getName()) && existingApi.getVersion() != null &&
existingApi.getVersion().equals(api.getVersion())) {
return true;
}
}
return false;
}
private API getAPI(APIConfig config) { private API getAPI(APIConfig config) {
API api = new API(); APIIdentifier apiIdentifier = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion());
api.setName(config.getName()); API api = new API(apiIdentifier);
api.setDescription(""); api.setDescription("");
String context = config.getContext(); String context = config.getContext();
context = context.startsWith("/") ? context : ("/" + context); context = context.startsWith("/") ? context : ("/" + context);
api.setContext(context); api.setContext(context + "/" + config.getVersion());
api.setVersion(config.getVersion()); api.setStatus(CREATED_STATUS);
api.setProvider(config.getOwner()); api.setWsdlUrl(null);
api.setApiDefinition(APIPublisherUtil.getSwaggerDefinition(config)); api.setResponseCache("Disabled");
api.setWsdlUri(null); api.setContextTemplate(context + "/{version}" );
api.setStatus(PUBLISHED_STATUS); api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config));
api.setResponseCaching("DISABLED"); api.setType("HTTP");
api.setDestinationStatsEnabled("false");
api.isDefaultVersion(config.isDefault());
List<String> transport = new ArrayList<>();
transport.add("https");
transport.add("http");
api.transport(transport);
api.setTags(Arrays.asList(config.getTags()));
api.addTiersItem(UNLIMITED_TIER);
api.setGatewayEnvironments(API_PUBLISH_ENVIRONMENT);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.all_tenants);
api.setVisibility(API.VisibilityEnum.PUBLIC);
} else {
api.setSubscriptionAvailability(API.SubscriptionAvailabilityEnum.current_tenant);
api.setVisibility(API.VisibilityEnum.PRIVATE);
}
String endpointConfig = "{\"production_endpoints\":{\"url\":\"" + config.getEndpoint() +
"\",\"config\":null},\"implementation_status\":\"managed\",\"endpoint_type\":\"http\"}";
Set<URITemplate> uriTemplates = new HashSet<>();
Iterator<ApiUriTemplate> iterator;
for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) {
ApiUriTemplate apiUriTemplate = iterator.next();
URITemplate uriTemplate = new URITemplate();
uriTemplate.setAuthType(apiUriTemplate.getAuthType());
uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb());
uriTemplate.setResourceURI(apiUriTemplate.getResourceURI());
uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate());
Scope scope = new Scope();
if (apiUriTemplate.getScope() != null) {
scope.setName(apiUriTemplate.getScope().getName());
scope.setDescription(apiUriTemplate.getScope().getDescription());
scope.setKey(apiUriTemplate.getScope().getKey());
scope.setRoles(apiUriTemplate.getScope().getRoles());
uriTemplate.setScope(scope);
}
uriTemplates.add(uriTemplate);
}
api.setUriTemplates(uriTemplates);
api.setApiOwner(config.getOwner());
api.setDefaultVersion(config.isDefault());
api.setTransports("https,http");
Set<String> tags = new HashSet<>();
tags.addAll(Arrays.asList(config.getTags()));
api.setTags(tags);
Set<Tier> availableTiers = new HashSet<>();
availableTiers.add(new Tier(UNLIMITED_TIER));
api.setAvailableTiers(availableTiers);
Set<String> environments = new HashSet<>();
environments.add(API_PUBLISH_ENVIRONMENT);
api.setEnvironments(environments);
if (config.isSharedWithAllTenants()) {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS);
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY);
} else {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT);
api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY);
}
String endpointConfig = "{ \"endpoint_type\": \"http\", \"sandbox_endpoints\": { \"url\": \" " +
config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" "+ config.getEndpoint()+"\" } }";
api.setEndpointConfig(endpointConfig); api.setEndpointConfig(endpointConfig);
APICorsConfiguration apiCorsConfiguration = new APICorsConfiguration();
List<String> accessControlAllowOrigins = new ArrayList<>(); List<String> accessControlAllowOrigins = new ArrayList<>();
accessControlAllowOrigins.add("*"); accessControlAllowOrigins.add("*");
apiCorsConfiguration.setAccessControlAllowOrigins(accessControlAllowOrigins);
List<String> accessControlAllowHeaders = new ArrayList<>(); List<String> accessControlAllowHeaders = new ArrayList<>();
accessControlAllowHeaders.add("authorization"); accessControlAllowHeaders.add("authorization");
accessControlAllowHeaders.add("Access-Control-Allow-Origin"); accessControlAllowHeaders.add("Access-Control-Allow-Origin");
accessControlAllowHeaders.add("Content-Type"); accessControlAllowHeaders.add("Content-Type");
accessControlAllowHeaders.add("SOAPAction"); accessControlAllowHeaders.add("SOAPAction");
apiCorsConfiguration.setAccessControlAllowHeaders(accessControlAllowHeaders); accessControlAllowHeaders.add("apikey");
accessControlAllowHeaders.add("Internal-Key");
List<String> accessControlAllowMethods = new ArrayList<>(); List<String> accessControlAllowMethods = new ArrayList<>();
accessControlAllowMethods.add("GET"); accessControlAllowMethods.add("GET");
accessControlAllowMethods.add("PUT"); accessControlAllowMethods.add("PUT");
@ -147,10 +187,16 @@ public class APIPublisherServiceImpl implements APIPublisherService {
accessControlAllowMethods.add("POST"); accessControlAllowMethods.add("POST");
accessControlAllowMethods.add("PATCH"); accessControlAllowMethods.add("PATCH");
accessControlAllowMethods.add("OPTIONS"); accessControlAllowMethods.add("OPTIONS");
apiCorsConfiguration.setAccessControlAllowMethods(accessControlAllowMethods); CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false,
apiCorsConfiguration.setAccessControlAllowCredentials(false); accessControlAllowHeaders, accessControlAllowMethods);
apiCorsConfiguration.corsConfigurationEnabled(false); api.setCorsConfiguration(corsConfiguration);
api.setCorsConfiguration(apiCorsConfiguration);
api.setAuthorizationHeader("Authorization");
List<String> keyManagers = new ArrayList<>();
keyManagers.add("all");
api.setKeyManagers(keyManagers);
api.setEnableStore(true);
return api; return api;
} }
} }

View File

@ -18,7 +18,6 @@
*/ */
package org.wso2.carbon.apimgt.webapp.publisher.internal; package org.wso2.carbon.apimgt.webapp.publisher.internal;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.apimgt.webapp.publisher.APIConfig; import org.wso2.carbon.apimgt.webapp.publisher.APIConfig;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.registry.core.service.RegistryService; import org.wso2.carbon.registry.core.service.RegistryService;
@ -37,8 +36,6 @@ public class APIPublisherDataHolder {
private RegistryService registryService; private RegistryService registryService;
private boolean isServerStarted; private boolean isServerStarted;
private Stack<APIConfig> unpublishedApis = new Stack<>(); private Stack<APIConfig> unpublishedApis = new Stack<>();
private IntegrationClientService integrationClientService;
private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder(); private static APIPublisherDataHolder thisInstance = new APIPublisherDataHolder();
private APIPublisherDataHolder() { private APIPublisherDataHolder() {
@ -117,12 +114,4 @@ public class APIPublisherDataHolder {
this.unpublishedApis = unpublishedApis; this.unpublishedApis = unpublishedApis;
} }
public IntegrationClientService getIntegrationClientService() {
return integrationClientService;
}
public void setIntegrationClientService(
IntegrationClientService integrationClientService) {
this.integrationClientService = integrationClientService;
}
} }

View File

@ -22,7 +22,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherService;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherServiceImpl;
import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherStartupHandler; import org.wso2.carbon.apimgt.webapp.publisher.APIPublisherStartupHandler;
@ -45,11 +44,6 @@ import org.wso2.carbon.user.core.service.RealmService;
* policy="dynamic" * policy="dynamic"
* bind="setRegistryService" * bind="setRegistryService"
* unbind="unsetRegistryService" * unbind="unsetRegistryService"
* interface="org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService"
* cardinality="1..1"
* policy="dynamic"
* bind="setIntegrationClientService"
* unbind="unsetIntegrationClientService"
*/ */
public class APIPublisherServiceComponent { public class APIPublisherServiceComponent {
@ -120,14 +114,4 @@ public class APIPublisherServiceComponent {
APIPublisherDataHolder.getInstance().setRegistryService(null); APIPublisherDataHolder.getInstance().setRegistryService(null);
} }
protected void setIntegrationClientService(IntegrationClientService integrationClientService) {
if (integrationClientService != null && log.isDebugEnabled()) {
log.debug("integrationClientService initialized");
}
APIPublisherDataHolder.getInstance().setIntegrationClientService(integrationClientService);
}
protected void unsetIntegrationClientService(IntegrationClientService integrationClientService) {
APIPublisherDataHolder.getInstance().setIntegrationClientService(null);
}
} }

View File

@ -22,25 +22,21 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apimgt-extensions</artifactId> <artifactId>apimgt-extensions</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - API Management Extensions Component</name> <name>WSO2 Carbon - API Management Extensions Component</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<modules> <modules>
<module>org.wso2.carbon.apimgt.integration.generated.client</module>
<module>org.wso2.carbon.apimgt.integration.client</module>
<module>org.wso2.carbon.apimgt.webapp.publisher</module> <module>org.wso2.carbon.apimgt.webapp.publisher</module>
<module>org.wso2.carbon.apimgt.application.extension</module> <module>org.wso2.carbon.apimgt.application.extension</module>
<module>org.wso2.carbon.apimgt.application.extension.api</module> <module>org.wso2.carbon.apimgt.application.extension.api</module>
<module>org.wso2.carbon.apimgt.annotations</module> <module>org.wso2.carbon.apimgt.annotations</module>
<module>org.wso2.carbon.apimgt.handlers</module>
</modules> </modules>
<build> <build>

View File

@ -3,13 +3,12 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.addons</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.addons</artifactId>
<version>4.1.16-SNAPSHOT</version>
<name>WSO2 Carbon - Application Management Add-Ons</name> <name>WSO2 Carbon - Application Management Add-Ons</name>
<description>WSO2 Carbon - Application Management Add-Ons</description> <description>WSO2 Carbon - Application Management Add-Ons</description>
<url>https://entgra.io</url> <url>https://entgra.io</url>

View File

@ -22,13 +22,12 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.api</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.api</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - Application Management API</name> <name>WSO2 Carbon - Application Management API</name>
<description>WSO2 Carbon - Application Management API</description> <description>WSO2 Carbon - Application Management API</description>

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -21,13 +21,12 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.common</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - Application Management Common</name> <name>WSO2 Carbon - Application Management Common</name>
<description>WSO2 Carbon - Application Management Common</description> <description>WSO2 Carbon - Application Management Common</description>
@ -56,7 +55,7 @@
io.swagger.annotations.*;resolution:=optional, io.swagger.annotations.*;resolution:=optional,
com.fasterxml.jackson.annotation, com.fasterxml.jackson.annotation,
javax.validation.constraints, javax.validation.constraints,
javax.xml.bind.annotation.*, javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}",
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
org.wso2.carbon.device.application.mgt.common.* org.wso2.carbon.device.application.mgt.common.*

View File

@ -24,7 +24,7 @@ import java.sql.Timestamp;
public class DeviceSubscriptionData { public class DeviceSubscriptionData {
private String action; private String action;
private Timestamp actionTriggeredTimestamp; private long actionTriggeredTimestamp;
private String actionTriggeredBy; private String actionTriggeredBy;
private String actionType; private String actionType;
private String status; private String status;
@ -38,11 +38,11 @@ public class DeviceSubscriptionData {
this.action = action; this.action = action;
} }
public Timestamp getActionTriggeredTimestamp() { public long getActionTriggeredTimestamp() {
return actionTriggeredTimestamp; return actionTriggeredTimestamp;
} }
public void setActionTriggeredTimestamp(Timestamp actionTriggeredTimestamp) { public void setActionTriggeredTimestamp(long actionTriggeredTimestamp) {
this.actionTriggeredTimestamp = actionTriggeredTimestamp; this.actionTriggeredTimestamp = actionTriggeredTimestamp;
} }

View File

@ -69,7 +69,7 @@ public class ScheduledSubscriptionDTO {
/** /**
* Scheduled time of subscription. * Scheduled time of subscription.
*/ */
private LocalDateTime scheduledAt; private long scheduledAt;
/** /**
* Username of the scheduler. * Username of the scheduler.
@ -86,7 +86,7 @@ public class ScheduledSubscriptionDTO {
} }
public ScheduledSubscriptionDTO(String taskName, String applicationUUID, LocalDateTime scheduledAt, public ScheduledSubscriptionDTO(String taskName, String applicationUUID, long scheduledAt,
List<?> subscriberList, String scheduledBy) { List<?> subscriberList, String scheduledBy) {
this.taskName = taskName; this.taskName = taskName;
this.applicationUUID = applicationUUID; this.applicationUUID = applicationUUID;
@ -135,11 +135,11 @@ public class ScheduledSubscriptionDTO {
this.status = status; this.status = status;
} }
public LocalDateTime getScheduledAt() { public long getScheduledAt() {
return scheduledAt; return scheduledAt;
} }
public void setScheduledAt(LocalDateTime scheduledAt) { public void setScheduledAt(long scheduledAt) {
this.scheduledAt = scheduledAt; this.scheduledAt = scheduledAt;
} }

View File

@ -22,6 +22,7 @@ import org.wso2.carbon.device.application.mgt.common.dto.ScheduledSubscriptionDT
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
import org.wso2.carbon.device.application.mgt.common.exception.SubscriptionManagementException; import org.wso2.carbon.device.application.mgt.common.exception.SubscriptionManagementException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import java.util.List; import java.util.List;
@ -127,14 +128,11 @@ public interface SubscriptionManager {
* This method used to get the app id ,device ids and pass them to DM service method. * This method used to get the app id ,device ids and pass them to DM service method.
* *
* @param appUUID UUID of the application release. * @param appUUID UUID of the application release.
* @param offsetValue offset value for get paginated request. * @param request paginated request object.
* @param limitValue limit value for get paginated request.
* @param status status of the devices.
* @return deviceDetails - device details for given application release. * @return deviceDetails - device details for given application release.
* @throws {@link ApplicationManagementException} Exception of the application management * @throws {@link ApplicationManagementException} Exception of the application management
*/ */
PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID) throws ApplicationManagementException;
List<String> status) throws ApplicationManagementException;
/*** /***
* This method used to get category details. * This method used to get category details.
@ -152,14 +150,15 @@ public interface SubscriptionManager {
/** /**
* This method is responsible to provide application subscription data for given application release UUID. * This method is responsible to provide application subscription data for given application release UUID.
* *
* @param offsetValue offset * @param request paginated request object.
* @param limitValue limit * @param actionStatus status of the operation.
* @param action action related to the device.
* @param appUUID application release UUID * @param appUUID application release UUID
* @return {@link PaginationResult} * @return {@link PaginationResult}
* @throws ApplicationManagementException if offset or limit contains incorrect values, if it couldn't find an * @throws ApplicationManagementException if offset or limit contains incorrect values, if it couldn't find an
* application release for given UUID, if an error occurred while getting device details of subscribed device ids, * application release for given UUID, if an error occurred while getting device details of subscribed device ids,
* if an error occurred while getting subscription details of given application release UUID. * if an error occurred while getting subscription details of given application release UUID.
*/ */
PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID) PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus, String action)
throws ApplicationManagementException; throws ApplicationManagementException;
} }

View File

@ -21,13 +21,12 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.core</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.core</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - Application Management Core</name> <name>WSO2 Carbon - Application Management Core</name>
<description>WSO2 Carbon - Application Management Core</description> <description>WSO2 Carbon - Application Management Core</description>
@ -51,8 +50,8 @@
<Bundle-Description>Application Management Core Bundle</Bundle-Description> <Bundle-Description>Application Management Core Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.application.mgt.core.internal</Private-Package> <Private-Package>org.wso2.carbon.device.application.mgt.core.internal</Private-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging, org.apache.commons.logging,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
org.wso2.carbon.context.*, org.wso2.carbon.context.*,
@ -62,8 +61,8 @@
javax.sql, javax.sql,
com.google.gson.*, com.google.gson.*,
javax.naming, javax.naming,
javax.xml.bind.annotation, javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}",
javax.xml.bind, javax.xml.bind; version="${javax.xml.bind.imp.pkg.version}",
org.wso2.carbon.device.application.mgt.common.*, org.wso2.carbon.device.application.mgt.common.*,
org.wso2.carbon.device.mgt.core.*, org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,
@ -87,8 +86,6 @@
org.apache.commons.validator.routines org.apache.commons.validator.routines
</Import-Package> </Import-Package>
<Embed-Dependency>apk-parser;scope=compile|runtime;inline=false</Embed-Dependency> <Embed-Dependency>apk-parser;scope=compile|runtime;inline=false</Embed-Dependency>
<!--<Embed-Transitive>true</Embed-Transitive>-->
<!--<Embed-StripGroup>true</Embed-StripGroup>-->
<Export-Package> <Export-Package>
!org.wso2.carbon.device.application.mgt.core.internal.*, !org.wso2.carbon.device.application.mgt.core.internal.*,
org.wso2.carbon.device.application.mgt.core.* org.wso2.carbon.device.application.mgt.core.*
@ -348,6 +345,10 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -81,7 +81,7 @@ public interface SubscriptionDAO {
void addGroupSubscriptions(int tenantId, String subscribedBy, List<String> groups, int releaseId, String action) void addGroupSubscriptions(int tenantId, String subscribedBy, List<String> groups, int releaseId, String action)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws
ApplicationManagementDAOException; ApplicationManagementDAOException;
Map<Integer, DeviceSubscriptionDTO> getDeviceSubscriptions(List<Integer> deviceIds, int appReleaseId, int tenantId) Map<Integer, DeviceSubscriptionDTO> getDeviceSubscriptions(List<Integer> deviceIds, int appReleaseId, int tenantId)
@ -124,7 +124,7 @@ public interface SubscriptionDAO {
* @param scheduledBy username of the user who scheduled the subscription * @param scheduledBy username of the user who scheduled the subscription
* @throws ApplicationManagementDAOException if error occurred while updating the entry * @throws ApplicationManagementDAOException if error occurred while updating the entry
*/ */
boolean updateScheduledSubscription(int id, LocalDateTime scheduledAt, String scheduledBy) boolean updateScheduledSubscription(int id, long scheduledAt, String scheduledBy)
throws ApplicationManagementDAOException; throws ApplicationManagementDAOException;
/** /**

View File

@ -134,7 +134,8 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, "
+ "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, "
+ "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, "
+ "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE "
+ "FROM AP_APP " + "FROM AP_APP "
+ "INNER JOIN AP_APP_RELEASE ON " + "INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "
@ -181,7 +182,17 @@ public class GenericApplicationDAOImpl extends AbstractDAOImpl implements Applic
if (filter.getLimit() != -1) { if (filter.getLimit() != -1) {
sql += "LIMIT ? OFFSET ? "; sql += "LIMIT ? OFFSET ? ";
} }
sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; sql += ") AS app_data ON app_data.ID = AP_APP.ID "
+ "INNER JOIN ("
+ "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID "
+ "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) "
+ "FROM AP_APP_LIFECYCLE_STATE "
+ "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE "
+ "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "WHERE AP_APP.TENANT_ID = ? "
+ "ORDER BY AP_APP.ID, LATEST_UPDATE DESC";
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {

View File

@ -80,7 +80,8 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl {
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, "
+ "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, "
+ "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, "
+ "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE "
+ "FROM AP_APP " + "FROM AP_APP "
+ "INNER JOIN AP_APP_RELEASE ON " + "INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "
@ -125,7 +126,17 @@ public class OracleApplicationDAOImpl extends GenericApplicationDAOImpl {
if (filter.getLimit() != -1) { if (filter.getLimit() != -1) {
sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ";
} }
sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; sql += ") AS app_data ON app_data.ID = AP_APP.ID "
+ "INNER JOIN ("
+ "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID "
+ "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) "
+ "FROM AP_APP_LIFECYCLE_STATE "
+ "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE "
+ "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "WHERE AP_APP.TENANT_ID = ? "
+ "ORDER BY AP_APP.ID, LATEST_UPDATE DESC";
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {

View File

@ -79,7 +79,8 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
+ "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, " + "AP_APP_RELEASE.SUPPORTED_OS_VERSIONS AS RELEASE_SUP_OS_VERSIONS, "
+ "AP_APP_RELEASE.RATING AS RELEASE_RATING, " + "AP_APP_RELEASE.RATING AS RELEASE_RATING, "
+ "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, " + "AP_APP_RELEASE.CURRENT_STATE AS RELEASE_CURRENT_STATE, "
+ "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT " + "AP_APP_RELEASE.RATED_USERS AS RATED_USER_COUNT, "
+ "NEW_AP_APP_LIFECYCLE_STATE.UPDATED_AT AS LATEST_UPDATE "
+ "FROM AP_APP " + "FROM AP_APP "
+ "INNER JOIN AP_APP_RELEASE ON " + "INNER JOIN AP_APP_RELEASE ON "
+ "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID " + "AP_APP.ID = AP_APP_RELEASE.AP_APP_ID "
@ -124,7 +125,17 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
if (filter.getLimit() != -1) { if (filter.getLimit() != -1) {
sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY "; sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ";
} }
sql += ") AS app_data ON app_data.ID = AP_APP.ID WHERE AP_APP.TENANT_ID = ? ORDER BY AP_APP.ID"; sql += ") AS app_data ON app_data.ID = AP_APP.ID "
+ "INNER JOIN ("
+ "SELECT AP_APP_LIFECYCLE_STATE.UPDATED_AT, AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "FROM AP_APP_LIFECYCLE_STATE WHERE AP_APP_LIFECYCLE_STATE.ID "
+ "IN(SELECT MAX(AP_APP_LIFECYCLE_STATE.ID) "
+ "FROM AP_APP_LIFECYCLE_STATE "
+ "GROUP BY AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID)) AS NEW_AP_APP_LIFECYCLE_STATE "
+ "ON AP_APP_RELEASE.ID = NEW_AP_APP_LIFECYCLE_STATE.AP_APP_RELEASE_ID "
+ "WHERE AP_APP.TENANT_ID = ? "
+ "ORDER BY AP_APP.ID, LATEST_UPDATE DESC";
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {

View File

@ -332,12 +332,15 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId) throws public List<DeviceSubscriptionDTO> getDeviceSubscriptions(int appReleaseId, int tenantId, String actionStatus, String action) throws
ApplicationManagementDAOException { ApplicationManagementDAOException {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Getting device subscriptions for the application release id " + appReleaseId log.debug("Getting device subscriptions for the application release id " + appReleaseId
+ " from the database"); + " from the database");
} }
boolean isActionStatusProvided = false;
boolean isActionProvided = false;
int index = 1;
String sql = "SELECT " String sql = "SELECT "
+ "DS.ID AS ID, " + "DS.ID AS ID, "
+ "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, " + "DS.SUBSCRIBED_BY AS SUBSCRIBED_BY, "
@ -350,11 +353,30 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
+ "DS.DM_DEVICE_ID AS DEVICE_ID " + "DS.DM_DEVICE_ID AS DEVICE_ID "
+ "FROM AP_DEVICE_SUBSCRIPTION DS " + "FROM AP_DEVICE_SUBSCRIPTION DS "
+ "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.TENANT_ID=?"; + "WHERE DS.AP_APP_RELEASE_ID = ? AND DS.TENANT_ID=?";
if (actionStatus != null && !actionStatus.isEmpty()) {
sql += " AND DS.STATUS= ?";
isActionStatusProvided = true;
}
if (action != null && !action.isEmpty()) {
sql += " AND DS.UNSUBSCRIBED= ?";
isActionProvided = true;
}
try { try {
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setInt(1, appReleaseId); stmt.setInt(index++, appReleaseId);
stmt.setInt(2, tenantId); stmt.setInt(index++, tenantId);
if (isActionStatusProvided) {
stmt.setString(index++, actionStatus);
}
if (isActionProvided) {
if (action.equals("SUBSCRIBED")) {
stmt.setString(index, "FALSE");
} else {
stmt.setString(index, "TRUE");
}
}
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully retrieved device subscriptions for application release id " log.debug("Successfully retrieved device subscriptions for application release id "
@ -765,7 +787,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
stmt.setString(2, subscriptionDTO.getApplicationUUID()); stmt.setString(2, subscriptionDTO.getApplicationUUID());
stmt.setString(3, subscriptionDTO.getSubscribersString()); stmt.setString(3, subscriptionDTO.getSubscribersString());
stmt.setString(4, ExecutionStatus.PENDING.toString()); stmt.setString(4, ExecutionStatus.PENDING.toString());
stmt.setTimestamp(5, Timestamp.valueOf(subscriptionDTO.getScheduledAt())); stmt.setLong(5, subscriptionDTO.getScheduledAt());
stmt.setTimestamp(6, new Timestamp(calendar.getTime().getTime())); stmt.setTimestamp(6, new Timestamp(calendar.getTime().getTime()));
stmt.setString(7, subscriptionDTO.getScheduledBy()); stmt.setString(7, subscriptionDTO.getScheduledBy());
stmt.setBoolean(8, false); stmt.setBoolean(8, false);
@ -785,7 +807,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
} }
@Override @Override
public boolean updateScheduledSubscription(int id, LocalDateTime scheduledAt, String scheduledBy) public boolean updateScheduledSubscription(int id, long scheduledAt, String scheduledBy)
throws ApplicationManagementDAOException { throws ApplicationManagementDAOException {
String sql = "UPDATE AP_SCHEDULED_SUBSCRIPTION " String sql = "UPDATE AP_SCHEDULED_SUBSCRIPTION "
+ "SET " + "SET "
@ -797,7 +819,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
Connection conn = this.getDBConnection(); Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
stmt.setTimestamp(1, Timestamp.valueOf(scheduledAt)); stmt.setLong(1, scheduledAt);
stmt.setString(2, scheduledBy); stmt.setString(2, scheduledBy);
stmt.setTimestamp(3, new Timestamp(calendar.getTime().getTime())); stmt.setTimestamp(3, new Timestamp(calendar.getTime().getTime()));
stmt.setInt(4, id); stmt.setInt(4, id);
@ -1037,7 +1059,7 @@ public class GenericSubscriptionDAOImpl extends AbstractDAOImpl implements Subsc
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, ExecutionStatus.PENDING.toString()); stmt.setString(1, ExecutionStatus.PENDING.toString());
stmt.setBoolean(2, false); stmt.setBoolean(2, false);
stmt.setTimestamp(3, new Timestamp(Calendar.getInstance().getTime().getTime())); stmt.setLong(3, Calendar.getInstance().getTime().getTime() / 1000);
try (ResultSet rs = stmt.executeQuery()) { try (ResultSet rs = stmt.executeQuery()) {
return DAOUtil.loadScheduledSubscriptions(rs); return DAOUtil.loadScheduledSubscriptions(rs);
} }

View File

@ -1445,7 +1445,7 @@ ApplicationManagerImpl implements ApplicationManager {
log.error(msg); log.error(msg);
throw new ForbiddenException(msg); throw new ForbiddenException(msg);
} }
if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId).isEmpty()) { if (!subscriptionDAO.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null).isEmpty()) {
String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid()
+ " either subscribed to device/s or it had subscribed to device/s. Therefore you are not " + " either subscribed to device/s or it had subscribed to device/s. Therefore you are not "
+ "permitted to delete the application release."; + "permitted to delete the application release.";
@ -1580,7 +1580,7 @@ ApplicationManagerImpl implements ApplicationManager {
try { try {
ConnectionManagerUtil.beginDBTransaction(); ConnectionManagerUtil.beginDBTransaction();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId); .getDeviceSubscriptions(applicationReleaseDTO.getId(), tenantId, null, null);
if (!deviceSubscriptionDTOS.isEmpty()) { if (!deviceSubscriptionDTOS.isEmpty()) {
String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid() String msg = "Application release which has UUID: " + applicationReleaseDTO.getUuid()
+ " either subscribed to device/s or it had subscribed to device/s. Therefore you " + " either subscribed to device/s or it had subscribed to device/s. Therefore you "

View File

@ -65,10 +65,7 @@ import org.wso2.carbon.device.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.application.mgt.core.util.Constants; import org.wso2.carbon.device.application.mgt.core.util.Constants;
import org.wso2.carbon.device.application.mgt.core.util.HelperUtil; import org.wso2.carbon.device.application.mgt.core.util.HelperUtil;
import org.wso2.carbon.device.application.mgt.core.util.OAuthUtils; import org.wso2.carbon.device.application.mgt.core.util.OAuthUtils;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.MDMAppConstants;
import org.wso2.carbon.device.mgt.common.app.mgt.App; import org.wso2.carbon.device.mgt.common.app.mgt.App;
import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes; import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes;
import org.wso2.carbon.device.mgt.common.app.mgt.android.CustomApplication; import org.wso2.carbon.device.mgt.common.app.mgt.android.CustomApplication;
@ -88,7 +85,6 @@ import org.wso2.carbon.device.mgt.core.util.MDMIOSOperationUtil;
import org.wso2.carbon.device.mgt.core.util.MDMWindowsOperationUtil; import org.wso2.carbon.device.mgt.core.util.MDMWindowsOperationUtil;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import java.io.BufferedReader; import java.io.BufferedReader;
@ -381,7 +377,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
if (applicationDTO != null) { if (applicationDTO != null) {
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = this.subscriptionDAO List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = this.subscriptionDAO
.getDeviceSubscriptions(applicationDTO.getApplicationReleaseDTOs().get(0).getId(), .getDeviceSubscriptions(applicationDTO.getApplicationReleaseDTOs().get(0).getId(),
tenantId); tenantId, null, null);
AtomicBoolean isAppSubscribable = new AtomicBoolean(true); AtomicBoolean isAppSubscribable = new AtomicBoolean(true);
for (DeviceSubscriptionDTO deviceSubscriptionDTO : deviceSubscriptionDTOS) { for (DeviceSubscriptionDTO deviceSubscriptionDTO : deviceSubscriptionDTOS) {
@ -1223,7 +1219,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
} }
@Override @Override
public PaginationResult getAppInstalledDevices(int offsetValue, int limitValue, String appUUID, List<String> status) public PaginationResult getAppInstalledDevices(PaginationRequest request, String appUUID)
throws ApplicationManagementException { throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil DeviceManagementProviderService deviceManagementProviderService = HelperUtil
@ -1235,7 +1231,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId(); int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseId, tenantId); .getDeviceSubscriptions(applicationReleaseId, tenantId, null, null);
if (deviceSubscriptionDTOS.isEmpty()) { if (deviceSubscriptionDTOS.isEmpty()) {
PaginationResult paginationResult = new PaginationResult(); PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(new ArrayList<>()); paginationResult.setData(new ArrayList<>());
@ -1262,8 +1258,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
} }
//pass the device id list to device manager service method //pass the device id list to device manager service method
try { try {
PaginationResult deviceDetails = deviceManagementProviderService PaginationResult deviceDetails = deviceManagementProviderService.getAppSubscribedDevices
.getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, status); (request, deviceIdList);
if (deviceDetails == null) { if (deviceDetails == null) {
String msg = "Couldn't found an subscribed devices details for device ids: " + deviceIdList; String msg = "Couldn't found an subscribed devices details for device ids: " + deviceIdList;
@ -1342,8 +1338,10 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
} }
@Override @Override
public PaginationResult getAppSubscriptionDetails(int offsetValue, int limitValue, String appUUID) public PaginationResult getAppSubscriptionDetails(PaginationRequest request, String appUUID, String actionStatus,
throws ApplicationManagementException { String action) throws ApplicationManagementException {
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
DeviceManagementProviderService deviceManagementProviderService = HelperUtil DeviceManagementProviderService deviceManagementProviderService = HelperUtil
.getDeviceManagementProviderService(); .getDeviceManagementProviderService();
@ -1365,7 +1363,7 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId(); int applicationReleaseId = applicationDTO.getApplicationReleaseDTOs().get(0).getId();
List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO List<DeviceSubscriptionDTO> deviceSubscriptionDTOS = subscriptionDAO
.getDeviceSubscriptions(applicationReleaseId, tenantId); .getDeviceSubscriptions(applicationReleaseId, tenantId, actionStatus, action);
if (deviceSubscriptionDTOS.isEmpty()) { if (deviceSubscriptionDTOS.isEmpty()) {
PaginationResult paginationResult = new PaginationResult(); PaginationResult paginationResult = new PaginationResult();
paginationResult.setData(new ArrayList<>()); paginationResult.setData(new ArrayList<>());
@ -1377,8 +1375,8 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
.collect(Collectors.toList()); .collect(Collectors.toList());
try { try {
//pass the device id list to device manager service method //pass the device id list to device manager service method
PaginationResult paginationResult = deviceManagementProviderService PaginationResult paginationResult = deviceManagementProviderService.getAppSubscribedDevices
.getAppSubscribedDevices(offsetValue, limitValue, deviceIdList, null); (request, deviceIdList);
List<DeviceSubscriptionData> deviceSubscriptionDataList = new ArrayList<>(); List<DeviceSubscriptionData> deviceSubscriptionDataList = new ArrayList<>();
if (!paginationResult.getData().isEmpty()) { if (!paginationResult.getData().isEmpty()) {
@ -1392,12 +1390,12 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
deviceSubscriptionData.setAction(Constants.UNSUBSCRIBED); deviceSubscriptionData.setAction(Constants.UNSUBSCRIBED);
deviceSubscriptionData.setActionTriggeredBy(subscription.getUnsubscribedBy()); deviceSubscriptionData.setActionTriggeredBy(subscription.getUnsubscribedBy());
deviceSubscriptionData deviceSubscriptionData
.setActionTriggeredTimestamp(subscription.getUnsubscribedTimestamp()); .setActionTriggeredTimestamp(subscription.getUnsubscribedTimestamp().getTime() / 1000);
} else { } else {
deviceSubscriptionData.setAction(Constants.SUBSCRIBED); deviceSubscriptionData.setAction(Constants.SUBSCRIBED);
deviceSubscriptionData.setActionTriggeredBy(subscription.getSubscribedBy()); deviceSubscriptionData.setActionTriggeredBy(subscription.getSubscribedBy());
deviceSubscriptionData deviceSubscriptionData
.setActionTriggeredTimestamp(subscription.getSubscribedTimestamp()); .setActionTriggeredTimestamp(subscription.getSubscribedTimestamp().getTime() / 1000);
} }
deviceSubscriptionData.setActionType(subscription.getActionTriggeredFrom()); deviceSubscriptionData.setActionType(subscription.getActionTriggeredFrom());
deviceSubscriptionData.setStatus(subscription.getStatus()); deviceSubscriptionData.setStatus(subscription.getStatus());

View File

@ -40,7 +40,7 @@ public class ScheduledAppSubscriptionCleanupTask extends RandomlyAssignedSchedul
@Override @Override
public void executeRandomlyAssignedTask() { public void executeRandomlyAssignedTask() {
try { try {
if(super.isQualifiedToExecuteTask()) { if(isQualifiedToExecuteTask()) {
subscriptionManager.cleanScheduledSubscriptions(); subscriptionManager.cleanScheduledSubscriptions();
} }
} catch (SubscriptionManagementException e) { } catch (SubscriptionManagementException e) {

View File

@ -68,7 +68,7 @@ public class ScheduledAppSubscriptionTask extends RandomlyAssignedScheduleTask {
@Override @Override
public void executeRandomlyAssignedTask() { public void executeRandomlyAssignedTask() {
if(super.isQualifiedToExecuteTask()) { if(isQualifiedToExecuteTask()) {
try { try {
ScheduledSubscriptionDTO subscriptionDTO = subscriptionManager.getPendingScheduledSubscription( ScheduledSubscriptionDTO subscriptionDTO = subscriptionManager.getPendingScheduledSubscription(
this.taskName); this.taskName);

View File

@ -40,6 +40,8 @@ import org.wso2.carbon.ntask.core.service.TaskService;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.TextStyle; import java.time.format.TextStyle;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
@ -64,24 +66,27 @@ public class ScheduledAppSubscriptionTaskManager {
* either {@link org.wso2.carbon.device.mgt.common.DeviceIdentifier} if {@param subType} is * either {@link org.wso2.carbon.device.mgt.common.DeviceIdentifier} if {@param subType} is
* equal to DEVICE or {@link String} if {@param subType} is USER, ROLE or GROUP * equal to DEVICE or {@link String} if {@param subType} is USER, ROLE or GROUP
* @param subscriptionType subscription type. E.g. <code>DEVICE, USER, ROLE, GROUP</code> * @param subscriptionType subscription type. E.g. <code>DEVICE, USER, ROLE, GROUP</code>
* {@see {@link org.wso2.carbon.device.application.mgt.common.SubscriptionType}} * {@see {@link SubscriptionType}}
* @param action action subscription action. E.g. {@code INSTALL/UNINSTALL} * @param action action subscription action. E.g. {@code INSTALL/UNINSTALL}
* {@see {@link org.wso2.carbon.device.application.mgt.common.SubAction}} * {@see {@link SubAction}}
* @param timestamp timestamp to schedule the application subscription * @param timestamp timestamp to schedule the application subscription
* @throws ApplicationOperationTaskException if error occurred while scheduling the subscription * @throws ApplicationOperationTaskException if error occurred while scheduling the subscription
*/ */
public void scheduleAppSubscriptionTask(String applicationUUID, List<?> subscribers, public void scheduleAppSubscriptionTask(String applicationUUID, List<?> subscribers,
SubscriptionType subscriptionType, SubAction action, LocalDateTime timestamp) SubscriptionType subscriptionType, SubAction action, long timestamp)
throws ApplicationOperationTaskException { throws ApplicationOperationTaskException {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(timestamp * 1000));
String space = " "; String space = " ";
String cronExpression = String cronExpression =
String.valueOf(timestamp.getSecond()) + space + timestamp.getMinute() + space + timestamp.getHour() calendar.get(Calendar.SECOND) + space + calendar.get(Calendar.MINUTE) + space
+ space + timestamp.getDayOfMonth() + space + timestamp.getMonth().getDisplayName(TextStyle.SHORT, + calendar.get(Calendar.HOUR_OF_DAY) + space + calendar.get(Calendar.DAY_OF_MONTH) + space
Locale.getDefault()).toUpperCase() + " ? " + timestamp.getYear(); + calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault()).toUpperCase() + " ? "
+ calendar.get(Calendar.YEAR);
if (!CronExpression.isValidExpression(cronExpression)) { if (!CronExpression.isValidExpression(cronExpression)) {
String msg = "The cron expression [" + cronExpression + "] generated by the" + " timestamp [" + timestamp String msg = "The cron expression [" + cronExpression + "] generated by the" + " timestamp [" + timestamp
.toString() + "] is invalid"; + "] is invalid";
log.error(msg); log.error(msg);
throw new ApplicationOperationTaskException(msg); throw new ApplicationOperationTaskException(msg);
} }

View File

@ -274,7 +274,7 @@ public class DAOUtil {
} }
subscription.setStatus(ExecutionStatus.valueOf(rs.getString("STATUS"))); subscription.setStatus(ExecutionStatus.valueOf(rs.getString("STATUS")));
subscription.setScheduledAt(rs.getTimestamp("SCHEDULED_AT").toLocalDateTime()); subscription.setScheduledAt(rs.getLong("SCHEDULED_AT"));
subscription.setScheduledBy(rs.getString("SCHEDULED_BY")); subscription.setScheduledBy(rs.getString("SCHEDULED_BY"));
subscription.setDeleted(rs.getBoolean("DELETED")); subscription.setDeleted(rs.getBoolean("DELETED"));
subscriptionDTOS.add(subscription); subscriptionDTOS.add(subscription);

View File

@ -63,7 +63,7 @@ public class OAuthUtils {
apiApplicationKeyInfo = apiManagementProviderService. apiApplicationKeyInfo = apiManagementProviderService.
generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(), generateAndRetrieveApplicationKeys(registrationProfile.getApplicationName(),
registrationProfile.getTags(), Constants.ApplicationInstall.DEFAULT_TOKEN_TYPE, registrationProfile.getTags(), Constants.ApplicationInstall.DEFAULT_TOKEN_TYPE,
registrationProfile.getApplicationName(), registrationProfile.isAllowedToAllDomains(), null, registrationProfile.isAllowedToAllDomains(),
Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD); Constants.ApplicationInstall.DEFAULT_VALIDITY_PERIOD);
} finally { } finally {
PrivilegedCarbonContext.endTenantFlow(); PrivilegedCarbonContext.endTenantFlow();

View File

@ -22,13 +22,12 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.publisher.api</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.publisher.api</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - Application Management Publisher API</name> <name>WSO2 Carbon - Application Management Publisher API</name>
<description>WSO2 Carbon - Application Management Publisher API</description> <description>WSO2 Carbon - Application Management Publisher API</description>

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -22,13 +22,12 @@
<parent> <parent>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.application.mgt.store.api</artifactId> <artifactId>org.wso2.carbon.device.application.mgt.store.api</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>war</packaging> <packaging>war</packaging>
<name>WSO2 Carbon - Application Management Store API</name> <name>WSO2 Carbon - Application Management Store API</name>
<description>WSO2 Carbon - Application Management Store API</description> <description>WSO2 Carbon - Application Management Store API</description>

View File

@ -32,6 +32,7 @@ import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.Size;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
@ -129,7 +130,7 @@ public interface SubscriptionManagementAPI {
name = "timestamp", name = "timestamp",
value = "Timestamp of scheduled install/uninstall operation" value = "Timestamp of scheduled install/uninstall operation"
) )
@QueryParam("timestamp") String timestamp @QueryParam("timestamp") long timestamp
); );
@POST @POST
@ -182,7 +183,7 @@ public interface SubscriptionManagementAPI {
name = "timestamp", name = "timestamp",
value = "Timestamp of scheduled install/uninstall operation" value = "Timestamp of scheduled install/uninstall operation"
) )
@QueryParam("timestamp") String timestamp @QueryParam("timestamp") long timestamp
); );
@POST @POST
@ -229,7 +230,7 @@ public interface SubscriptionManagementAPI {
name = "timestamp", name = "timestamp",
value = "Timestamp of scheduled ent. install operation" value = "Timestamp of scheduled ent. install operation"
) )
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@ApiParam( @ApiParam(
name = "requiresUpdatingExternal", name = "requiresUpdatingExternal",
value = "Should external system such as Google EMM APIs need to be updated." value = "Should external system such as Google EMM APIs need to be updated."
@ -287,7 +288,7 @@ public interface SubscriptionManagementAPI {
name = "timestamp", name = "timestamp",
value = "Timestamp of scheduled ent app install operation" value = "Timestamp of scheduled ent app install operation"
) )
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@ApiParam( @ApiParam(
name = "requiresUpdatingExternal", name = "requiresUpdatingExternal",
value = "Should external system such as Google EMM APIs need to be updated." value = "Should external system such as Google EMM APIs need to be updated."
@ -337,6 +338,28 @@ public interface SubscriptionManagementAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getAppInstalledDevices( Response getAppInstalledDevices(
@ApiParam(
name = "name",
value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.",
required = false)
@Size(max = 45)
String name,
@ApiParam(
name = "user",
value = "The username of the owner of the device.",
required = false)
@QueryParam("user")
String user,
@ApiParam(
name = "ownership",
allowableValues = "BYOD, COPE",
value = "Provide the ownership status of the device. The following values can be assigned:\n" +
"- BYOD: Bring Your Own Device\n" +
"- COPE: Corporate-Owned, Personally-Enabled",
required = false)
@QueryParam("ownership")
@Size(max = 45)
String ownership,
@ApiParam( @ApiParam(
name="uuid", name="uuid",
value="uuid of the application release.", value="uuid of the application release.",

View File

@ -31,6 +31,7 @@ import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.application.mgt.common.ErrorResponse; import org.wso2.carbon.device.application.mgt.common.ErrorResponse;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
@ -111,6 +112,32 @@ public interface SubscriptionManagementAdminAPI {
response = ErrorResponse.class) response = ErrorResponse.class)
}) })
Response getAppInstalledDevices( Response getAppInstalledDevices(
@ApiParam(
name = "name",
value = "The device name. For example, Nexus devices can have names, suhc as shamu, bullhead or angler.",
required = false)
@Size(max = 45)
String name,
@ApiParam(
name = "user",
value = "The username of the owner of the device.",
required = false)
@QueryParam("user")
String user,
@ApiParam(
name = "action",
value = "The action, subscribed or unsubscribed.",
required = false)
@Size(max = 45)
@QueryParam("action") String action,
@ApiParam(
name = "actionStatus",
value = "Provide the action status details")
@QueryParam("actionStatus") String actionStatus,
@ApiParam(
name = "status",
value = "Provide the device status details, such as active or inactive.")
@QueryParam("status") List<String> status,
@ApiParam( @ApiParam(
name = "uuid", name = "uuid",
value = "uuid of the application release.", value = "uuid of the application release.",

View File

@ -33,6 +33,8 @@ import org.wso2.carbon.device.application.mgt.common.BasicUserInfo;
import org.wso2.carbon.device.application.mgt.common.BasicUserInfoList; import org.wso2.carbon.device.application.mgt.common.BasicUserInfoList;
import org.wso2.carbon.device.application.mgt.common.RoleList; import org.wso2.carbon.device.application.mgt.common.RoleList;
import org.wso2.carbon.device.application.mgt.common.DeviceGroupList; import org.wso2.carbon.device.application.mgt.common.DeviceGroupList;
import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException; import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException; import org.wso2.carbon.device.application.mgt.core.exception.ForbiddenException;
@ -73,9 +75,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@PathParam("action") String action, @PathParam("action") String action,
@Valid List<DeviceIdentifier> deviceIdentifiers, @Valid List<DeviceIdentifier> deviceIdentifiers,
@QueryParam("timestamp") String timestamp) { @QueryParam("timestamp") long timestamp) {
try { try {
if (StringUtils.isEmpty(timestamp)) { if (0 == timestamp) {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
ApplicationInstallResponse response = subscriptionManager ApplicationInstallResponse response = subscriptionManager
.performBulkAppOperation(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(), action); .performBulkAppOperation(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(), action);
@ -114,9 +116,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@PathParam("subType") String subType, @PathParam("subType") String subType,
@PathParam("action") String action, @PathParam("action") String action,
@Valid List<String> subscribers, @Valid List<String> subscribers,
@QueryParam("timestamp") String timestamp) { @QueryParam("timestamp") long timestamp) {
try { try {
if (StringUtils.isEmpty(timestamp)) { if (0 == timestamp) {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
ApplicationInstallResponse response = subscriptionManager ApplicationInstallResponse response = subscriptionManager
.performBulkAppOperation(uuid, subscribers, subType, action); .performBulkAppOperation(uuid, subscribers, subType, action);
@ -155,10 +157,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@PathParam("action") String action, @PathParam("action") String action,
@Valid List<DeviceIdentifier> deviceIdentifiers, @Valid List<DeviceIdentifier> deviceIdentifiers,
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) { @QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) {
try { try {
if (StringUtils.isEmpty(timestamp)) { if (0 == timestamp) {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
subscriptionManager subscriptionManager
.performEntAppSubscription(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(), .performEntAppSubscription(uuid, deviceIdentifiers, SubscriptionType.DEVICE.toString(),
@ -202,10 +204,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@PathParam("subType") String subType, @PathParam("subType") String subType,
@PathParam("action") String action, @PathParam("action") String action,
@Valid List<String> subscribers, @Valid List<String> subscribers,
@QueryParam("timestamp") String timestamp, @QueryParam("timestamp") long timestamp,
@QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) { @QueryParam("requiresUpdatingExternal") boolean requiresUpdatingExternal) {
try { try {
if (StringUtils.isEmpty(timestamp)) { if (0 == timestamp) {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
subscriptionManager.performEntAppSubscription(uuid, subscribers, subType, action, requiresUpdatingExternal); subscriptionManager.performEntAppSubscription(uuid, subscribers, subType, action, requiresUpdatingExternal);
String msg = "Application release which has UUID " + uuid + " is installed to subscriber's valid device" String msg = "Application release which has UUID " + uuid + " is installed to subscriber's valid device"
@ -253,11 +255,11 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
* @return {@link Response} of the operation * @return {@link Response} of the operation
*/ */
private Response scheduleApplicationOperationTask(String applicationUUID, List<?> subscribers, private Response scheduleApplicationOperationTask(String applicationUUID, List<?> subscribers,
SubscriptionType subType, SubAction subAction, String timestamp) { SubscriptionType subType, SubAction subAction, long timestamp) {
try { try {
ScheduledAppSubscriptionTaskManager subscriptionTaskManager = new ScheduledAppSubscriptionTaskManager(); ScheduledAppSubscriptionTaskManager subscriptionTaskManager = new ScheduledAppSubscriptionTaskManager();
subscriptionTaskManager.scheduleAppSubscriptionTask(applicationUUID, subscribers, subType, subAction, subscriptionTaskManager.scheduleAppSubscriptionTask(applicationUUID, subscribers, subType, subAction,
LocalDateTime.parse(timestamp, DateTimeFormatter.ISO_LOCAL_DATE_TIME)); timestamp);
} catch (ApplicationOperationTaskException e) { } catch (ApplicationOperationTaskException e) {
String msg = "Error occurred while scheduling the application install operation"; String msg = "Error occurred while scheduling the application install operation";
log.error(msg, e); log.error(msg, e);
@ -273,6 +275,9 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@Produces("application/json") @Produces("application/json")
@Path("/{uuid}/devices") @Path("/{uuid}/devices")
public Response getAppInstalledDevices( public Response getAppInstalledDevices(
@QueryParam("name") String name,
@QueryParam("user") String user,
@QueryParam("ownership") String ownership,
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@DefaultValue("0") @DefaultValue("0")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@ -281,8 +286,31 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
@QueryParam("status") List<String> status) { @QueryParam("status") List<String> status) {
try { try {
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationResult subscribedDeviceDetails = subscriptionManager PaginationRequest request = new PaginationRequest(offset, limit);
.getAppInstalledDevices(offset, limit, uuid, status); if (name != null && !name.isEmpty()) {
request.setDeviceName(name);
}
if (user != null && !user.isEmpty()) {
request.setOwner(user);
}
if (ownership != null && !ownership.isEmpty()) {
RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
PaginationResult subscribedDeviceDetails = subscriptionManager.getAppInstalledDevices(request, uuid);
DeviceList devices = new DeviceList(); DeviceList devices = new DeviceList();
devices.setList((List<Device>) subscribedDeviceDetails.getData()); devices.setList((List<Device>) subscribedDeviceDetails.getData());
devices.setCount(subscribedDeviceDetails.getRecordsTotal()); devices.setCount(subscribedDeviceDetails.getRecordsTotal());
@ -292,8 +320,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) { } catch (BadRequestException e) {
String msg = "Found invalid payload for getting application which has UUID: " + uuid String msg = "User requested details are not valid";
+ ". Hence verify the payload";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) { } catch (ForbiddenException e) {

View File

@ -18,6 +18,7 @@
package org.wso2.carbon.device.application.mgt.store.api.services.impl.admin; package org.wso2.carbon.device.application.mgt.store.api.services.impl.admin;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException; import org.wso2.carbon.device.application.mgt.common.exception.ApplicationManagementException;
@ -26,6 +27,8 @@ import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException
import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException; import org.wso2.carbon.device.application.mgt.core.exception.NotFoundException;
import org.wso2.carbon.device.application.mgt.core.util.APIUtil; import org.wso2.carbon.device.application.mgt.core.util.APIUtil;
import org.wso2.carbon.device.application.mgt.store.api.services.admin.SubscriptionManagementAdminAPI; import org.wso2.carbon.device.application.mgt.store.api.services.admin.SubscriptionManagementAdminAPI;
import org.wso2.carbon.device.application.mgt.store.api.services.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
@ -36,6 +39,7 @@ import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.List;
/** /**
* Implementation of Subscription Management related APIs. * Implementation of Subscription Management related APIs.
@ -51,6 +55,11 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
@Produces("application/json") @Produces("application/json")
@Path("/{uuid}") @Path("/{uuid}")
public Response getAppInstalledDevices( public Response getAppInstalledDevices(
@QueryParam("name") String name,
@QueryParam("user") String user,
@QueryParam("action") String action,
@QueryParam("actionStatus") String actionStatus,
@QueryParam("status") List<String> status,
@PathParam("uuid") String uuid, @PathParam("uuid") String uuid,
@DefaultValue("0") @DefaultValue("0")
@QueryParam("offset") int offset, @QueryParam("offset") int offset,
@ -58,22 +67,49 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
@QueryParam("limit") int limit) { @QueryParam("limit") int limit) {
try { try {
PaginationRequest request = new PaginationRequest(offset, limit);
if (name != null && !name.isEmpty()) {
request.setDeviceName(name);
}
if (user != null && !user.isEmpty()) {
request.setOwner(user);
}
if (action != null && !action.isEmpty()) {
RequestValidationUtil.validateAction(action);
}
if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true;
for (String statusString : status) {
if (StringUtils.isNotBlank(statusString)) {
isStatusEmpty = false;
break;
}
}
if (!isStatusEmpty) {
RequestValidationUtil.validateStatus(status);
request.setStatusList(status);
}
}
if (actionStatus != null && !actionStatus.isEmpty()) {
if (StringUtils.isNotBlank(actionStatus)) {
RequestValidationUtil.validateStatusFiltering(actionStatus);
}
}
SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager(); SubscriptionManager subscriptionManager = APIUtil.getSubscriptionManager();
PaginationResult subscriptionData = subscriptionManager PaginationResult subscriptionData = subscriptionManager.getAppSubscriptionDetails
.getAppSubscriptionDetails(offset, limit, uuid); (request, uuid, actionStatus, action);
return Response.status(Response.Status.OK).entity(subscriptionData).build(); return Response.status(Response.Status.OK).entity(subscriptionData).build();
} catch (NotFoundException e) { } catch (NotFoundException e) {
String msg = "Application with application release UUID: " + uuid + " is not found"; String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build(); return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) { } catch (BadRequestException e) {
String msg = "Found invalid payload for getting application which has UUID: " + uuid String msg = "User requested details are not valid";
+ ". Hence verify the payload";
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build(); return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) { } catch (ApplicationManagementException e) {
String msg = "Error occurred while getting app installed devices which has application release UUID of: " String msg = "Error occurred while getting app installed devices which has application release UUID of: "
+ uuid; + uuid;
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} }

View File

@ -0,0 +1,116 @@
/*
* Copyright (c) 2021, 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.application.mgt.store.api.services.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.application.mgt.core.exception.BadRequestException;
import org.wso2.carbon.device.application.mgt.store.api.util.Constants;
import java.util.List;
public class RequestValidationUtil {
private static final Log log = LogFactory.getLog(RequestValidationUtil.class);
/**
* Checks if user requested status codes are valid.
*
* @param statusList status codes upon to filter operation logs using status
*/
public static void validateStatus(List<String> statusList) throws BadRequestException {
for (String status : statusList) {
switch (status) {
case "ACTIVE":
case "INACTIVE":
case "UNCLAIMED":
case "UNREACHABLE":
case "SUSPENDED":
case "DISENROLLMENT_REQUESTED":
case "REMOVED":
case "BLOCKED":
case "CREATED":
break;
default:
String msg = "Invalid enrollment status type: " + status + ". \nValid status types " +
"are ACTIVE | INACTIVE | UNCLAIMED | UNREACHABLE | SUSPENDED | " +
"DISENROLLMENT_REQUESTED | REMOVED | BLOCKED | CREATED";
log.error(msg);
throw new BadRequestException(msg);
}
}
}
/**
* Checks if user requested action is valid.
*
* @param action action upon to filter devices using action
*/
public static void validateAction(String action) throws BadRequestException {
if (action.equals("SUBSCRIBED") || action.equals("UNSUBSCRIBED")) {
} else {
String msg = "Invalid action type received.Valid action types are SUBSCRIBED | UNSUBSCRIBED";
log.error(msg);
throw new BadRequestException(msg);
}
}
/**
* Checks if user requested ownerships are valid.
*
* @param ownership ownerships upon to filter devices using ownership
*/
public static void validateOwnershipType(String ownership) throws BadRequestException {
switch (ownership) {
case "BYOD":
case "COPE":
case "WORK_PROFILE":
case "GOOGLE_ENTERPRISE":
case "COSU":
case "FULLY_MANAGED":
case "DEDICATED_DEVICE":
break;
default:
String msg = "Invalid ownership type received.Valid ownership types are BYOD | COPE | WORK_PROFILE |" +
"GOOGLE_ENTERPRISE | COSU | FULLY_MANAGED | DEDICATED_DEVICE";
log.error(msg);
throw new BadRequestException(msg);
}
}
/**
* Checks if user requested Action status codes are valid.
*
* @param status status codes upon to filter operation logs using status
*/
public static void validateStatusFiltering(String status) throws BadRequestException {
if (Constants.OperationStatus.COMPLETED.toUpperCase().equals(status)
|| Constants.OperationStatus.ERROR.toUpperCase().equals(status)
|| Constants.OperationStatus.NOTNOW.toUpperCase().equals(status)
|| Constants.OperationStatus.REPEATED.toUpperCase().equals(status)
|| Constants.OperationStatus.PENDING.toUpperCase().equals(status)
|| Constants.OperationStatus.IN_PROGRESS.toUpperCase().equals(status)) {
} else {
String msg = "Invalid status type: " + status + ". \nValid status types are COMPLETED | ERROR | " +
"IN_PROGRESS | NOTNOW | PENDING | REPEATED";
log.error(msg);
throw new BadRequestException(msg);
}
}
}

View File

@ -0,0 +1,101 @@
/*
* 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.
*
*
* Copyright (c) 2019, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
*
* Entgra (pvt) Ltd. 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.application.mgt.store.api.util;
/**
* Holds the constants used by DeviceImpl Management Admin web application.
*/
public class Constants {
public static final String USER_CLAIM_EMAIL_ADDRESS = "http://wso2.org/claims/emailaddress";
public static final String USER_CLAIM_FIRST_NAME = "http://wso2.org/claims/givenname";
public static final String USER_CLAIM_LAST_NAME = "http://wso2.org/claims/lastname";
public static final String USER_CLAIM_CREATED = "http://wso2.org/claims/created";
public static final String USER_CLAIM_MODIFIED = "http://wso2.org/claims/modified";
public static final String USER_CLAIM_DEVICES = "http://wso2.org/claims/devices";
public static final String PRIMARY_USER_STORE = "PRIMARY";
public static final String DEFAULT_STREAM_VERSION = "1.0.0";
public static final String SCOPE = "scope";
public static final String JDBC_USERSTOREMANAGER = "org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager";
public static final String DEFAULT_SIMPLE_DATE_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
public static final int DEFAULT_PAGE_LIMIT = 50;
public static final String FORWARD_SLASH = "/";
public static final String ANDROID = "android";
public static final String ANDROID_POLICY_VALIDATOR = "io.entgra.proprietary.platform.android." +
"core.polcy.AndroidPolicyPayloadValidator";
public static final String IOS = "ios";
public static final String WINDOWS = "windows";
public final class OperationStatus {
private OperationStatus () { throw new AssertionError(); }
public static final String COMPLETED = "completed";
public static final String ERROR = "error";
public static final String IN_PROGRESS = "in_progress";
public static final String PENDING = "pending";
public static final String NOTNOW = "notnow";
public static final String REPEATED = "repeated";
}
public static final String DEVICES = "devices";
public static final String ATTRIBUTE_DISPLAY_NAME = "DisplayName";
public static final String ATTRIBUTE_DESCRIPTION = "Description";
public static final String EXTERNAL_DEVICE_CLAIM_DISPLAY_NAME = "Devices";
public static final String EXTERNAL_DEVICE_CLAIM_DESCRIPTION = "Device list";
public final class ErrorMessages {
private ErrorMessages () { throw new AssertionError(); }
public static final String STATUS_BAD_REQUEST_MESSAGE_DEFAULT = "Bad Request";
}
public final class DeviceConstants {
private DeviceConstants () { throw new AssertionError(); }
public static final String APPLICATION_JSON = "application/json";
public static final String HEADER_CONTENT_TYPE = "Content-Type";
}
public final class Permission {
private Permission() { throw new AssertionError(); }
public static final String ADMIN = "/permission/admin";
public static final String LOGIN = "/permission/admin/login";
public static final String DEVICE_MGT = "/permission/admin/device-mgt";
public static final String APP_MGT = "/permission/admin/app-mgt";
}
}

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -22,13 +22,12 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>application-mgt</artifactId> <artifactId>application-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - Application Management Component</name> <name>WSO2 Carbon - Application Management Component</name>
<description>WSO2 Carbon - Application Management Component</description> <description>WSO2 Carbon - Application Management Component</description>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -134,9 +134,16 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.springframework</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <artifactId>spring-web</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>commons-codec.wso2</groupId> <groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
@ -147,24 +154,11 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>org.wso2.carbon.logging</artifactId>
@ -207,11 +201,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -133,9 +133,15 @@
</profiles> </profiles>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec.wso2</groupId> <groupId>commons-codec.wso2</groupId>
@ -147,14 +153,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
@ -204,11 +202,6 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -38,13 +38,12 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId> <artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>bundle</packaging> <packaging>bundle</packaging>
<name>WSO2 Carbon - Certificate Management Core</name> <name>WSO2 Carbon - Certificate Management Core</name>
<description>WSO2 Carbon - Certificate Management Core</description> <description>WSO2 Carbon - Certificate Management Core</description>
@ -72,8 +71,8 @@
org.wso2.carbon.certificate.mgt.core.util org.wso2.carbon.certificate.mgt.core.util
</Private-Package> </Private-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging, org.apache.commons.logging,
org.apache.commons.collections.map, org.apache.commons.collections.map,
javax.security.auth.x500, javax.security.auth.x500,

View File

@ -22,14 +22,13 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>certificate-mgt</artifactId> <artifactId>certificate-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version>
<packaging>pom</packaging> <packaging>pom</packaging>
<name>WSO2 Carbon - Certificate Management Component</name> <name>WSO2 Carbon - Certificate Management Component</name>
<url>http://wso2.org</url> <url>http://wso2.org</url>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -140,8 +140,8 @@
org.apache.axis2.deployment.*, org.apache.axis2.deployment.*,
org.apache.commons.lang;version="${commons-lang.wso2.osgi.version.range}", org.apache.commons.lang;version="${commons-lang.wso2.osgi.version.range}",
org.apache.commons.logging, org.apache.commons.logging,
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.w3c.dom, org.w3c.dom,
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -82,8 +82,8 @@
org.wso2.carbon.device.mgt.extensions.pull.notification.* org.wso2.carbon.device.mgt.extensions.pull.notification.*
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging, org.apache.commons.logging,
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.core.service org.wso2.carbon.device.mgt.core.service

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -135,7 +135,8 @@
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
com.google.gson, com.google.gson,
org.osgi.service.component, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.operation.mgt,
org.wso2.carbon.device.mgt.common.push.notification, org.wso2.carbon.device.mgt.common.push.notification,
org.apache.commons.logging, org.apache.commons.logging,

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -126,13 +126,13 @@
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.apache.commons.logging, org.apache.commons.logging,
org.osgi.service.component, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.operation.mgt,
org.wso2.carbon.device.mgt.common.push.notification, org.wso2.carbon.device.mgt.common.push.notification,
org.wso2.carbon.device.mgt.common, org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.core.service, org.wso2.carbon.device.mgt.core.service,
org.osgi.framework,
org.wso2.carbon.device.mgt.core.operation.mgt, org.wso2.carbon.device.mgt.core.operation.mgt,
org.wso2.carbon.core, org.wso2.carbon.core,
com.google.gson, com.google.gson,

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -148,7 +148,8 @@
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.apache.commons.logging, org.apache.commons.logging,
org.osgi.service.component, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.operation.mgt,
org.wso2.carbon.device.mgt.common.push.notification, org.wso2.carbon.device.mgt.common.push.notification,
@ -157,7 +158,6 @@
org.wso2.carbon.device.mgt.core.service, org.wso2.carbon.device.mgt.core.service,
org.wso2.carbon.event.output.adapter.core, org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception, org.wso2.carbon.event.output.adapter.core.exception,
org.osgi.framework,
org.wso2.carbon.device.mgt.core.operation.mgt, org.wso2.carbon.device.mgt.core.operation.mgt,
org.wso2.carbon.core, org.wso2.carbon.core,
org.wso2.carbon.device.application.mgt.common.*, org.wso2.carbon.device.application.mgt.common.*,

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt-extensions</artifactId> <artifactId>device-mgt-extensions</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -135,14 +135,14 @@
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.apache.commons.logging, org.apache.commons.logging,
org.osgi.service.component, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.wso2.carbon.context, org.wso2.carbon.context,
org.wso2.carbon.device.mgt.common.operation.mgt, org.wso2.carbon.device.mgt.common.operation.mgt,
org.wso2.carbon.device.mgt.common.push.notification, org.wso2.carbon.device.mgt.common.push.notification,
org.wso2.carbon.device.mgt.core.service, org.wso2.carbon.device.mgt.core.*,
org.wso2.carbon.event.output.adapter.core, org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception, org.wso2.carbon.event.output.adapter.core.exception,
org.osgi.framework,
org.wso2.carbon.core, org.wso2.carbon.core,
org.wso2.carbon.device.mgt.common.* org.wso2.carbon.device.mgt.common.*
</Import-Package> </Import-Package>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>carbon-devicemgt</artifactId> <artifactId>carbon-devicemgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath> <relativePath>../../pom.xml</relativePath>
</parent> </parent>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -146,13 +146,13 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.springframework</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>spring-web</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId> <artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -107,8 +107,8 @@
org.wso2.carbon.device.mgt.analytics.data.publisher.*;version="${carbon.device.mgt.version}" org.wso2.carbon.device.mgt.analytics.data.publisher.*;version="${carbon.device.mgt.version}"
</Export-Package> </Export-Package>
<Import-Package> <Import-Package>
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging.*, org.apache.commons.logging.*,
org.wso2.carbon.utils.multitenancy, org.wso2.carbon.utils.multitenancy,
org.wso2.carbon.context;version="${carbon.kernel.version.range}", org.wso2.carbon.context;version="${carbon.kernel.version.range}",

View File

@ -20,7 +20,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>

View File

@ -22,7 +22,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -146,18 +146,13 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.springframework</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId> <artifactId>spring-web</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -165,11 +160,6 @@
<artifactId>commons-httpclient</artifactId> <artifactId>commons-httpclient</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
@ -200,11 +190,6 @@
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId> <artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
@ -340,6 +325,12 @@
<dependency> <dependency>
<groupId>javax.ws.rs</groupId> <groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId> <artifactId>javax.ws.rs-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.commons</groupId> <groupId>org.wso2.carbon.commons</groupId>
@ -350,11 +341,6 @@
<groupId>org.wso2.carbon.analytics</groupId> <groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId> <artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
@ -402,11 +388,6 @@
<artifactId>org.wso2.carbon.event.stream.persistence.stub</artifactId> <artifactId>org.wso2.carbon.event.stream.persistence.stub</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId> <artifactId>powermock-module-testng</artifactId>

View File

@ -0,0 +1,84 @@
/*
* Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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 org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
public class GeoCluster {
private final GeoCoordinate coordinates;
private final GeoCoordinate southWestBound;
private final GeoCoordinate northEastBound;
private final long count;
private final String geohashPrefix;
private final String deviceIdentification;
private final String deviceName;
private final String deviceType;
private final String lastSeen;
public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound,
long count, String geohashPrefix, String deviceIdentification, String deviceName,
String deviceType, String lastSeen) {
this.coordinates = coordinates;
this.southWestBound = southWestBound;
this.northEastBound = northEastBound;
this.count = count;
this.geohashPrefix = geohashPrefix;
this.deviceIdentification = deviceIdentification;
this.deviceName = deviceName;
this.deviceType = deviceType;
this.lastSeen = lastSeen;
}
public String getGeohashPrefix() {
return geohashPrefix;
}
public long getCount() {
return count;
}
public GeoCoordinate getCoordinates() {
return coordinates;
}
public GeoCoordinate getSouthWestBound() {
return southWestBound;
}
public GeoCoordinate getNorthEastBound() {
return northEastBound;
}
public String getDeviceIdentification() {
return deviceIdentification;
}
public String getDeviceName() {
return deviceName;
}
public String getDeviceType() {
return deviceType;
}
public String getLastSeen() {
return lastSeen;
}
}

View File

@ -67,64 +67,65 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public interface DeviceEventManagementService { public interface DeviceEventManagementService {
@POST //todo:amalka
@Path("/{type}") // @POST
@ApiOperation( // @Path("/{type}")
produces = MediaType.APPLICATION_JSON, // @ApiOperation(
httpMethod = "POST", // produces = MediaType.APPLICATION_JSON,
value = "Adding the Event Type Definition", // httpMethod = "POST",
notes = "Add the event definition for a device.", // value = "Adding the Event Type Definition",
tags = "Device Event Management", // notes = "Add the event definition for a device.",
extensions = { // tags = "Device Event Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
} // })
) // }
@ApiResponses( // )
value = { // @ApiResponses(
@ApiResponse( // value = {
code = 200, // @ApiResponse(
message = "OK. \n Successfully added the event defintion.", // code = 200,
responseHeaders = { // message = "OK. \n Successfully added the event defintion.",
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "ETag", // @ResponseHeader(
description = "Entity Tag of the response resource.\n" + // name = "ETag",
"Used by caches, or in conditional requests."), // description = "Entity Tag of the response resource.\n" +
@ResponseHeader( // "Used by caches, or in conditional requests."),
name = "Last-Modified", // @ResponseHeader(
description = // name = "Last-Modified",
"Date and time the resource was last modified.\n" + // description =
"Used by caches, or in conditional requests."), // "Date and time the resource was last modified.\n" +
} // "Used by caches, or in conditional requests."),
), // }
@ApiResponse( // ),
code = 400, // @ApiResponse(
message = // code = 400,
"Bad Request. \n"), // message =
@ApiResponse( // "Bad Request. \n"),
code = 406, // @ApiResponse(
message = "Not Acceptable.\n The requested media type is not supported"), // code = 406,
@ApiResponse( // message = "Not Acceptable.\n The requested media type is not supported"),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Server error occurred while fetching the " + // code = 500,
"list of supported device types.", // message = "Internal Server Error. \n Server error occurred while fetching the " +
response = ErrorResponse.class) // "list of supported device types.",
} // response = ErrorResponse.class)
) // }
Response deployDeviceTypeEventDefinition( // )
@ApiParam(name = "type", value = "The device type, such as android, ios, and windows.") // Response deployDeviceTypeEventDefinition(
@PathParam("type")String deviceType, // @ApiParam(name = "type", value = "The device type, such as android, ios, and windows.")
@ApiParam(name = "skipPersist", value = "Is it required to persist the data or not") // @PathParam("type")String deviceType,
@QueryParam("skipPersist") boolean skipPersist, // @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
@ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants") // @QueryParam("skipPersist") boolean skipPersist,
@QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, // @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
@ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.", // @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
required = true) // @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.",
@Valid DeviceTypeEvent deviceTypeEvent); // required = true)
// @Valid DeviceTypeEvent deviceTypeEvent);
@DELETE @DELETE
@Path("/{type}") @Path("/{type}")
@ -178,183 +179,186 @@ public interface DeviceEventManagementService {
"ios, and windows.", required = false) "ios, and windows.", required = false)
@PathParam("type")String deviceType); @PathParam("type")String deviceType);
@GET //todo:amalka
@Path("/{type}/{deviceId}") // @GET
@ApiOperation( // @Path("/{type}/{deviceId}")
produces = MediaType.APPLICATION_JSON, // @ApiOperation(
httpMethod = "GET", // produces = MediaType.APPLICATION_JSON,
value = "Getting Device Events", // httpMethod = "GET",
notes = "Get the events for the device.", // value = "Getting Device Events",
tags = "Device Event Management", // notes = "Get the events for the device.",
extensions = { // tags = "Device Event Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
} // })
) // }
@ApiResponses( // )
value = { // @ApiResponses(
@ApiResponse( // value = {
code = 200, // @ApiResponse(
message = "OK. \n Successfully fetched the event definition.", // code = 200,
response = EventRecords.class, // message = "OK. \n Successfully fetched the event definition.",
responseHeaders = { // response = EventRecords.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "ETag", // @ResponseHeader(
description = "Entity Tag of the response resource.\n" + // name = "ETag",
"Used by caches, or in conditional requests."), // description = "Entity Tag of the response resource.\n" +
@ResponseHeader( // "Used by caches, or in conditional requests."),
name = "Last-Modified", // @ResponseHeader(
description = // name = "Last-Modified",
"Date and time the resource was last modified.\n" + // description =
"Used by caches, or in conditional requests."), // "Date and time the resource was last modified.\n" +
} // "Used by caches, or in conditional requests."),
), // }
@ApiResponse( // ),
code = 400, // @ApiResponse(
message = // code = 400,
"Bad Request. \n"), // message =
@ApiResponse( // "Bad Request. \n"),
code = 406, // @ApiResponse(
message = "Not Acceptable.\n The requested media type is not supported"), // code = 406,
@ApiResponse( // message = "Not Acceptable.\n The requested media type is not supported"),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Server error occurred while fetching the " + // code = 500,
"list of supported device types.", // message = "Internal Server Error. \n Server error occurred while fetching the " +
response = ErrorResponse.class) // "list of supported device types.",
} // response = ErrorResponse.class)
) // }
Response getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false) // )
@PathParam("deviceId") String deviceId, // Response getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false)
@ApiParam(name = "from", value = "unix timestamp to retrieve", required = false) // @PathParam("deviceId") String deviceId,
@QueryParam("from") long from, // @ApiParam(name = "from", value = "unix timestamp to retrieve", required = false)
@ApiParam(name = "to", value = "unix time to retrieve", required = false) // @QueryParam("from") long from,
@QueryParam("to") long to, // @ApiParam(name = "to", value = "unix time to retrieve", required = false)
@ApiParam(name = "type", value = "name of the device type", required = false) // @QueryParam("to") long to,
@PathParam("type") String deviceType, // @ApiParam(name = "type", value = "name of the device type", required = false)
@ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false) // @PathParam("type") String deviceType,
@QueryParam("offset") int offset, // @ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false)
@ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) // @QueryParam("offset") int offset,
@QueryParam("limit") int limit); // @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false)
// @QueryParam("limit") int limit);
@GET //todo:amalka
@Path("last-known/{type}/{deviceId}") // @GET
@ApiOperation( // @Path("last-known/{type}/{deviceId}")
produces = MediaType.APPLICATION_JSON, // @ApiOperation(
httpMethod = "GET", // produces = MediaType.APPLICATION_JSON,
value = "Getting Last Known Device Events", // httpMethod = "GET",
notes = "Get the last known events for the device.", // value = "Getting Last Known Device Events",
tags = "Device Event Management", // notes = "Get the last known events for the device.",
extensions = { // tags = "Device Event Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
} // })
) // }
@ApiResponses( // )
value = { // @ApiResponses(
@ApiResponse( // value = {
code = 200, // @ApiResponse(
message = "OK. \n Successfully fetched the event.", // code = 200,
response = EventRecords.class, // message = "OK. \n Successfully fetched the event.",
responseHeaders = { // response = EventRecords.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "ETag", // @ResponseHeader(
description = "Entity Tag of the response resource.\n" + // name = "ETag",
"Used by caches, or in conditional requests."), // description = "Entity Tag of the response resource.\n" +
@ResponseHeader( // "Used by caches, or in conditional requests."),
name = "Last-Modified", // @ResponseHeader(
description = // name = "Last-Modified",
"Date and time the resource was last modified.\n" + // description =
"Used by caches, or in conditional requests."), // "Date and time the resource was last modified.\n" +
} // "Used by caches, or in conditional requests."),
), // }
@ApiResponse( // ),
code = 400, // @ApiResponse(
message = // code = 400,
"Bad Request. \n"), // message =
@ApiResponse( // "Bad Request. \n"),
code = 406, // @ApiResponse(
message = "Not Acceptable.\n The requested media type is not supported"), // code = 406,
@ApiResponse( // message = "Not Acceptable.\n The requested media type is not supported"),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Server error occurred while fetching the " + // code = 500,
"list of supported device types.", // message = "Internal Server Error. \n Server error occurred while fetching the " +
response = ErrorResponse.class) // "list of supported device types.",
} // response = ErrorResponse.class)
) // }
Response getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = true) // )
@PathParam("deviceId") String deviceId, // Response getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = true)
@ApiParam(name = "type", value = "name of the device type", required = true) // @PathParam("deviceId") String deviceId,
@PathParam("type") String deviceType, // @ApiParam(name = "type", value = "name of the device type", required = true)
@ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false) // @PathParam("type") String deviceType,
@QueryParam("limit") int limit); // @ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false)
// @QueryParam("limit") int limit);
@GET //todo:amalka
@Path("filter/{type}/{parameter}") // @GET
@ApiOperation( // @Path("filter/{type}/{parameter}")
produces = MediaType.APPLICATION_JSON, // @ApiOperation(
httpMethod = "GET", // produces = MediaType.APPLICATION_JSON,
value = "Getting the filtered devices", // httpMethod = "GET",
notes = "Get the list of devices based on the filter parameter", // value = "Getting the filtered devices",
tags = "Device Event Management", // notes = "Get the list of devices based on the filter parameter",
extensions = { // tags = "Device Event Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
} // })
) // }
@ApiResponses( // )
value = { // @ApiResponses(
@ApiResponse( // value = {
code = 200, // @ApiResponse(
message = "OK. \n Successfully fetched the event.", // code = 200,
response = EventRecords.class, // message = "OK. \n Successfully fetched the event.",
responseHeaders = { // response = EventRecords.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "ETag", // @ResponseHeader(
description = "Entity Tag of the response resource.\n" + // name = "ETag",
"Used by caches, or in conditional requests."), // description = "Entity Tag of the response resource.\n" +
@ResponseHeader( // "Used by caches, or in conditional requests."),
name = "Last-Modified", // @ResponseHeader(
description = // name = "Last-Modified",
"Date and time the resource was last modified.\n" + // description =
"Used by caches, or in conditional requests."), // "Date and time the resource was last modified.\n" +
} // "Used by caches, or in conditional requests."),
), // }
@ApiResponse( // ),
code = 400, // @ApiResponse(
message = // code = 400,
"Bad Request. \n"), // message =
@ApiResponse( // "Bad Request. \n"),
code = 406, // @ApiResponse(
message = "Not Acceptable.\n The requested media type is not supported"), // code = 406,
@ApiResponse( // message = "Not Acceptable.\n The requested media type is not supported"),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Server error occurred while fetching the " + // code = 500,
"list of supported device types.", // message = "Internal Server Error. \n Server error occurred while fetching the " +
response = ErrorResponse.class) // "list of supported device types.",
} // response = ErrorResponse.class)
) // }
Response getFilteredDevices( // )
@ApiParam(name = "type", value = "name of the device type", required = true) // Response getFilteredDevices(
@PathParam("type") String deviceType, // @ApiParam(name = "type", value = "name of the device type", required = true)
@ApiParam(name = "type", value = "name of the parameter", required = true) // @PathParam("type") String deviceType,
@PathParam("type") String parameter, // @ApiParam(name = "type", value = "name of the parameter", required = true)
@ApiParam(name = "limit", value = "minimum value the parameter can have", required = false) // @PathParam("type") String parameter,
@QueryParam("min") double min, // @ApiParam(name = "limit", value = "minimum value the parameter can have", required = false)
@ApiParam(name = "max", value = "max value the parameter can have", required = false) // @QueryParam("min") double min,
@QueryParam("max") double max // @ApiParam(name = "max", value = "max value the parameter can have", required = false)
); // @QueryParam("max") double max
// );
@GET @GET
@Path("/{type}") @Path("/{type}")

View File

@ -269,6 +269,12 @@ public interface DeviceManagementService {
@QueryParam("ownership") @QueryParam("ownership")
@Size(max = 45) @Size(max = 45)
String ownership, String ownership,
@ApiParam(
name = "serialNumber",
value = "The serial number of the device.",
required = false)
@QueryParam("serialNumber")
String serialNumber,
@ApiParam( @ApiParam(
name = "status", name = "status",
value = "Provide the device status details, such as active or inactive.", value = "Provide the device status details, such as active or inactive.",

View File

@ -16,7 +16,6 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.jaxrs.service.api; package org.wso2.carbon.device.mgt.jaxrs.service.api;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
@ -32,6 +31,7 @@ import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag; import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope; import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes; import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.geo.service.Alert; import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper;
@ -41,7 +41,6 @@ import javax.validation.Valid;
import javax.validation.constraints.Size; import javax.validation.constraints.Size;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.PUT; import javax.ws.rs.PUT;
@ -51,7 +50,7 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.util.ArrayList; import java.util.List;
@SwaggerDefinition( @SwaggerDefinition(
info = @Info( info = @Info(
@ -97,71 +96,72 @@ public interface GeoLocationBasedService {
/** /**
* Retrieve Analytics for the device type * Retrieve Analytics for the device type
*/ */
@GET //todo:amalka
@Path("stats/{deviceType}/{deviceId}") // @GET
@ApiOperation( // @Path("stats/{deviceType}/{deviceId}")
consumes = "application/json", // @ApiOperation(
produces = "application/json", // consumes = "application/json",
httpMethod = "GET", // produces = "application/json",
value = "Getting the Location Details of a Device", // httpMethod = "GET",
notes = "Get the location details of a device during a define time period.", // value = "Getting the Location Details of a Device",
response = Response.class, // notes = "Get the location details of a device during a define time period.",
tags = "Geo Service Management", // response = Response.class,
extensions = { // tags = "Geo Service Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view")
} // })
) // }
@ApiResponses(value = { // )
@ApiResponse( // @ApiResponses(value = {
code = 200, // @ApiResponse(
message = "OK.", // code = 200,
response = Response.class, // message = "OK.",
responseHeaders = { // response = Response.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "Last-Modified", // @ResponseHeader(
description = "Date and time the resource was last modified.\n" + // name = "Last-Modified",
"Used by caches, or in conditional requests."), // description = "Date and time the resource was last modified.\n" +
}), // "Used by caches, or in conditional requests."),
@ApiResponse( // }),
code = 400, // @ApiResponse(
message = "Bad Request. \n Invalid Device Identifiers found.", // code = 400,
response = Response.class), // message = "Bad Request. \n Invalid Device Identifiers found.",
@ApiResponse( // response = Response.class),
code = 401, // @ApiResponse(
message = "Unauthorized. \n Unauthorized request."), // code = 401,
@ApiResponse( // message = "Unauthorized. \n Unauthorized request."),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Error on retrieving stats", // code = 500,
response = Response.class) // message = "Internal Server Error. \n Error on retrieving stats",
}) // response = Response.class)
Response getGeoDeviceStats( // })
@ApiParam( // Response getGeoDeviceStats(
name = "deviceId", // @ApiParam(
value = "The device ID.", // name = "deviceId",
required = true) // value = "The device ID.",
@PathParam("deviceId") String deviceId, // required = true)
@ApiParam( // @PathParam("deviceId") String deviceId,
name = "device-type", // @ApiParam(
value = "The device type, such as ios, android, or windows.", // name = "device-type",
required = true) // value = "The device type, such as ios, android, or windows.",
@PathParam("deviceType") // required = true)
@Size(max = 45) // @PathParam("deviceType")
String deviceType, // @Size(max = 45)
@ApiParam( // String deviceType,
name = "from", // @ApiParam(
value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", // name = "from",
required = true) // value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.",
@QueryParam("from") long from, // required = true)
@ApiParam( // @QueryParam("from") long from,
name = "to", // @ApiParam(
value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", // name = "to",
required = true) // value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.",
@QueryParam("to") long to); // required = true)
// @QueryParam("to") long to);
/** /**
* Get data to show device locations in a map * Get data to show device locations in a map
@ -208,6 +208,7 @@ public interface GeoLocationBasedService {
message = "Internal Server Error. \n Error on retrieving stats", message = "Internal Server Error. \n Error on retrieving stats",
response = Response.class) response = Response.class)
}) })
@Deprecated
Response getGeoDeviceLocations( Response getGeoDeviceLocations(
@ApiParam( @ApiParam(
name = "deviceType", name = "deviceType",
@ -244,6 +245,124 @@ public interface GeoLocationBasedService {
defaultValue ="2") defaultValue ="2")
@QueryParam("zoom") int zoom); @QueryParam("zoom") int zoom);
@Path("stats/geo-view")
@GET
@Consumes("application/json")
@Produces("application/json")
@ApiOperation(
consumes = "application/json",
produces = "application/json",
httpMethod = "GET",
value = "Getting geo view of devices",
notes = "Get the details of the devices that are within the map. The map area is enclosed with four " +
"coordinates in the shape of a square or rectangle. This is done by defining two points of the " +
"map. The other two points are automatically created using the given points. " +
"You can define the zoom level or scale of the map too.",
response = Response.class,
tags = "Geo Service Management",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:analytics-view")
})
}
)
@ApiResponses(value = {
@ApiResponse(
code = 200,
message = "OK.",
response = Response.class,
responseHeaders = {
@ResponseHeader(
name = "Content-Type",
description = "The content type of the body"),
@ResponseHeader(
name = "Last-Modified",
description = "Date and time the resource was last modified.\n" +
"Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid parameters found.",
response = Response.class),
@ApiResponse(
code = 401,
message = "Unauthorized. \n Unauthorized request."),
@ApiResponse(
code = 500,
message = "Internal Server Error. \n Error on retrieving stats",
response = Response.class)
})
Response getGeoDeviceView(
@ApiParam(
name = "minLat",
value = "Define the minimum latitude of the geofence.",
required = true,
defaultValue ="79.85213577747345")
@QueryParam("minLat") double minLat,
@ApiParam(
name = "maxLat",
value = "Define the maximum latitude of the geofence.",
required = true,
defaultValue ="79.85266149044037")
@QueryParam("maxLat") double maxLat,
@ApiParam(
name = "minLong",
value = "Define the minimum longitude of the geofence.",
required = true,
defaultValue ="6.909673257977737")
@QueryParam("minLong") double minLong,
@ApiParam(
name = "maxLong",
value = "Define the maximum longitude of the geofence",
required = true,
defaultValue ="6.909673257977737")
@QueryParam("maxLong") double maxLong,
@ApiParam(
name = "zoom",
value = "Define the level to zoom or scale the map. You can define any value between 1 to 14.",
required = true,
defaultValue ="2")
@QueryParam("zoom") int zoom,
@ApiParam(
name = "deviceType",
value = "Optional Device type name.")
@QueryParam("deviceType") List<String> deviceTypes,
@ApiParam(
name = "deviceIdentifier",
value = "Optional Device Identifier.")
@QueryParam("deviceIdentifier") List<String> deviceIdentifiers,
@ApiParam(
name = "status",
value = "Optional Device status.")
@QueryParam("status") List<EnrolmentInfo.Status> statuses,
@ApiParam(
name = "ownership",
value = "Optional Device ownership.")
@QueryParam("ownership") List<String> ownerships,
@ApiParam(
name = "owner",
value = "Optional Device owner.")
@QueryParam("owner") List<String> owners,
@ApiParam(
name = "noClusters",
value = "Optional include devices only.")
@QueryParam("noClusters") boolean noClusters,
@ApiParam(
name = "createdBefore",
value = "Optional Device created before timestamp.")
@QueryParam("createdBefore") long createdBefore,
@ApiParam(
name = "createdAfter",
value = "Optional Device created after timestamp..")
@QueryParam("createdAfter") long createdAfter,
@ApiParam(
name = "updatedBefore",
value = "Optional Device updated before timestamp.")
@QueryParam("updatedBefore") long updatedBefore,
@ApiParam(
name = "updatedAfter",
value = "Optional Device updated after timestamp.")
@QueryParam("updatedAfter") long updatedAfter);
/** /**
* Create Geo alerts * Create Geo alerts
@ -602,128 +721,130 @@ public interface GeoLocationBasedService {
/** /**
* Retrieve Geo alerts history * Retrieve Geo alerts history
*/ */
@GET //todo:amalka
@Path("alerts/history/{deviceType}/{deviceId}") // @GET
@ApiOperation( // @Path("alerts/history/{deviceType}/{deviceId}")
consumes = "application/json", // @ApiOperation(
produces = "application/json", // consumes = "application/json",
httpMethod = "GET", // produces = "application/json",
value = "Getting the Geo Service Alert History of a Device", // httpMethod = "GET",
notes = "Get the geo alert history of a device during the defined time period.", // value = "Getting the Geo Service Alert History of a Device",
response = Response.class, // notes = "Get the geo alert history of a device during the defined time period.",
tags = "Geo Service Management", // response = Response.class,
extensions = { // tags = "Geo Service Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
} // })
) // }
@ApiResponses(value = { // )
@ApiResponse( // @ApiResponses(value = {
code = 200, // @ApiResponse(
message = "OK.", // code = 200,
response = Response.class, // message = "OK.",
responseHeaders = { // response = Response.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "Last-Modified", // @ResponseHeader(
description = "Date and time the resource was last modified.\n" + // name = "Last-Modified",
"Used by caches, or in conditional requests.") // description = "Date and time the resource was last modified.\n" +
}), // "Used by caches, or in conditional requests.")
@ApiResponse( // }),
code = 400, // @ApiResponse(
message = "Bad Request. \n Invalid Device Identifiers found.", // code = 400,
response = Response.class), // message = "Bad Request. \n Invalid Device Identifiers found.",
@ApiResponse( // response = Response.class),
code = 401, // @ApiResponse(
message = "Unauthorized. \n Unauthorized request."), // code = 401,
@ApiResponse( // message = "Unauthorized. \n Unauthorized request."),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Error on retrieving stats", // code = 500,
response = Response.class) // message = "Internal Server Error. \n Error on retrieving stats",
}) // response = Response.class)
Response getGeoAlertsHistory( // })
@ApiParam( // Response getGeoAlertsHistory(
name = "deviceId", // @ApiParam(
value = "The device ID.", // name = "deviceId",
required = true) // value = "The device ID.",
@PathParam("deviceId") String deviceId, // required = true)
@ApiParam( // @PathParam("deviceId") String deviceId,
name = "device-type", // @ApiParam(
value = "The device type, such as ios, android, or windows.", // name = "device-type",
required = true) // value = "The device type, such as ios, android, or windows.",
@PathParam("deviceType") // required = true)
@Size(max = 45) // @PathParam("deviceType")
String deviceType, // @Size(max = 45)
@ApiParam( // String deviceType,
name = "from", // @ApiParam(
value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.", // name = "from",
required = true) // value = "Define the time to start getting the geo location history of the device in the Epoch or UNIX format.",
@QueryParam("from") long from, // required = true)
@ApiParam( // @QueryParam("from") long from,
name = "to", // @ApiParam(
value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.", // name = "to",
required = true) // value = "Define the time to finish getting the geo location history of the device in the Epoch or UNIX format.",
@QueryParam("to") long to); // required = true)
// @QueryParam("to") long to);
/** /**
* Retrieve Geo alerts history for geo clusters * Retrieve Geo alerts history for geo clusters
*/ */
@GET //todo:amalka
@Path("alerts/history") // @GET
@ApiOperation( // @Path("alerts/history")
consumes = "application/json", // @ApiOperation(
produces = "application/json", // consumes = "application/json",
httpMethod = "GET", // produces = "application/json",
value = "Retrieve Geo alerts history for geo clusters", // httpMethod = "GET",
notes = "Retrieving geo alert history of all defined alerts for geo clusters", // value = "Retrieve Geo alerts history for geo clusters",
response = Response.class, // notes = "Retrieving geo alert history of all defined alerts for geo clusters",
tags = "Geo Service Management", // response = Response.class,
extensions = { // tags = "Geo Service Management",
@Extension(properties = { // extensions = {
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage") // @Extension(properties = {
}) // @ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
} // })
) // }
@ApiResponses(value = { // )
@ApiResponse( // @ApiResponses(value = {
code = 200, // @ApiResponse(
message = "OK.", // code = 200,
response = Response.class, // message = "OK.",
responseHeaders = { // response = Response.class,
@ResponseHeader( // responseHeaders = {
name = "Content-Type", // @ResponseHeader(
description = "The content type of the body"), // name = "Content-Type",
@ResponseHeader( // description = "The content type of the body"),
name = "Last-Modified", // @ResponseHeader(
description = "Date and time the resource was last modified.\n" + // name = "Last-Modified",
"Used by caches, or in conditional requests.") // description = "Date and time the resource was last modified.\n" +
}), // "Used by caches, or in conditional requests.")
@ApiResponse( // }),
code = 400, // @ApiResponse(
message = "Bad Request. \n Invalid Device Identifiers found.", // code = 400,
response = Response.class), // message = "Bad Request. \n Invalid Device Identifiers found.",
@ApiResponse( // response = Response.class),
code = 401, // @ApiResponse(
message = "Unauthorized. \n Unauthorized request."), // code = 401,
@ApiResponse( // message = "Unauthorized. \n Unauthorized request."),
code = 500, // @ApiResponse(
message = "Internal Server Error. \n Error on retrieving stats", // code = 500,
response = Response.class) // message = "Internal Server Error. \n Error on retrieving stats",
}) // response = Response.class)
Response getGeoAlertsHistoryForGeoClusters( // })
@ApiParam( // Response getGeoAlertsHistoryForGeoClusters(
name = "from", // @ApiParam(
value = "Get stats from what time", // name = "from",
required = true) // value = "Get stats from what time",
@QueryParam("from") long from, // required = true)
@ApiParam( // @QueryParam("from") long from,
name = "to", // @ApiParam(
value = "Get stats up to what time", // name = "to",
required = true) // value = "Get stats up to what time",
@QueryParam("to") long to); // required = true)
// @QueryParam("to") long to);
/** /**

View File

@ -26,7 +26,6 @@ import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
@ -36,7 +35,6 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException; import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.ComplianceFeature;
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException; import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -52,7 +50,6 @@ import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto; import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint; import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException; import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
@ -280,19 +277,20 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
i++; i++;
} }
if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type // todo: amalka: commented data publishing
, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) // if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type
, Constants.DEFAULT_STREAM_VERSION, metaData // , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
, null, payloadData)) { // , Constants.DEFAULT_STREAM_VERSION, metaData
// , null, payloadData)) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} else { // } else {
String msg = "Error occurred while publishing the event."; // String msg = "Error occurred while publishing the event.";
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} // }
} catch (DataPublisherConfigurationException e) { // } catch (DataPublisherConfigurationException e) {
String msg = "Error occurred while publishing the event."; // String msg = "Error occurred while publishing the event.";
log.error(msg, e); // log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
String msg = "Error occurred when checking for authorization"; String msg = "Error occurred when checking for authorization";
log.error(msg, e); log.error(msg, e);
@ -380,19 +378,20 @@ public class DeviceAgentServiceImpl implements DeviceAgentService {
i++; i++;
} }
if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type // todo: amalka: commented data publishing
, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()) // if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type
, Constants.DEFAULT_STREAM_VERSION, metaData // , PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
, null, payloadData)) { // , Constants.DEFAULT_STREAM_VERSION, metaData
// , null, payloadData)) {
return Response.status(Response.Status.OK).build(); return Response.status(Response.Status.OK).build();
} else { // } else {
String msg = "Error occurred while publishing the event."; // String msg = "Error occurred while publishing the event.";
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} // }
} catch (DataPublisherConfigurationException e) { // } catch (DataPublisherConfigurationException e) {
String msg = "Error occurred while publishing the event."; // String msg = "Error occurred while publishing the event.";
log.error(msg, e); // log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
String msg = "Error occurred when checking for authorization"; String msg = "Error occurred when checking for authorization";
log.error(msg, e); log.error(msg, e);

View File

@ -4,29 +4,13 @@ import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Stub; import org.apache.axis2.client.Stub;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.commons.SortType;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable;
import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventRecords;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType; import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService; import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceEventManagementService;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants; import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
@ -43,21 +27,14 @@ import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.validation.Valid;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
@ -81,49 +58,50 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
private static final String MQTT_CONTENT_VALIDATOR = "default"; private static final String MQTT_CONTENT_VALIDATOR = "default";
private static final String TIMESTAMP_FIELD_NAME = "_timestamp"; private static final String TIMESTAMP_FIELD_NAME = "_timestamp";
private static AnalyticsDataAPI getAnalyticsDataAPI() { //todo:amalka
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); // private static AnalyticsDataAPI getAnalyticsDataAPI() {
AnalyticsDataAPI analyticsDataAPI = // PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null); // AnalyticsDataAPI analyticsDataAPI =
if (analyticsDataAPI == null) { // (AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
String msg = "Analytics api service has not initialized."; // if (analyticsDataAPI == null) {
log.error(msg); // String msg = "Analytics api service has not initialized.";
throw new IllegalStateException(msg); // log.error(msg);
} // throw new IllegalStateException(msg);
return analyticsDataAPI; // }
} // return analyticsDataAPI;
// }
private static EventRecords getAllEventsForDevice(String tableName, String query, List<SortByField> sortByFields // private static EventRecords getAllEventsForDevice(String tableName, String query, List<SortByField> sortByFields
, int offset, int limit) throws AnalyticsException { // , int offset, int limit) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); // int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI(); // AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
EventRecords eventRecords = new EventRecords(); // EventRecords eventRecords = new EventRecords();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query); // int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) { // if (eventCount == 0) {
eventRecords.setCount(0); // eventRecords.setCount(0);
} // }
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit, // List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit,
sortByFields); // sortByFields);
List<String> recordIds = getRecordIds(resultEntries); // List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds); // AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
eventRecords.setCount(eventCount); // eventRecords.setCount(eventCount);
List<Record> records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response); // List<Record> records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response);
records.sort(new Comparator<Record>() { // records.sort(new Comparator<Record>() {
@Override public int compare(Record r1, Record r2) { // @Override public int compare(Record r1, Record r2) {
return Long.compare(r2.getTimestamp(), r1.getTimestamp()); // return Long.compare(r2.getTimestamp(), r1.getTimestamp());
} // }
}); // });
eventRecords.setList(records); // eventRecords.setList(records);
return eventRecords; // return eventRecords;
} // }
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) { // private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>(); // List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) { // for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId()); // ids.add(searchResult.getId());
} // }
return ids; // return ids;
} // }
/** /**
* Retrieves the stream definition from das for the given device type. * Retrieves the stream definition from das for the given device type.
@ -195,65 +173,66 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
/** /**
* Deploy Event Stream, Receiver, Publisher and Store Configuration. * Deploy Event Stream, Receiver, Publisher and Store Configuration.
*/ */
@POST //todo:amalka
@Path("/{type}") // @POST
@Override // @Path("/{type}")
public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType, // @Override
@QueryParam("skipPersist") boolean skipPersist, // public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
@QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants, // @QueryParam("skipPersist") boolean skipPersist,
@Valid DeviceTypeEvent deviceTypeEvent) { // @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
TransportType transportType = deviceTypeEvent.getTransportType(); // @Valid DeviceTypeEvent deviceTypeEvent) {
EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList(); // TransportType transportType = deviceTypeEvent.getTransportType();
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); // EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
try { // String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 || // try {
deviceType == null || transportType == null || // if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { // deviceType == null || transportType == null ||
String errorMessage = "Invalid Payload"; // !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
log.error(errorMessage); // String errorMessage = "Invalid Payload";
return Response.status(Response.Status.BAD_REQUEST).build(); // log.error(errorMessage);
} // return Response.status(Response.Status.BAD_REQUEST).build();
String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain); // }
String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION; // String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain);
publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); // String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION;
publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); // publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
if (!skipPersist) { // publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType);
publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes); // if (!skipPersist) {
} // publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes);
publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType); // }
try { // publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType);
PrivilegedCarbonContext.startTenantFlow(); // try {
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( // PrivilegedCarbonContext.startTenantFlow();
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true); // PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) { // MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes); // if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType); // publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
} // publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, isSharedWithAllTenants, deviceType);
} finally { // }
PrivilegedCarbonContext.endTenantFlow(); // } finally {
} // PrivilegedCarbonContext.endTenantFlow();
return Response.ok().build(); // }
} catch (AxisFault e) { // return Response.ok().build();
log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e); // } catch (AxisFault e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e);
} catch (RemoteException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Failed to connect with the remote services:" + tenantDomain, e); // } catch (RemoteException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error("Failed to connect with the remote services:" + tenantDomain, e);
} catch (JWTClientException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e); // } catch (JWTClientException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
} catch (UserStoreException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e); // } catch (UserStoreException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
} catch (DeviceManagementException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e); // } catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
} catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType, // } catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) {
e); // log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType,
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // e);
} // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} // }
// }
/** /**
* Delete device type specific artifacts from DAS. * Delete device type specific artifacts from DAS.
@ -349,175 +328,178 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
/** /**
* Returns device specific data for the give period of time. * Returns device specific data for the give period of time.
*/ */
@GET //todo:amalka
@Path("/{type}/{deviceId}") // @GET
@Override // @Path("/{type}/{deviceId}")
public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, // @Override
@QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset") // public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
int offset, @QueryParam("limit") int limit) { // @QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset")
if (from == 0 || to == 0) { // int offset, @QueryParam("limit") int limit) {
String errorMessage = "Invalid values for from/to"; // if (from == 0 || to == 0) {
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); // String errorMessage = "Invalid values for from/to";
} // return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
if (limit == 0) { // }
String errorMessage = "Invalid values for offset/limit"; // if (limit == 0) {
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); // String errorMessage = "Invalid values for offset/limit";
} // return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
String fromDate = String.valueOf(from); // }
String toDate = String.valueOf(to); // String fromDate = String.valueOf(from);
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId // String toDate = String.valueOf(to);
+ " AND _timestamp : [" + fromDate + " TO " + toDate + "]"; // String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); // + " AND _timestamp : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); // String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
try { // String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain));
if (deviceType == null || // try {
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { // if (deviceType == null ||
String errorMessage = "Invalid device type"; // !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
log.error(errorMessage); // String errorMessage = "Invalid device type";
return Response.status(Response.Status.BAD_REQUEST).build(); // log.error(errorMessage);
} // return Response.status(Response.Status.BAD_REQUEST).build();
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( // }
new DeviceIdentifier(deviceId, deviceType))) { // if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // new DeviceIdentifier(deviceId, deviceType))) {
} // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
List<SortByField> sortByFields = new ArrayList<>(); // }
SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); // List<SortByField> sortByFields = new ArrayList<>();
sortByFields.add(sortByField); // SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC);
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit); // sortByFields.add(sortByField);
return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); // EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit);
} catch (AnalyticsException e) { // return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build();
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (AnalyticsException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} catch (DeviceAccessAuthorizationException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
log.error(e.getErrorMessage(), e); // } catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error(e.getErrorMessage(), e);
} catch (DeviceManagementException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (DeviceManagementException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} // }
// }
/** /**
* Returns last known data points up to the limit if limit is specified. Otherwise returns last known data point. * Returns last known data points up to the limit if limit is specified. Otherwise returns last known data point.
* Limit parameter needs to be zero or positive. * Limit parameter needs to be zero or positive.
*/ */
@GET //todo:amalka
@Path("/last-known/{type}/{deviceId}") // @GET
@Override // @Path("/last-known/{type}/{deviceId}")
public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType, @QueryParam("limit") int limit) { // @Override
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId; // public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType, @QueryParam("limit") int limit) {
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); // String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId;
String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); // String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
try { // String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain));
if (deviceType == null || // try {
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { // if (deviceType == null ||
String errorMessage = "Invalid device type"; // !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
log.error(errorMessage); // String errorMessage = "Invalid device type";
return Response.status(Response.Status.BAD_REQUEST).build(); // log.error(errorMessage);
} // return Response.status(Response.Status.BAD_REQUEST).build();
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( // }
new DeviceIdentifier(deviceId, deviceType))) { // if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // new DeviceIdentifier(deviceId, deviceType))) {
} // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
List<SortByField> sortByFields = new ArrayList<>(); // }
SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); // List<SortByField> sortByFields = new ArrayList<>();
sortByFields.add(sortByField); // SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC);
if (limit == 0) { // sortByFields.add(sortByField);
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1); // if (limit == 0) {
return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); // EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1);
} else if (limit > 0) { // return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build();
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, limit); // } else if (limit > 0) {
return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build(); // EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, limit);
} else { // return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build();
String errorMessage = "Invalid limit value"; // } else {
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build(); // String errorMessage = "Invalid limit value";
} // return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
} catch (AnalyticsException e) { // }
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (AnalyticsException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} catch (DeviceAccessAuthorizationException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
log.error(e.getErrorMessage(), e); // } catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); // log.error(e.getErrorMessage(), e);
} catch (DeviceManagementException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (DeviceManagementException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} // }
// }
/** /**
* Returns the filterd device list. Devices are filterd using the paramter given and the timestamp of the record. * Returns the filterd device list. Devices are filterd using the paramter given and the timestamp of the record.
* parameter should given as a range. * parameter should given as a range.
*/ */
@GET //todo:amalka
@Path("filter/{type}/{parameter}") // @GET
@Override // @Path("filter/{type}/{parameter}")
public Response getFilteredDevices(@PathParam("type") String deviceType, @PathParam("parameter") String parameter, // @Override
@QueryParam("min") double min, @QueryParam("max") double max) { // public Response getFilteredDevices(@PathParam("type") String deviceType, @PathParam("parameter") String parameter,
String query; // @QueryParam("min") double min, @QueryParam("max") double max) {
Calendar c = java.util.Calendar.getInstance(); // String query;
long currentTimestamp = c.getTimeInMillis(); // Calendar c = java.util.Calendar.getInstance();
long previousTimestamp = currentTimestamp - 300 * 1000; // long currentTimestamp = c.getTimeInMillis();
String fromDate = String.valueOf(previousTimestamp); // long previousTimestamp = currentTimestamp - 300 * 1000;
String toDate = String.valueOf(currentTimestamp); // String fromDate = String.valueOf(previousTimestamp);
if (min != 0 & max != 0) { // String toDate = String.valueOf(currentTimestamp);
query = parameter + " : [" + min + " TO " + max + "]" + // if (min != 0 & max != 0) {
" AND _timestamp : [" + fromDate + " TO " + toDate + "]"; // query = parameter + " : [" + min + " TO " + max + "]" +
} else { // " AND _timestamp : [" + fromDate + " TO " + toDate + "]";
String errorMessage = "The of range values need to be given"; // } else {
log.error(errorMessage); // String errorMessage = "The of range values need to be given";
return Response.status(Response.Status.BAD_REQUEST).build(); // log.error(errorMessage);
} // return Response.status(Response.Status.BAD_REQUEST).build();
// }
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(); //
String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain)); // String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
try { // String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain));
if (deviceType == null || // try {
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) { // if (deviceType == null ||
String errorMessage = "Invalid device type"; // !DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
log.error(errorMessage); // String errorMessage = "Invalid device type";
return Response.status(Response.Status.BAD_REQUEST).build(); // log.error(errorMessage);
} // return Response.status(Response.Status.BAD_REQUEST).build();
// }
List<SortByField> sortByFields = new ArrayList<>(); //
SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC); // List<SortByField> sortByFields = new ArrayList<>();
sortByFields.add(sortByField); // SortByField sortByField = new SortByField(TIMESTAMP_FIELD_NAME, SortType.DESC);
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 100); // sortByFields.add(sortByField);
List<Record> filterdEvents = eventRecords.getRecord(); // EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 100);
List<Record> uniqueFilterdEvents = new ArrayList<Record>(); // List<Record> filterdEvents = eventRecords.getRecord();
Set<String> devices = new HashSet<>(); // List<Record> uniqueFilterdEvents = new ArrayList<Record>();
// Set<String> devices = new HashSet<>();
for (int i = 0; i < filterdEvents.size(); i++) { //
String deviceid = (String) filterdEvents.get(i).getValue("meta_deviceId"); // for (int i = 0; i < filterdEvents.size(); i++) {
if (!devices.contains(deviceid) && DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( // String deviceid = (String) filterdEvents.get(i).getValue("meta_deviceId");
new DeviceIdentifier(deviceid, deviceType))) { // if (!devices.contains(deviceid) && DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
devices.add(deviceid); // new DeviceIdentifier(deviceid, deviceType))) {
uniqueFilterdEvents.add(filterdEvents.get(i)); // devices.add(deviceid);
} // uniqueFilterdEvents.add(filterdEvents.get(i));
} // }
// }
EventRecords filterdRecords = new EventRecords(); //
filterdRecords.setList(uniqueFilterdEvents); // EventRecords filterdRecords = new EventRecords();
return Response.status(Response.Status.OK.getStatusCode()).entity(filterdRecords).build(); // filterdRecords.setList(uniqueFilterdEvents);
// return Response.status(Response.Status.OK.getStatusCode()).entity(filterdRecords).build();
} catch (AnalyticsException e) { //
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (AnalyticsException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} catch (DeviceManagementException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (DeviceManagementException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build(); // log.error(errorMsg);
} catch (DeviceAccessAuthorizationException e) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query; // } catch (DeviceAccessAuthorizationException e) {
log.error(errorMsg); // String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); // log.error(errorMsg);
} // return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} // }
// }
private void publishEventReceivers(String streamNameWithVersion, TransportType transportType private void publishEventReceivers(String streamNameWithVersion, TransportType transportType
@ -613,47 +595,48 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
} }
} }
private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes) //todo:amalka
throws RemoteException, UserStoreException, JWTClientException, // private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes)
EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException { // throws RemoteException, UserStoreException, JWTClientException,
EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub = // EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException {
DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub(); // EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub =
try { // DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub();
AnalyticsTable analyticsTable = new AnalyticsTable(); // try {
analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME); // AnalyticsTable analyticsTable = new AnalyticsTable();
analyticsTable.setStreamVersion(version); // analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME);
analyticsTable.setTableName(streamName); // analyticsTable.setStreamVersion(version);
analyticsTable.setMergeSchema(false); // analyticsTable.setTableName(streamName);
analyticsTable.setPersist(true); // analyticsTable.setMergeSchema(false);
AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1]; // analyticsTable.setPersist(true);
int i = 0; // AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1];
for (Attribute attribute : eventAttributes.getList()) { // int i = 0;
AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); // for (Attribute attribute : eventAttributes.getList()) {
analyticsTableRecord.setColumnName(attribute.getName()); // AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase()); // analyticsTableRecord.setColumnName(attribute.getName());
analyticsTableRecord.setFacet(false); // analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase());
analyticsTableRecord.setIndexed(false); // analyticsTableRecord.setFacet(false);
analyticsTableRecord.setPersist(true); // analyticsTableRecord.setIndexed(false);
analyticsTableRecord.setPrimaryKey(false); // analyticsTableRecord.setPersist(true);
analyticsTableRecord.setScoreParam(false); // analyticsTableRecord.setPrimaryKey(false);
analyticsTableRecords[i] = analyticsTableRecord; // analyticsTableRecord.setScoreParam(false);
i++; // analyticsTableRecords[i] = analyticsTableRecord;
} // i++;
AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord(); // }
analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE); // AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase()); // analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE);
analyticsTableRecord.setFacet(false); // analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase());
analyticsTableRecord.setIndexed(true); // analyticsTableRecord.setFacet(false);
analyticsTableRecord.setPersist(true); // analyticsTableRecord.setIndexed(true);
analyticsTableRecord.setPrimaryKey(false); // analyticsTableRecord.setPersist(true);
analyticsTableRecord.setScoreParam(false); // analyticsTableRecord.setPrimaryKey(false);
analyticsTableRecords[i] = analyticsTableRecord; // analyticsTableRecord.setScoreParam(false);
analyticsTable.setAnalyticsTableRecords(analyticsTableRecords); // analyticsTableRecords[i] = analyticsTableRecord;
eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable); // analyticsTable.setAnalyticsTableRecords(analyticsTableRecords);
} finally { // eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable);
cleanup(eventStreamPersistenceAdminServiceStub); // } finally {
} // cleanup(eventStreamPersistenceAdminServiceStub);
} // }
// }
private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType) private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType)
throws RemoteException, UserStoreException, JWTClientException { throws RemoteException, UserStoreException, JWTClientException {

View File

@ -172,6 +172,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("userPattern") String userPattern, @QueryParam("userPattern") String userPattern,
@QueryParam("role") String role, @QueryParam("role") String role,
@QueryParam("ownership") String ownership, @QueryParam("ownership") String ownership,
@QueryParam("serialNumber") String serialNumber,
@QueryParam("status") List<String> status, @QueryParam("status") List<String> status,
@QueryParam("groupId") int groupId, @QueryParam("groupId") int groupId,
@QueryParam("since") String since, @QueryParam("since") String since,
@ -205,6 +206,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
RequestValidationUtil.validateOwnershipType(ownership); RequestValidationUtil.validateOwnershipType(ownership);
request.setOwnership(ownership); request.setOwnership(ownership);
} }
if (StringUtils.isNotBlank(serialNumber)) {
request.setSerialNumber(serialNumber);
}
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
boolean isStatusEmpty = true; boolean isStatusEmpty = true;
for (String statusString : status){ for (String statusString : status){

View File

@ -38,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices; import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.PaginationRequest; import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
@ -47,13 +48,14 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.geo.service.Alert; import org.wso2.carbon.device.mgt.common.geo.service.Alert;
import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException; import org.wso2.carbon.device.mgt.common.geo.service.AlertAlreadyExistException;
import org.wso2.carbon.device.mgt.common.geo.service.Event; import org.wso2.carbon.device.mgt.common.geo.service.Event;
import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence; import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery;
import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData; import org.wso2.carbon.device.mgt.common.geo.service.GeofenceData;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy; import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.GeoHashLengthStrategy;
import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy; import org.wso2.carbon.device.mgt.core.geo.geoHash.geoHashStrategy.ZoomGeoHashLengthStrategy;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
@ -81,7 +83,10 @@ import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.IOException; import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -91,15 +96,15 @@ import java.util.Map;
*/ */
public class GeoLocationBasedServiceImpl implements GeoLocationBasedService { public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
private static Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class); private static final Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class);
@Path("stats/{deviceType}/{deviceId}") @Path("stats/{deviceType}/{deviceId}")
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId, public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@QueryParam("from") long from, @QueryParam("to") long to) { @QueryParam("from") long from, @QueryParam("to") long to) {
try { try {
if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) { if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()) return Response.status(Response.Status.BAD_REQUEST.getStatusCode())
@ -155,6 +160,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@GET @GET
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
@Deprecated
public Response getGeoDeviceLocations( public Response getGeoDeviceLocations(
@QueryParam("deviceType") String deviceType, @QueryParam("deviceType") String deviceType,
@QueryParam("minLat") double minLat, @QueryParam("minLat") double minLat,
@ -162,6 +168,64 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@QueryParam("minLong") double minLong, @QueryParam("minLong") double minLong,
@QueryParam("maxLong") double maxLong, @QueryParam("maxLong") double maxLong,
@QueryParam("zoom") int zoom) { @QueryParam("zoom") int zoom) {
GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy();
GeoCoordinate southWest = new GeoCoordinate(minLat, minLong);
GeoCoordinate northEast = new GeoCoordinate(maxLat, maxLong);
int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom);
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
GeoQuery geoQuery = new GeoQuery(southWest, northEast, geohashLength);
if (deviceType != null) {
geoQuery.setDeviceTypes(Collections.singletonList(deviceType));
}
List<org.wso2.carbon.device.mgt.jaxrs.beans.GeoCluster> geoClusters = new ArrayList<>();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
try {
List<GeoCluster> newClusters = deviceManagementService.findGeoClusters(geoQuery);
org.wso2.carbon.device.mgt.jaxrs.beans.GeoCluster geoCluster;
String deviceIdentification = null;
String deviceName = null;
String lastSeen = null;
for (GeoCluster gc : newClusters) {
if (gc.getDevice() != null) {
deviceIdentification = gc.getDevice().getDeviceIdentifier();
deviceName = gc.getDevice().getName();
deviceType = gc.getDevice().getType();
lastSeen = simpleDateFormat.format(new Date(gc.getDevice()
.getEnrolmentInfo().getDateOfLastUpdate()));
}
geoCluster = new org.wso2.carbon.device.mgt.jaxrs.beans.GeoCluster(gc.getCoordinates(),
gc.getSouthWestBound(), gc.getNorthEastBound(), gc.getCount(), gc.getGeohashPrefix(),
deviceIdentification, deviceName, deviceType, lastSeen);
geoClusters.add(geoCluster);
}
} catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving geo clusters query: " + new Gson().toJson(geoQuery);
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(geoClusters).build();
}
@Path("stats/geo-view")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getGeoDeviceView(
@QueryParam("minLat") double minLat,
@QueryParam("maxLat") double maxLat,
@QueryParam("minLong") double minLong,
@QueryParam("maxLong") double maxLong,
@QueryParam("zoom") int zoom,
@QueryParam("deviceType") List<String> deviceTypes,
@QueryParam("deviceIdentifier") List<String> deviceIdentifiers,
@QueryParam("status") List<EnrolmentInfo.Status> statuses,
@QueryParam("ownership") List<String> ownerships,
@QueryParam("owner") List<String> owners,
@QueryParam("noClusters") boolean noClusters,
@QueryParam("createdBefore") long createdBefore,
@QueryParam("createdAfter") long createdAfter,
@QueryParam("updatedBefore") long updatedBefore,
@QueryParam("updatedAfter") long updatedAfter) {
GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy(); GeoHashLengthStrategy geoHashLengthStrategy = new ZoomGeoHashLengthStrategy();
GeoCoordinate southWest = new GeoCoordinate(minLat, minLong); GeoCoordinate southWest = new GeoCoordinate(minLat, minLong);
@ -169,15 +233,25 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom); int geohashLength = geoHashLengthStrategy.getGeohashLength(southWest, northEast, zoom);
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService(); DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
List<GeoCluster> geoClusters; List<GeoCluster> geoClusters;
GeoQuery geoQuery = new GeoQuery(southWest, northEast, geohashLength);
geoQuery.setDeviceTypes(deviceTypes);
geoQuery.setDeviceIdentifiers(deviceIdentifiers);
geoQuery.setStatuses(statuses);
geoQuery.setOwners(owners);
geoQuery.setOwnerships(ownerships);
geoQuery.setNoClusters(noClusters);
geoQuery.setCreatedBefore(createdBefore);
geoQuery.setCreatedAfter(createdAfter);
geoQuery.setUpdatedBefore(updatedBefore);
geoQuery.setUpdatedAfter(updatedAfter);
try { try {
geoClusters = deviceManagementService.findGeoClusters(deviceType, southWest, northEast, geohashLength); geoClusters = deviceManagementService.findGeoClusters(geoQuery);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
String msg = "Error occurred while retrieving geo clusters "; String msg = "Error occurred while retrieving geo clusters for query: " + new Gson().toJson(geoQuery);
log.error(msg, e); log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} }
return Response.ok().entity(geoClusters).build(); return Response.ok().entity(geoClusters).build();
} }
@Path("alerts/{alertType}/{deviceType}/{deviceId}") @Path("alerts/{alertType}/{deviceType}/{deviceId}")
@ -185,8 +259,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("alertType") String alertType) { @PathParam("alertType") String alertType) {
try { try {
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, deviceType), new DeviceIdentifier(deviceId, deviceType),
@ -252,8 +326,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId, public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("alertType") String alertType) { @PathParam("alertType") String alertType) {
try { try {
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, deviceType), new DeviceIdentifier(deviceId, deviceType),
@ -317,9 +391,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response removeGeoAlerts(@PathParam("deviceId") String deviceId, public Response removeGeoAlerts(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("alertType") String alertType, @PathParam("alertType") String alertType,
@QueryParam("queryName") String queryName) { @QueryParam("queryName") String queryName) {
try { try {
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, deviceType), new DeviceIdentifier(deviceId, deviceType),
@ -375,8 +449,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getGeoAlerts(@PathParam("deviceId") String deviceId, public Response getGeoAlerts(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@PathParam("alertType") String alertType) { @PathParam("alertType") String alertType) {
try { try {
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized( if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, deviceType), new DeviceIdentifier(deviceId, deviceType),
@ -441,26 +515,26 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
String result = null; String result = null;
switch (alertType) { switch (alertType) {
case GeoServices.ALERT_TYPE_WITHIN: case GeoServices.ALERT_TYPE_WITHIN:
alerts = geoService.getWithinAlerts(); alerts = geoService.getWithinAlerts();
break; break;
case GeoServices.ALERT_TYPE_EXIT: case GeoServices.ALERT_TYPE_EXIT:
alerts = geoService.getExitAlerts(); alerts = geoService.getExitAlerts();
break; break;
case GeoServices.ALERT_TYPE_STATIONARY: case GeoServices.ALERT_TYPE_STATIONARY:
alerts = geoService.getStationaryAlerts(); alerts = geoService.getStationaryAlerts();
break; break;
case GeoServices.ALERT_TYPE_TRAFFIC: case GeoServices.ALERT_TYPE_TRAFFIC:
alerts = geoService.getTrafficAlerts(); alerts = geoService.getTrafficAlerts();
break; break;
case GeoServices.ALERT_TYPE_SPEED: case GeoServices.ALERT_TYPE_SPEED:
result = geoService.getSpeedAlerts(); result = geoService.getSpeedAlerts();
return Response.ok().entity(result).build(); return Response.ok().entity(result).build();
case GeoServices.ALERT_TYPE_PROXIMITY: case GeoServices.ALERT_TYPE_PROXIMITY:
result = geoService.getProximityAlerts(); result = geoService.getProximityAlerts();
return Response.ok().entity(result).build(); return Response.ok().entity(result).build();
default: default:
throw new GeoLocationBasedServiceException("Invalid Alert Type"); throw new GeoLocationBasedServiceException("Invalid Alert Type");
} }
return Response.ok().entity(alerts).build(); return Response.ok().entity(alerts).build();
@ -476,8 +550,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId, public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId,
@PathParam("deviceType") String deviceType, @PathParam("deviceType") String deviceType,
@QueryParam("from") long from, @QueryParam("to") long to) { @QueryParam("from") long from, @QueryParam("to") long to) {
String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS"; String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS";
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
@ -561,8 +635,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
} }
private List<Event> getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName, private List<Event> getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName,
List<String> columns, List<String> columns,
List<SearchResultEntry> searchResults) throws AnalyticsException { List<SearchResultEntry> searchResults) throws AnalyticsException {
List<String> ids = getIds(searchResults); List<String> ids = getIds(searchResults);
List<String> requiredColumns = (columns == null || columns.isEmpty()) ? null : columns; List<String> requiredColumns = (columns == null || columns.isEmpty()) ? null : columns;
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids); AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids);
@ -572,7 +646,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
} }
private List<Event> getSortedEventBeans(Map<String, Event> eventBeanMap, private List<Event> getSortedEventBeans(Map<String, Event> eventBeanMap,
List<SearchResultEntry> searchResults) { List<SearchResultEntry> searchResults) {
List<Event> sortedRecords = new ArrayList<>(); List<Event> sortedRecords = new ArrayList<>();
for (SearchResultEntry entry : searchResults) { for (SearchResultEntry entry : searchResults) {
sortedRecords.add(eventBeanMap.get(entry.getId())); sortedRecords.add(eventBeanMap.get(entry.getId()));
@ -665,7 +739,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getGeofence(@PathParam("fenceId") int fenceId, public Response getGeofence(@PathParam("fenceId") int fenceId,
@QueryParam("requireEventData") boolean requireEventData) { @QueryParam("requireEventData") boolean requireEventData) {
try { try {
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
GeofenceData geofenceData = geoService.getGeoFences(fenceId); GeofenceData geofenceData = geoService.getGeoFences(fenceId);
@ -748,9 +822,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response getGeofence(@QueryParam("offset") int offset, public Response getGeofence(@QueryParam("offset") int offset,
@QueryParam("limit") int limit, @QueryParam("limit") int limit,
@QueryParam("name") String name, @QueryParam("name") String name,
@QueryParam("requireEventData") boolean requireEventData) { @QueryParam("requireEventData") boolean requireEventData) {
try { try {
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService(); GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (offset >= 0 && limit != 0) { if (offset >= 0 && limit != 0) {
@ -819,8 +893,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json") @Consumes("application/json")
@Produces("application/json") @Produces("application/json")
public Response updateGeofence(GeofenceWrapper geofenceWrapper, public Response updateGeofence(GeofenceWrapper geofenceWrapper,
@PathParam("fenceId") int fenceId, @PathParam("fenceId") int fenceId,
@QueryParam("eventIds") int[] eventIds) { @QueryParam("eventIds") int[] eventIds) {
RequestValidationUtil.validateGeofenceData(geofenceWrapper); RequestValidationUtil.validateGeofenceData(geofenceWrapper);
RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig()); RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
try { try {

View File

@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.jaxrs.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse; import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.OldPasswordResetWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper; import org.wso2.carbon.device.mgt.jaxrs.beans.PasswordResetWrapper;
@ -64,8 +63,9 @@ public class CredentialManagementResponseBuilder {
username = CarbonContext.getThreadLocalCarbonContext().getUsername(); username = CarbonContext.getThreadLocalCarbonContext().getUsername();
userStoreManager.updateCredential(username, credentials.getNewPassword(), userStoreManager.updateCredential(username, credentials.getNewPassword(),
credentials.getOldPassword()); credentials.getOldPassword());
DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, //todo:amalka
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); // DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username,
// PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " + return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
username + " was successfully changed.").build(); username + " was successfully changed.").build();
} catch (UserStoreException e) { } catch (UserStoreException e) {
@ -108,8 +108,9 @@ public class CredentialManagementResponseBuilder {
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build(); new ErrorResponse.ErrorResponseBuilder().setMessage(errorMsg).build()).build();
} }
userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword()); userStoreManager.updateCredentialByAdmin(username, credentials.getNewPassword());
DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username, //todo:amalka
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); // DeviceMgtAPIUtils.getIntegrationClientService().resetUserInfo(username,
// PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
return Response.status(Response.Status.OK).entity("UserImpl password by username: " + return Response.status(Response.Status.OK).entity("UserImpl password by username: " +
username + " was successfully changed.").build(); username + " was successfully changed.").build();
} catch (UserStoreException e) { } catch (UserStoreException e) {

View File

@ -45,31 +45,28 @@ import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.apimgt.integration.client.service.IntegrationClientService;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI; import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager; import org.wso2.carbon.device.application.mgt.common.services.SubscriptionManager;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Device; 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.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.MonitoringOperation; import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistory;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException; import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService; import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
@ -171,7 +168,7 @@ public class DeviceMgtAPIUtils {
private static KeyStore trustStore; private static KeyStore trustStore;
private static char[] keyStorePassword; private static char[] keyStorePassword;
private static IntegrationClientService integrationClientService; // private static IntegrationClientService integrationClientService;
private static MetadataManagementService metadataManagementService; private static MetadataManagementService metadataManagementService;
private static OTPManagementService otpManagementService; private static OTPManagementService otpManagementService;
@ -373,24 +370,6 @@ public class DeviceMgtAPIUtils {
return privacyComplianceProvider; return privacyComplianceProvider;
} }
public static IntegrationClientService getIntegrationClientService() {
if (integrationClientService == null) {
synchronized (DeviceMgtAPIUtils.class) {
if (integrationClientService == null) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
integrationClientService = (IntegrationClientService) ctx.getOSGiService(IntegrationClientService.class, null);
if (integrationClientService == null) {
String msg = "IntegrationClientService is not initialized";
log.error(msg);
throw new IllegalStateException(msg);
}
}
}
}
return integrationClientService;
}
/** /**
* Initializing and accessing method for OTPManagementService. * Initializing and accessing method for OTPManagementService.
* *
@ -626,17 +605,18 @@ public class DeviceMgtAPIUtils {
return username; return username;
} }
public static EventsPublisherService getEventPublisherService() { // todo: amalka: commented
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); // public static EventsPublisherService getEventPublisherService() {
EventsPublisherService eventsPublisherService = // PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
(EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null); // EventsPublisherService eventsPublisherService =
if (eventsPublisherService == null) { // (EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null);
String msg = "Event Publisher service has not initialized."; // if (eventsPublisherService == null) {
log.error(msg); // String msg = "Event Publisher service has not initialized.";
throw new IllegalStateException(msg); // log.error(msg);
} // throw new IllegalStateException(msg);
return eventsPublisherService; // }
} // return eventsPublisherService;
// }
public static String getStreamDefinition(String deviceType, String tenantDomain) { public static String getStreamDefinition(String deviceType, String tenantDomain) {
return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", "."); return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", ".");

View File

@ -31,5 +31,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

View File

@ -175,7 +175,8 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceAccessAuthorizationService); .toReturn(this.deviceAccessAuthorizationService);
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -194,19 +195,23 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP, .getDevices(TEST_DEVICE_NAME, TEST_DEVICE_TYPE, null, null, null, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, true, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -319,7 +324,7 @@ public class DeviceManagementServiceImplTest {
.toReturn(this.deviceManagementProviderService); .toReturn(this.deviceManagementProviderService);
Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true); Mockito.when(deviceAccessAuthorizationService.isDeviceAdminUser()).thenReturn(true);
deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, deviceManagementService.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null,
DEFAULT_ROLE, DEFAULT_OWNERSHIP, DEFAULT_STATUS_LIST, 1, DEFAULT_ROLE, DEFAULT_OWNERSHIP, null, DEFAULT_STATUS_LIST, 1,
null, null, false, 10, 5); null, null, false, 10, 5);
} }
@ -339,11 +344,11 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP .getDevices(null, TEST_DEVICE_TYPE, null, DEFAULT_USERNAME, DEFAULT_ROLE, DEFAULT_OWNERSHIP
, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); , null, DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
} }
@ -365,7 +370,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, "newuser", null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 0, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.UNAUTHORIZED.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);
} }
@ -386,15 +392,18 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false, 10, 5); null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true, 10, 5); null, DEFAULT_STATUS_LIST, 0, null, ifModifiedSince, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.NOT_MODIFIED.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince", false, 10, 5); null, DEFAULT_STATUS_LIST, 0, null, "ErrorModifiedSince",
false, 10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -414,15 +423,18 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, since, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 0, since, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, since, null, true, 10, 5); null, DEFAULT_STATUS_LIST, 0, since, null, true,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
response = this.deviceManagementService response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false, 10, 5); null, DEFAULT_STATUS_LIST, 0, "ErrorSince", null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
} }
@ -444,7 +456,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceManagementProviderService); Mockito.reset(this.deviceManagementProviderService);
} }
@ -466,7 +479,8 @@ public class DeviceManagementServiceImplTest {
Response response = this.deviceManagementService Response response = this.deviceManagementService
.getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP, .getDevices(null, TEST_DEVICE_TYPE, DEFAULT_USERNAME, null, DEFAULT_ROLE, DEFAULT_OWNERSHIP,
DEFAULT_STATUS_LIST, 1, null, null, false, 10, 5); null, DEFAULT_STATUS_LIST, 1, null, null, false,
10, 5);
Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
Mockito.reset(this.deviceAccessAuthorizationService); Mockito.reset(this.deviceAccessAuthorizationService);
} }

View File

@ -7,8 +7,9 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService; import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
@ -33,8 +34,9 @@ public class GeoLocationBasedServiceImplTest {
@Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are no devices" + @Test(description = "This method tests the behaviour of getGeoDeviceLocations when there are no devices" +
"in the given map boundaries") "in the given map boundaries")
public void testGetGeoDeviceLocations1() throws DeviceManagementException { public void testGetGeoDeviceLocations1() throws DeviceManagementException {
GeoQuery geoQuery = new GeoQuery(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt());
Mockito.doReturn(new ArrayList<GeoCluster>()).when(deviceManagementProviderService) Mockito.doReturn(new ArrayList<GeoCluster>()).when(deviceManagementProviderService)
.findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); .findGeoClusters(geoQuery);
Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6, Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6,
90.1, 6); 90.1, 6);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
@ -47,12 +49,14 @@ public class GeoLocationBasedServiceImplTest {
List<GeoCluster> geoClusters = new ArrayList<>(); List<GeoCluster> geoClusters = new ArrayList<>();
geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7), geoClusters.add(new GeoCluster(new GeoCoordinate(1.5, 80.7),
new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3, new GeoCoordinate(1.1, 79.5), new GeoCoordinate(1.9, 82.1), 3,
"tb32", "aegtew234", "test1", "android", "1234")); "tb32", null));
geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1), geoClusters.add(new GeoCluster(new GeoCoordinate(10.2, 86.1),
new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4, new GeoCoordinate(9.8, 84.7), new GeoCoordinate(11.1, 88.1), 4,
"t1gd", "swerty12s", "t2test", "android", "1234")); "t1gd", null));
GeoQuery geoQuery = new GeoQuery(Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt());
Mockito.doReturn(geoClusters).when(deviceManagementProviderService) Mockito.doReturn(geoClusters).when(deviceManagementProviderService)
.findGeoClusters(null, Mockito.any(GeoCoordinate.class), Mockito.any(GeoCoordinate.class), Mockito.anyInt()); .findGeoClusters(geoQuery);
Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6, Response response = geoLocationBasedService.getGeoDeviceLocations(null, 0.4, 15, 75.6,
90.1, 6); 90.1, 6);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),

View File

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -50,7 +50,6 @@
<Import-Package> <Import-Package>
javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}", javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.version}",
com.fasterxml.jackson.annotation;version="${jackson-annotations.version}", com.fasterxml.jackson.annotation;version="${jackson-annotations.version}",
org.wso2.carbon.analytics.datasource.commons;version="${carbon.analytics.version.range}",
io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional, io.swagger.annotations; version="${swagger.annotations.version}"; resolution:=optional,
com.google.gson com.google.gson
</Import-Package> </Import-Package>
@ -96,14 +95,6 @@
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId> <groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>jackson-annotations</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>

View File

@ -40,6 +40,7 @@ public class PaginationRequest {
private String ownerRole; private String ownerRole;
private Date since; private Date since;
private String filter; private String filter;
private String serialNumber;
private Map<String, Object> property = new HashMap<>(); private Map<String, Object> property = new HashMap<>();
private List<String> statusList = new ArrayList<>(); private List<String> statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters(); private OperationLogFilters operationLogFilters = new OperationLogFilters();
@ -153,6 +154,10 @@ public class PaginationRequest {
return this.property.get(key); return this.property.get(key);
} }
public String getSerialNumber() { return serialNumber; }
public void setSerialNumber(String serialNumber) { this.serialNumber = serialNumber; }
public Map<String, Object> getProperties() { public Map<String, Object> getProperties() {
Map<String, Object> temp = new HashMap<>(); Map<String, Object> temp = new HashMap<>();
temp.putAll(property); temp.putAll(property);

View File

@ -0,0 +1,66 @@
/*
* Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.geo.service;
import org.wso2.carbon.device.mgt.common.Device;
public class GeoCluster {
private final GeoCoordinate coordinates;
private final GeoCoordinate southWestBound;
private final GeoCoordinate northEastBound;
private final long count;
private final String geohashPrefix;
private final Device device;
public GeoCluster(GeoCoordinate coordinates, GeoCoordinate southWestBound, GeoCoordinate northEastBound,
long count, String geohashPrefix, Device device) {
this.coordinates = coordinates;
this.southWestBound = southWestBound;
this.northEastBound = northEastBound;
this.count = count;
this.geohashPrefix = geohashPrefix;
this.device = device;
}
public String getGeohashPrefix() {
return geohashPrefix;
}
public long getCount() {
return count;
}
public GeoCoordinate getCoordinates() {
return coordinates;
}
public GeoCoordinate getSouthWestBound() {
return southWestBound;
}
public GeoCoordinate getNorthEastBound() {
return northEastBound;
}
public Device getDevice() {
return device;
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.geo.service;
public class GeoCoordinate {
private final double latitude;
private final double longitude;
public GeoCoordinate(double latitude, double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}

View File

@ -0,0 +1,139 @@
/*
* Copyright (c) 2018-2021, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. 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.geo.service;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import java.util.List;
public class GeoQuery {
private final GeoCoordinate southWest;
private final GeoCoordinate northEast;
private final int geohashLength;
private List<String> deviceTypes;
private List<String> deviceIdentifiers;
private List<EnrolmentInfo.Status> statuses;
private List<String> ownerships;
private List<String> owners;
private boolean noClusters;
private long createdBefore;
private long createdAfter;
private long updatedBefore;
private long updatedAfter;
public GeoQuery(GeoCoordinate southWest, GeoCoordinate northEast, int geohashLength) {
this.southWest = southWest;
this.northEast = northEast;
this.geohashLength = geohashLength;
}
public GeoCoordinate getSouthWest() {
return southWest;
}
public GeoCoordinate getNorthEast() {
return northEast;
}
public int getGeohashLength() {
return geohashLength;
}
public List<String> getDeviceTypes() {
return deviceTypes;
}
public void setDeviceTypes(List<String> deviceTypes) {
this.deviceTypes = deviceTypes;
}
public List<String> getDeviceIdentifiers() {
return deviceIdentifiers;
}
public void setDeviceIdentifiers(List<String> deviceIdentifiers) {
this.deviceIdentifiers = deviceIdentifiers;
}
public List<EnrolmentInfo.Status> getStatuses() {
return statuses;
}
public void setStatuses(List<EnrolmentInfo.Status> statuses) {
this.statuses = statuses;
}
public List<String> getOwnerships() {
return ownerships;
}
public void setOwnerships(List<String> ownerships) {
this.ownerships = ownerships;
}
public List<String> getOwners() {
return owners;
}
public void setOwners(List<String> owners) {
this.owners = owners;
}
public boolean isNoClusters() {
return noClusters;
}
public void setNoClusters(boolean noClusters) {
this.noClusters = noClusters;
}
public long getCreatedBefore() {
return createdBefore;
}
public void setCreatedBefore(long createdBefore) {
this.createdBefore = createdBefore;
}
public long getCreatedAfter() {
return createdAfter;
}
public void setCreatedAfter(long createdAfter) {
this.createdAfter = createdAfter;
}
public long getUpdatedBefore() {
return updatedBefore;
}
public void setUpdatedBefore(long updatedBefore) {
this.updatedBefore = updatedBefore;
}
public long getUpdatedAfter() {
return updatedAfter;
}
public void setUpdatedAfter(long updatedAfter) {
this.updatedAfter = updatedAfter;
}
}

View File

@ -30,7 +30,7 @@ import java.util.List;
public class ActivityStatus { public class ActivityStatus {
public enum Status { public enum Status {
IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED IN_PROGRESS, PENDING, COMPLETED, ERROR, REPEATED, INVALID, UNAUTHORIZED, NOTNOW
} }
@ApiModelProperty( @ApiModelProperty(

View File

@ -27,6 +27,7 @@ public class Item {
private String label; private String label;
private String tooltip; private String tooltip;
private String docLink;
private String key; private String key;
private String value; private String value;
private boolean isRequired; private boolean isRequired;
@ -65,6 +66,16 @@ public class Item {
this.tooltip = tooltip; this.tooltip = tooltip;
} }
@XmlElement(name = "DocLink")
public String getDocLink() {
return docLink;
}
public void setDocLink(String docLink) {
this.docLink = docLink;
}
@XmlElement(name = "Key", required = true) @XmlElement(name = "Key", required = true)
public String getKey() { public String getKey() {
return key; return key;

View File

@ -22,7 +22,7 @@
<parent> <parent>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>device-mgt</artifactId> <artifactId>device-mgt</artifactId>
<version>4.1.16-SNAPSHOT</version> <version>5.0.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -78,8 +78,8 @@
<Private-Package>org.wso2.carbon.device.mgt.core.internal</Private-Package> <Private-Package>org.wso2.carbon.device.mgt.core.internal</Private-Package>
<Import-Package> <Import-Package>
org.apache.axis2.*;version="${axis2.osgi.version.range}", org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.osgi.framework, org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
org.osgi.service.component, org.osgi.service.*;version="${imp.package.version.osgi.service}",
org.apache.commons.logging, org.apache.commons.logging,
javax.naming, javax.naming,
javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional, javax.xml.parsers;version="${javax.xml.parsers.import.pkg.version}";resolution:=optional,
@ -90,7 +90,6 @@
org.wso2.carbon.core, org.wso2.carbon.core,
org.wso2.carbon.utils.*, org.wso2.carbon.utils.*,
org.wso2.carbon.device.mgt.common.*, org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.analytics.data.publisher.service,
org.wso2.carbon.user.api, org.wso2.carbon.user.api,
org.wso2.carbon.user.core.*, org.wso2.carbon.user.core.*,
org.wso2.carbon.registry.core.service, org.wso2.carbon.registry.core.service,
@ -104,8 +103,6 @@
org.wso2.carbon.ndatasource.core, org.wso2.carbon.ndatasource.core,
org.wso2.carbon.ntask.core.*, org.wso2.carbon.ntask.core.*,
org.wso2.carbon.ntask.common, org.wso2.carbon.ntask.common,
org.apache.catalina,
org.apache.catalina.core,
org.apache.commons.collections;version="${commons-collections.version.range}", org.apache.commons.collections;version="${commons-collections.version.range}",
org.wso2.carbon.email.sender.*, org.wso2.carbon.email.sender.*,
io.swagger.annotations.*;resolution:=optional, io.swagger.annotations.*;resolution:=optional,
@ -122,9 +119,7 @@
org.wso2.carbon.device.mgt.core.* org.wso2.carbon.device.mgt.core.*
</Export-Package> </Export-Package>
<Embed-Dependency> <Embed-Dependency>
javax.ws.rs-api,
scribe;scope=compile|runtime;inline=false, scribe;scope=compile|runtime;inline=false,
javassist;inline=false
</Embed-Dependency> </Embed-Dependency>
<DynamicImport-Package>*</DynamicImport-Package> <DynamicImport-Package>*</DynamicImport-Package>
</instructions> </instructions>
@ -166,32 +161,6 @@
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId> <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.indexing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon.identity.framework</groupId>
<artifactId>org.wso2.carbon.user.mgt</artifactId>
</exclusion>
<exclusion>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>org.wso2.carbon.logging</artifactId>

View File

@ -53,6 +53,8 @@ public final class DeviceManagementConstants {
public static final String SCOPES_FOR_TOKEN = "perm:device:operations perm:device:publish-event perm:windows:enroll"; public static final String SCOPES_FOR_TOKEN = "perm:device:operations perm:device:publish-event perm:windows:enroll";
public static final String IOT_GATEWAY_HOST = "iot.gateway.host"; public static final String IOT_GATEWAY_HOST = "iot.gateway.host";
public static final String IOT_GATEWAY_HTTPS_PORT = "iot.gateway.https.port"; public static final String IOT_GATEWAY_HTTPS_PORT = "iot.gateway.https.port";
public static final String IOT_CORE_HOST = "iot.core.host";
public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port";
public static final String APPLICATION_REGISTRATION_API_ENDPOINT = public static final String APPLICATION_REGISTRATION_API_ENDPOINT =
"/api-application-registration/register"; "/api-application-registration/register";
public static final String AUTHORIZATION_HEADER = "authorization"; public static final String AUTHORIZATION_HEADER = "authorization";

View File

@ -31,6 +31,7 @@ public class UIConfiguration {
private AppRegistration appRegistration; private AppRegistration appRegistration;
private List<String> scopes; private List<String> scopes;
private boolean isSsoEnable; private boolean isSsoEnable;
private int sessionTimeOut;
@XmlElement(name = "AppRegistration", required=true) @XmlElement(name = "AppRegistration", required=true)
public AppRegistration getAppRegistration() { public AppRegistration getAppRegistration() {
@ -59,4 +60,13 @@ public class UIConfiguration {
public void setSsoEnable(boolean ssoEnable) { public void setSsoEnable(boolean ssoEnable) {
isSsoEnable = ssoEnable; isSsoEnable = ssoEnable;
} }
@XmlElement(name = "SessionTimeOut")
public int getSessionTimeOut() {
return sessionTimeOut;
}
public void setSessionTimeOut(int sessionTimeOut) {
this.sessionTimeOut = sessionTimeOut;
}
} }

View File

@ -46,9 +46,10 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot;
import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData; import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData;
import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Date; import java.util.Date;
@ -555,14 +556,11 @@ public interface DeviceDAO {
* This method is used to retrieve the details of geoclusters formed relatively to the zoom level and map * This method is used to retrieve the details of geoclusters formed relatively to the zoom level and map
* boundaries. * boundaries.
* *
* @param deviceType Optional device type name. * @param geoQuery the query to determine the geo data.
* @param southWest the coordinates of southWest corner of the map. * @param tenantId tenant id.
* @param northEast the coordinates of northEast corner of the map.
* @param tenantId tenant id.
* @return returns a list of enrolment info objects. * @return returns a list of enrolment info objects.
*/ */
List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, List<GeoCluster> findGeoClusters(GeoQuery geoQuery, int tenantId) throws DeviceManagementDAOException;
int geohashLength,int tenantId) throws DeviceManagementDAOException;
/** /**
* This method is used to identify whether given device ids are exist or not. * This method is used to identify whether given device ids are exist or not.
@ -651,16 +649,14 @@ public interface DeviceDAO {
/** /**
* This method is used to get the details of subscribed devices. * This method is used to get the details of subscribed devices.
* *
* @param deviceIds device ids of the subscribed devices. * @param deviceIds device ids of the subscribed devices.
* @param tenantId Id of the current tenant. * @param tenantId Id of the current tenant.
* @param offsetValue offset value for get paginated request. * @param request paginated request object.
* @param limitValue limit value for get paginated request.
* @param status status of the devices.
* @return devices - subscribed device details list * @return devices - subscribed device details list
* @throws DeviceManagementDAOException if connections establishment fails. * @throws DeviceManagementDAOException if connections establishment fails.
*/ */
List<Device> getSubscribedDevices(int offsetValue, int limitValue, List<Integer> deviceIds, List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
int tenantId, List<String> status) throws DeviceManagementDAOException; throws DeviceManagementDAOException;
/** /**
* @param deviceIds device ids of the subscribed devices. * @param deviceIds device ids of the subscribed devices.

View File

@ -48,13 +48,14 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.DevicePropertyInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData; import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot; import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshot;
import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData; import org.wso2.carbon.device.mgt.common.device.details.DeviceMonitoringData;
import org.wso2.carbon.device.mgt.common.geo.service.GeoQuery;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType; import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -64,6 +65,7 @@ import java.sql.Statement;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -1850,62 +1852,161 @@ public abstract class AbstractDeviceDAOImpl implements DeviceDAO {
return tenants; return tenants;
} }
public List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, public List<GeoCluster> findGeoClusters(GeoQuery geoQuery, int tenantId) throws DeviceManagementDAOException {
int geohashLength, int tenantId) throws DeviceManagementDAOException {
Connection conn; Connection conn;
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
List<GeoCluster> geoClusters = new ArrayList<>(); List<GeoCluster> geoClusters = new ArrayList<>();
try { try {
conn = this.getConnection(); conn = this.getConnection();
String sql = "SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE,AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE," + String sql = "SELECT AVG(DEVICE_LOCATION.LATITUDE) AS LATITUDE, " +
" MIN(DEVICE_LOCATION.LATITUDE) AS MIN_LATITUDE, MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE," + "AVG(DEVICE_LOCATION.LONGITUDE) AS LONGITUDE, " +
" MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE," + "MIN(DEVICE_LOCATION.LATITUDE) AS MIN_LATITUDE, " +
" MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE," + "MAX(DEVICE_LOCATION.LATITUDE) AS MAX_LATITUDE, " +
" SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,?) AS GEOHASH_PREFIX, COUNT(*) AS COUNT," + "MIN(DEVICE_LOCATION.LONGITUDE) AS MIN_LONGITUDE, " +
" MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION," + "MAX(DEVICE_LOCATION.LONGITUDE) AS MAX_LONGITUDE, " +
" MIN(DEVICE.NAME) AS NAME," + "SUBSTRING(DEVICE_LOCATION.GEO_HASH,1,?) AS GEOHASH_PREFIX, " +
" MIN(DEVICE_TYPE.NAME) AS TYPE, " + "COUNT(DEVICE_LOCATION.ID) AS COUNT, " +
" MIN(DEVICE.LAST_UPDATED_TIMESTAMP) AS LAST_UPDATED_TIMESTAMP " + "MIN(DEVICE.ID) AS DEVICE_ID, " +
"FROM DM_DEVICE_LOCATION AS DEVICE_LOCATION,DM_DEVICE AS DEVICE, DM_DEVICE_TYPE AS DEVICE_TYPE " + "MIN(DEVICE.NAME) AS DEVICE_NAME, " +
"WHERE DEVICE_LOCATION.LATITUDE BETWEEN ? AND ? AND " + "MIN(DEVICE.DESCRIPTION) AS DESCRIPTION, " +
"DEVICE_LOCATION.LONGITUDE BETWEEN ? AND ? AND " + "MIN(DEVICE_TYPE.NAME) AS DEVICE_TYPE, " +
"DEVICE.TENANT_ID=? AND " + "MIN(DEVICE.DEVICE_IDENTIFICATION) AS DEVICE_IDENTIFICATION, " +
"DEVICE.ID=DEVICE_LOCATION.DEVICE_ID AND DEVICE.DEVICE_TYPE_ID=DEVICE_TYPE.ID"; "MIN(ENROLMENT.ID) AS ENROLMENT_ID, " +
if (deviceType != null && !deviceType.isEmpty()) { "MIN(ENROLMENT.OWNER) AS OWNER, " +
sql += " AND DEVICE_TYPE.NAME=?"; "MIN(ENROLMENT.OWNERSHIP) AS OWNERSHIP, " +
"MIN(ENROLMENT.IS_TRANSFERRED) AS IS_TRANSFERRED, " +
"MIN(ENROLMENT.DATE_OF_ENROLMENT) AS DATE_OF_ENROLMENT, " +
"MIN(ENROLMENT.DATE_OF_LAST_UPDATE) AS DATE_OF_LAST_UPDATE, " +
"MIN(ENROLMENT.STATUS) AS STATUS " +
"FROM DM_DEVICE_LOCATION AS DEVICE_LOCATION, DM_DEVICE AS DEVICE, " +
"DM_DEVICE_TYPE AS DEVICE_TYPE, DM_ENROLMENT AS ENROLMENT " +
"WHERE DEVICE_LOCATION.LATITUDE BETWEEN ? AND ? " +
"AND DEVICE_LOCATION.LONGITUDE BETWEEN ? AND ? ";
if (geoQuery.getDeviceTypes() != null && !geoQuery.getDeviceTypes().isEmpty()) {
sql += "AND DEVICE_TYPE.NAME IN (";
sql += String.join(", ",
Collections.nCopies(geoQuery.getDeviceTypes().size(), "?"));
sql += ") ";
} }
sql += " GROUP BY GEOHASH_PREFIX"; if (geoQuery.getDeviceIdentifiers() != null && !geoQuery.getDeviceIdentifiers().isEmpty()) {
sql += "AND DEVICE.DEVICE_IDENTIFICATION IN (";
sql += String.join(", ",
Collections.nCopies(geoQuery.getDeviceIdentifiers().size(), "?"));
sql += ") ";
}
if (geoQuery.getOwners() != null && !geoQuery.getOwners().isEmpty()) {
sql += "AND ENROLMENT.OWNER IN (";
sql += String.join(", ",
Collections.nCopies(geoQuery.getOwners().size(), "?"));
sql += ") ";
}
if (geoQuery.getOwnerships() != null && !geoQuery.getOwnerships().isEmpty()) {
sql += "AND ENROLMENT.OWNERSHIP IN (";
sql += String.join(", ",
Collections.nCopies(geoQuery.getOwnerships().size(), "?"));
sql += ") ";
}
if (geoQuery.getStatuses() != null && !geoQuery.getStatuses().isEmpty()) {
sql += "AND ENROLMENT.STATUS IN (";
sql += String.join(", ",
Collections.nCopies(geoQuery.getStatuses().size(), "?"));
sql += ") ";
} else {
sql += "AND ENROLMENT.STATUS != 'REMOVED' ";
}
if (geoQuery.getCreatedBefore() != 0 || geoQuery.getCreatedAfter() != 0) {
sql += "AND ENROLMENT.DATE_OF_ENROLMENT BETWEEN ? AND ? ";
}
if (geoQuery.getUpdatedBefore() != 0 || geoQuery.getUpdatedAfter() != 0) {
sql += "AND ENROLMENT.DATE_OF_LAST_UPDATE BETWEEN ? AND ? ";
}
sql += "AND DEVICE.ID = DEVICE_LOCATION.DEVICE_ID AND DEVICE.DEVICE_TYPE_ID = DEVICE_TYPE.ID " +
"AND DEVICE.ID = ENROLMENT.DEVICE_ID " +
"AND DEVICE.TENANT_ID = ? AND DEVICE.TENANT_ID = ENROLMENT.TENANT_ID GROUP BY GEOHASH_PREFIX";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setInt(1, geohashLength);
stmt.setDouble(2, southWest.getLatitude()); int index = 1;
stmt.setDouble(3, northEast.getLatitude()); stmt.setInt(index++, geoQuery.getGeohashLength());
stmt.setDouble(4, southWest.getLongitude()); stmt.setDouble(index++, geoQuery.getSouthWest().getLatitude());
stmt.setDouble(5, northEast.getLongitude()); stmt.setDouble(index++, geoQuery.getNorthEast().getLatitude());
stmt.setDouble(6, tenantId); stmt.setDouble(index++, geoQuery.getSouthWest().getLongitude());
if (deviceType != null && !deviceType.isEmpty()) { stmt.setDouble(index++, geoQuery.getNorthEast().getLongitude());
stmt.setString(7, deviceType); if (geoQuery.getDeviceTypes() != null) {
for (String s: geoQuery.getDeviceTypes()) {
stmt.setString(index++, s);
}
} }
if (geoQuery.getDeviceIdentifiers() != null) {
for (String s: geoQuery.getDeviceIdentifiers()) {
stmt.setString(index++, s);
}
}
if (geoQuery.getOwners() != null) {
for (String s: geoQuery.getOwners()) {
stmt.setString(index++, s);
}
}
if (geoQuery.getOwnerships() != null) {
for (String s: geoQuery.getOwnerships()) {
stmt.setString(index++, s);
}
}
if (geoQuery.getStatuses() != null) {
for (Status s: geoQuery.getStatuses()) {
stmt.setString(index++, s.toString());
}
}
if (geoQuery.getCreatedBefore() != 0 || geoQuery.getCreatedAfter() != 0) {
stmt.setTimestamp(index++, new Timestamp(geoQuery.getCreatedAfter()));
if (geoQuery.getCreatedBefore() == 0) {
stmt.setTimestamp(index++, new Timestamp(System.currentTimeMillis()));
} else {
stmt.setTimestamp(index++, new Timestamp(geoQuery.getCreatedBefore()));
}
}
if (geoQuery.getUpdatedBefore() != 0 || geoQuery.getUpdatedAfter() != 0) {
stmt.setTimestamp(index++, new Timestamp(geoQuery.getUpdatedAfter()));
if (geoQuery.getUpdatedBefore() == 0) {
stmt.setTimestamp(index++, new Timestamp(System.currentTimeMillis()));
} else {
stmt.setTimestamp(index++, new Timestamp(geoQuery.getUpdatedBefore()));
}
}
stmt.setInt(index, tenantId);
rs = stmt.executeQuery(); rs = stmt.executeQuery();
double latitude;
double longitude;
double minLatitude;
double maxLatitude;
double minLongitude;
double maxLongitude;
long count;
String geohashPrefix;
Device device;
while (rs.next()) { while (rs.next()) {
double latitude = rs.getDouble("LATITUDE"); latitude = rs.getDouble("LATITUDE");
double longitude = rs.getDouble("LONGITUDE"); longitude = rs.getDouble("LONGITUDE");
double min_latitude = rs.getDouble("MIN_LATITUDE"); minLatitude = rs.getDouble("MIN_LATITUDE");
double max_latitude = rs.getDouble("MAX_LATITUDE"); maxLatitude = rs.getDouble("MAX_LATITUDE");
double min_longitude = rs.getDouble("MIN_LONGITUDE"); minLongitude = rs.getDouble("MIN_LONGITUDE");
double max_longitude = rs.getDouble("MAX_LONGITUDE"); maxLongitude = rs.getDouble("MAX_LONGITUDE");
String device_identification = rs.getString("DEVICE_IDENTIFICATION"); count = rs.getLong("COUNT");
String device_name = rs.getString("NAME"); geohashPrefix = rs.getString("GEOHASH_PREFIX");
String device_type = rs.getString("TYPE"); if (count == 1) {
String last_seen = rs.getString("LAST_UPDATED_TIMESTAMP"); device = DeviceManagementDAOUtil.loadDevice(rs);
long count = rs.getLong("COUNT"); } else {
String geohashPrefix = rs.getString("GEOHASH_PREFIX"); device = null;
}
geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude), geoClusters.add(new GeoCluster(new GeoCoordinate(latitude, longitude),
new GeoCoordinate(min_latitude, min_longitude), new GeoCoordinate(max_latitude, max_longitude), new GeoCoordinate(minLatitude, minLongitude), new GeoCoordinate(maxLatitude, maxLongitude),
count, geohashPrefix, device_identification, device_name, device_type, last_seen)); count, geohashPrefix, device));
} }
} catch (SQLException e) { } catch (SQLException e) {
throw new DeviceManagementDAOException("Error occurred while retrieving information of " + throw new DeviceManagementDAOException("Error occurred while retrieving information of " +
"Geo Clusters", e); "Geo Clusters", e);
} finally { } finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs); DeviceManagementDAOUtil.cleanupResources(stmt, rs);

View File

@ -67,6 +67,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false; boolean isStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try { try {
Connection conn = getConnection(); Connection conn = getConnection();
@ -87,10 +90,19 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " + "d.DESCRIPTION, " +
"d.NAME, " + "d.NAME, " +
"d.DEVICE_IDENTIFICATION, " + "d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " + "t.NAME AS DEVICE_TYPE ";
"FROM DM_DEVICE d, DM_DEVICE_TYPE t ";
sql = sql + " WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp //Add query for last updated timestamp
if (since != null) { if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +140,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1; int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -877,11 +892,15 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue, public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
List<Integer> deviceIds, int tenantId, List<String> status)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try { try {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) { if (deviceIds.isEmpty()) {
@ -891,6 +910,10 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1; int index = 1;
boolean isStatusProvided = false; boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",", StringJoiner joiner = new StringJoiner(",",
"SELECT " "SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, " + "DM_DEVICE.ID AS DEVICE_ID, "
@ -918,6 +941,18 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add); deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString(); String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status); query += buildStatusQuery(status);
isStatusProvided = true; isStatusProvided = true;
@ -930,8 +965,16 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
for (Integer deviceId : deviceIds) { for (Integer deviceId : deviceIds) {
ps.setObject(index++, deviceId); ps.setObject(index++, deviceId);
} }
ps.setInt(index++, tenantId); ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) { if (isStatusProvided) {
for (String deviceStatus : status) { for (String deviceStatus : status) {
ps.setString(index++, deviceStatus); ps.setString(index++, deviceStatus);

View File

@ -68,6 +68,8 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false; boolean isStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try { try {
conn = getConnection(); conn = getConnection();
@ -88,9 +90,19 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " + "d.DESCRIPTION, " +
"d.NAME, " + "d.NAME, " +
"d.DEVICE_IDENTIFICATION, " + "d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " + "t.NAME AS DEVICE_TYPE ";
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?"; if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp //Add query for last updated timestamp
if (since != null) { if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +140,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1; int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -847,11 +862,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue, public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
List<Integer> deviceIds, int tenantId, List<String> status)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try { try {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) { if (deviceIds.isEmpty()) {
@ -861,6 +880,9 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1; int index = 1;
boolean isStatusProvided = false; boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",", StringJoiner joiner = new StringJoiner(",",
"SELECT " "SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, " + "DM_DEVICE.ID AS DEVICE_ID, "
@ -888,6 +910,18 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add); deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString(); String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status); query += buildStatusQuery(status);
isStatusProvided = true; isStatusProvided = true;
@ -902,6 +936,15 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
ps.setInt(index++, tenantId); ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) { if (isStatusProvided) {
for (String deviceStatus : status) { for (String deviceStatus : status) {
ps.setString(index++, deviceStatus); ps.setString(index++, deviceStatus);

View File

@ -67,6 +67,8 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false; boolean isStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try { try {
conn = getConnection(); conn = getConnection();
@ -87,11 +89,19 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " + "d.DESCRIPTION, " +
"d.NAME, " + "d.NAME, " +
"d.DEVICE_IDENTIFICATION, " + "d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " + "t.NAME AS DEVICE_TYPE ";
"FROM DM_DEVICE d, " +
"DM_DEVICE_TYPE t " + if (serial != null) {
"WHERE DEVICE_TYPE_ID = t.ID " + sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"AND d.TENANT_ID = ?"; "WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add the query for device-type //Add the query for device-type
if (deviceType != null && !deviceType.isEmpty()) { if (deviceType != null && !deviceType.isEmpty()) {
sql = sql + " AND t.NAME = ?"; sql = sql + " AND t.NAME = ?";
@ -124,6 +134,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1; int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isDeviceTypeProvided) { if (isDeviceTypeProvided) {
stmt.setString(paramIdx++, deviceType); stmt.setString(paramIdx++, deviceType);
@ -827,11 +840,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue, public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
List<Integer> deviceIds, int tenantId, List<String> status)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try { try {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) { if (deviceIds.isEmpty()) {
@ -841,6 +858,9 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1; int index = 1;
boolean isStatusProvided = false; boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",", StringJoiner joiner = new StringJoiner(",",
"SELECT " "SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, " + "DM_DEVICE.ID AS DEVICE_ID, "
@ -868,6 +888,18 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add); deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString(); String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status); query += buildStatusQuery(status);
isStatusProvided = true; isStatusProvided = true;
@ -882,6 +914,15 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
ps.setInt(index++, tenantId); ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) { if (isStatusProvided) {
for (String deviceStatus : status) { for (String deviceStatus : status) {
ps.setString(index++, deviceStatus); ps.setString(index++, deviceStatus);

View File

@ -18,7 +18,6 @@
package org.wso2.carbon.device.mgt.core.dao.impl.device; package org.wso2.carbon.device.mgt.core.dao.impl.device;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Count; import org.wso2.carbon.device.mgt.common.Count;
@ -29,8 +28,8 @@ import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl; import org.wso2.carbon.device.mgt.core.dao.impl.AbstractDeviceDAOImpl;
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.core.geo.GeoCluster; import org.wso2.carbon.device.mgt.common.geo.service.GeoCluster;
import org.wso2.carbon.device.mgt.core.geo.geoHash.GeoCoordinate; import org.wso2.carbon.device.mgt.common.geo.service.GeoCoordinate;
import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import org.wso2.carbon.device.mgt.core.report.mgt.Constants;
import java.sql.Connection; import java.sql.Connection;
@ -69,6 +68,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
boolean isStatusProvided = false; boolean isStatusProvided = false;
Date since = request.getSince(); Date since = request.getSince();
boolean isSinceProvided = false; boolean isSinceProvided = false;
String serial = request.getSerialNumber();
boolean isSerialProvided = false;
try { try {
conn = getConnection(); conn = getConnection();
@ -89,8 +90,19 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
"d.DESCRIPTION, " + "d.DESCRIPTION, " +
"d.NAME, " + "d.NAME, " +
"d.DEVICE_IDENTIFICATION, " + "d.DEVICE_IDENTIFICATION, " +
"t.NAME AS DEVICE_TYPE " + "t.NAME AS DEVICE_TYPE ";
"FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ?";
if (serial != null) {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t, DM_DEVICE_INFO i " +
"WHERE DEVICE_TYPE_ID = t.ID " +
"AND d.ID= i.DEVICE_ID " +
"AND i.KEY_FIELD = 'serial' " +
"AND i.VALUE_FIELD = ? " +
"AND d.TENANT_ID = ? ";
isSerialProvided = true;
} else {
sql = sql + "FROM DM_DEVICE d, DM_DEVICE_TYPE t WHERE DEVICE_TYPE_ID = t.ID AND d.TENANT_ID = ? ";
}
//Add query for last updated timestamp //Add query for last updated timestamp
if (since != null) { if (since != null) {
sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?"; sql = sql + " AND d.LAST_UPDATED_TIMESTAMP > ?";
@ -128,6 +140,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
try (PreparedStatement stmt = conn.prepareStatement(sql)) { try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIdx = 1; int paramIdx = 1;
if (isSerialProvided) {
stmt.setString(paramIdx++, serial);
}
stmt.setInt(paramIdx++, tenantId); stmt.setInt(paramIdx++, tenantId);
if (isSinceProvided) { if (isSinceProvided) {
stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime())); stmt.setTimestamp(paramIdx++, new Timestamp(since.getTime()));
@ -693,11 +708,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
@Override @Override
public List<Device> getSubscribedDevices(int offsetValue, int limitValue, public List<Device> getSubscribedDevices(PaginationRequest request, List<Integer> deviceIds, int tenantId)
List<Integer> deviceIds, int tenantId, List<String> status)
throws DeviceManagementDAOException { throws DeviceManagementDAOException {
Connection conn; Connection conn;
int limitValue = request.getRowCount();
int offsetValue = request.getStartIndex();
List<String> status = request.getStatusList();
String name = request.getDeviceName();
String user = request.getOwner();
String ownership = request.getOwnership();
try { try {
List<Device> devices = new ArrayList<>(); List<Device> devices = new ArrayList<>();
if (deviceIds.isEmpty()) { if (deviceIds.isEmpty()) {
@ -707,6 +726,9 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
int index = 1; int index = 1;
boolean isStatusProvided = false; boolean isStatusProvided = false;
boolean isDeviceNameProvided = false;
boolean isOwnerProvided = false;
boolean isOwnershipProvided = false;
StringJoiner joiner = new StringJoiner(",", StringJoiner joiner = new StringJoiner(",",
"SELECT " "SELECT "
+ "DM_DEVICE.ID AS DEVICE_ID, " + "DM_DEVICE.ID AS DEVICE_ID, "
@ -734,6 +756,18 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
deviceIds.stream().map(ignored -> "?").forEach(joiner::add); deviceIds.stream().map(ignored -> "?").forEach(joiner::add);
String query = joiner.toString(); String query = joiner.toString();
if (name != null && !name.isEmpty()) {
query += " AND DM_DEVICE.NAME LIKE ?";
isDeviceNameProvided = true;
}
if (ownership != null && !ownership.isEmpty()) {
query += " AND e.OWNERSHIP = ?";
isOwnershipProvided = true;
}
if (user != null && !user.isEmpty()) {
query += " AND e.OWNER = ?";
isOwnerProvided = true;
}
if (status != null && !status.isEmpty()) { if (status != null && !status.isEmpty()) {
query += buildStatusQuery(status); query += buildStatusQuery(status);
isStatusProvided = true; isStatusProvided = true;
@ -748,6 +782,15 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
ps.setInt(index++, tenantId); ps.setInt(index++, tenantId);
if (isDeviceNameProvided) {
ps.setString(index++, name + "%");
}
if (isOwnershipProvided) {
ps.setString(index++, ownership);
}
if (isOwnerProvided) {
ps.setString(index++, user);
}
if (isStatusProvided) { if (isStatusProvided) {
for (String deviceStatus : status) { for (String deviceStatus : status) {
ps.setString(index++, deviceStatus); ps.setString(index++, deviceStatus);
@ -1089,6 +1132,8 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
} }
//TODO: Override for MSSQL
/*
@Override @Override
public List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast, public List<GeoCluster> findGeoClusters(String deviceType, GeoCoordinate southWest, GeoCoordinate northEast,
int geohashLength, int tenantId) throws DeviceManagementDAOException { int geohashLength, int tenantId) throws DeviceManagementDAOException {
@ -1163,4 +1208,5 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
} }
return geoClusters; return geoClusters;
} }
*/
} }

View File

@ -22,22 +22,17 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.common.Device; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceDetailsWrapper; import org.wso2.carbon.device.mgt.common.device.details.DeviceDetailsWrapper;
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.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.EventPublishingException; import org.wso2.carbon.device.mgt.common.exceptions.EventPublishingException;
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException; import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
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.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.config.tenant.PlatformConfigurationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO; import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
@ -46,18 +41,14 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManag
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsDAO;
import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException; import org.wso2.carbon.device.mgt.core.device.details.mgt.dao.DeviceDetailsMgtDAOException;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder; import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.report.mgt.Constants; import org.wso2.carbon.device.mgt.core.report.mgt.Constants;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService; import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil; import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil; import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.user.api.UserRealm;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -178,9 +169,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceInfo.getAvailableRAMMemory(), deviceInfo.getAvailableRAMMemory(),
deviceInfo.isPluggedIn() deviceInfo.isPluggedIn()
}; };
DeviceManagerUtil.getEventPublisherService().publishEvent( //todo:amalka
DEVICE_INFO_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload // DeviceManagerUtil.getEventPublisherService().publishEvent(
); // DEVICE_INFO_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
// );
} }
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e); throw new DeviceDetailsMgtException("Transactional error occurred while adding the device information.", e);
@ -193,8 +185,9 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " + throw new DeviceDetailsMgtException("Error occurred while updating the last update timestamp of the " +
"device", e); "device", e);
} catch (DataPublisherConfigurationException e) { //todo:amalka
throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); // } catch (DataPublisherConfigurationException e) {
// throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }
@ -389,9 +382,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceLocation.getBearing(), deviceLocation.getBearing(),
deviceLocation.getDistance() deviceLocation.getDistance()
}; };
DeviceManagerUtil.getEventPublisherService().publishEvent( //todo:amalka
LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload // DeviceManagerUtil.getEventPublisherService().publishEvent(
); // LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
// );
} }
DeviceManagementDAOFactory.commitTransaction(); DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) { } catch (TransactionManagementException e) {
@ -403,9 +397,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
DeviceManagementDAOFactory.rollbackTransaction(); DeviceManagementDAOFactory.rollbackTransaction();
throw new DeviceDetailsMgtException("Error occurred while getting the device information.", e); throw new DeviceDetailsMgtException("Error occurred while getting the device information.", e);
} catch (DataPublisherConfigurationException e) { //todo:amalka
DeviceManagementDAOFactory.rollbackTransaction(); // } catch (DataPublisherConfigurationException e) {
throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e); // DeviceManagementDAOFactory.rollbackTransaction();
// throw new DeviceDetailsMgtException("Error occurred while publishing the device location information.", e);
} finally { } finally {
DeviceManagementDAOFactory.closeConnection(); DeviceManagementDAOFactory.closeConnection();
} }

View File

@ -22,6 +22,10 @@ public class CommandOperation extends Operation {
private boolean enabled; private boolean enabled;
public CommandOperation() {
setControl(Control.NO_REPEAT);
}
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return enabled;
} }
@ -34,8 +38,4 @@ public class CommandOperation extends Operation {
return Type.COMMAND; return Type.COMMAND;
} }
public Control getControl(){
return Control.NO_REPEAT;
}
} }

View File

@ -23,10 +23,11 @@ import java.util.List;
public class ConfigOperation extends Operation { public class ConfigOperation extends Operation {
private List<Property> properties; private final List<Property> properties;
public ConfigOperation() { public ConfigOperation() {
properties = new ArrayList<Property>(); properties = new ArrayList<>();
setControl(Control.REPEAT);
} }
public List<Property> getConfigProperties() { public List<Property> getConfigProperties() {
@ -37,6 +38,10 @@ public class ConfigOperation extends Operation {
properties.add(new Property(name, value, type)); properties.add(new Property(name, value, type));
} }
public Type getType() {
return Type.CONFIG;
}
public static class Property { public static class Property {
private String name; private String name;
private Object value; private Object value;
@ -73,13 +78,4 @@ public class ConfigOperation extends Operation {
} }
} }
public Type getType() {
return Type.CONFIG;
}
public Control getControl(){
return Control.REPEAT;
}
} }

View File

@ -19,7 +19,13 @@ package org.wso2.carbon.device.mgt.core.dto.operation.mgt;
import java.util.List; import java.util.List;
public class PolicyOperation extends Operation{ public class PolicyOperation extends Operation {
private List<ProfileOperation> profileOperations;
public PolicyOperation() {
setControl(Control.REPEAT);
}
public List<ProfileOperation> getProfileOperations() { public List<ProfileOperation> getProfileOperations() {
return profileOperations; return profileOperations;
@ -29,10 +35,4 @@ public class PolicyOperation extends Operation{
this.profileOperations = profileOperations; this.profileOperations = profileOperations;
} }
private List<ProfileOperation> profileOperations;
public Control getControl(){
return Control.REPEAT;
}
} }

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