mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Merging with master
This commit is contained in:
commit
f3bca0f88c
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Annotations</name>
|
||||
<description>WSO2 Carbon - API Management Custom Annotation Module</description>
|
||||
|
||||
@ -21,12 +21,12 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension.api</artifactId>
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 Carbon - API Application Management API</name>
|
||||
|
||||
@ -42,6 +42,7 @@ public class APIUtil {
|
||||
|
||||
private static Log log = LogFactory.getLog(APIUtil.class);
|
||||
private static final String DEFAULT_CDMF_API_TAG = "device_management";
|
||||
private static final String DEFAULT_AGENT_API_TAG = "device_agent";
|
||||
private static final String DEFAULT_CERT_API_TAG = "scep_management";
|
||||
public static final String PERMISSION_PROPERTY_NAME = "name";
|
||||
|
||||
@ -106,6 +107,7 @@ public class APIUtil {
|
||||
List<String> allowedApisTags = getDeviceManagementProviderService().getAvailableDeviceTypes();
|
||||
allowedApisTags.add(DEFAULT_CDMF_API_TAG);
|
||||
allowedApisTags.add(DEFAULT_CERT_API_TAG);
|
||||
allowedApisTags.add(DEFAULT_AGENT_API_TAG);
|
||||
return allowedApisTags;
|
||||
}
|
||||
|
||||
|
||||
@ -22,12 +22,12 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Application Management</name>
|
||||
|
||||
@ -84,109 +84,118 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
|
||||
String keyType, String username,
|
||||
boolean isAllowedAllDomains, String validityTime)
|
||||
throws APIManagerException {
|
||||
StoreClient storeClient = APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
|
||||
.getStoreClient();
|
||||
StoreClient storeClient =
|
||||
APIApplicationManagerExtensionDataHolder.getInstance().getIntegrationClientService()
|
||||
.getStoreClient();
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
|
||||
.getTenantDomain();
|
||||
try {
|
||||
ApplicationList applicationList = storeClient.getApplications()
|
||||
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
|
||||
Application application;
|
||||
if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) {
|
||||
//create application;
|
||||
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) {
|
||||
throw new APIManagerException(
|
||||
"Api application creation failed for " + applicationName + " to the user " + username);
|
||||
}
|
||||
|
||||
ApplicationList applicationList = storeClient.getApplications()
|
||||
.applicationsGet("", applicationName, 1, 0, CONTENT_TYPE, null);
|
||||
Application application;
|
||||
if (applicationList == null || applicationList.getList() == null || applicationList.getList().size() == 0) {
|
||||
//create application;
|
||||
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) {
|
||||
throw new APIManagerException (
|
||||
"Api application creation failed for " + applicationName + " to the user " + username);
|
||||
}
|
||||
SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet
|
||||
(null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null);
|
||||
List<Subscription> needToSubscribe = new ArrayList<>();
|
||||
// subscribe to apis.
|
||||
if (tags != null && tags.length > 0) {
|
||||
for (String tag : tags) {
|
||||
APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag
|
||||
, CONTENT_TYPE, null);
|
||||
if (apiList.getList() == null || apiList.getList().size() == 0) {
|
||||
apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0
|
||||
, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, "tag:" + tag, CONTENT_TYPE, null);
|
||||
}
|
||||
|
||||
SubscriptionList subscriptionList = storeClient.getSubscriptions().subscriptionsGet
|
||||
(null, application.getApplicationId(), "", 0, 100, CONTENT_TYPE, null);
|
||||
List<Subscription> needToSubscribe = new ArrayList<>();
|
||||
// subscribe to apis.
|
||||
if (tags != null && tags.length > 0) {
|
||||
for (String tag: tags) {
|
||||
APIList apiList = storeClient.getApis().apisGet(MAX_API_PER_TAG, 0, tenantDomain, "tag:" + tag
|
||||
, CONTENT_TYPE, null);
|
||||
if (apiList.getList() == null || apiList.getList().size() == 0) {
|
||||
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) {
|
||||
for (APIInfo apiInfo : apiList.getList()) {
|
||||
String id = apiInfo.getProvider().replace("@", "-AT-")
|
||||
+ "-" + apiInfo.getName()+ "-" + apiInfo.getVersion();
|
||||
boolean subscriptionExist = false;
|
||||
if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) {
|
||||
for (Subscription subs : subscriptionList.getList()) {
|
||||
if (subs.getApiIdentifier().equals(id)) {
|
||||
subscriptionExist = true;
|
||||
break;
|
||||
if (apiList.getList() != null && apiList.getList().size() > 0) {
|
||||
for (APIInfo apiInfo : apiList.getList()) {
|
||||
String id = apiInfo.getProvider().replace("@", "-AT-")
|
||||
+ "-" + apiInfo.getName() + "-" + apiInfo.getVersion();
|
||||
boolean subscriptionExist = false;
|
||||
if (subscriptionList.getList() != null && subscriptionList.getList().size() > 0) {
|
||||
for (Subscription subs : subscriptionList.getList()) {
|
||||
if (subs.getApiIdentifier().equals(id)) {
|
||||
subscriptionExist = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!subscriptionExist) {
|
||||
Subscription subscription = new Subscription();
|
||||
//fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0
|
||||
if (!subscriptionExist) {
|
||||
Subscription subscription = new Subscription();
|
||||
//fix for APIMANAGER-5566 admin-AT-tenant1.com-Tenant1API1-1.0.0
|
||||
|
||||
subscription.setApiIdentifier(id);
|
||||
subscription.setApplicationId(application.getApplicationId());
|
||||
subscription.tier(ApiApplicationConstants.DEFAULT_TIER);
|
||||
if (!needToSubscribe.contains(subscription)){
|
||||
needToSubscribe.add(subscription);
|
||||
subscription.setApiIdentifier(id);
|
||||
subscription.setApplicationId(application.getApplicationId());
|
||||
subscription.tier(ApiApplicationConstants.DEFAULT_TIER);
|
||||
if (!needToSubscribe.contains(subscription)) {
|
||||
needToSubscribe.add(subscription);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!needToSubscribe.isEmpty()) {
|
||||
storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE);
|
||||
}
|
||||
//end of subscription
|
||||
if (!needToSubscribe.isEmpty()) {
|
||||
storeClient.getSubscriptionMultitpleApi().subscriptionsMultiplePost(needToSubscribe, CONTENT_TYPE);
|
||||
}
|
||||
//end of subscription
|
||||
|
||||
List<ApplicationKey> applicationKeys = application.getKeys();
|
||||
if (applicationKeys != null) {
|
||||
for (ApplicationKey applicationKey : applicationKeys) {
|
||||
if (keyType.equals(applicationKey.getKeyType().toString())) {
|
||||
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
|
||||
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
|
||||
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
|
||||
return apiApplicationKey;
|
||||
List<ApplicationKey> applicationKeys = application.getKeys();
|
||||
if (applicationKeys != null) {
|
||||
for (ApplicationKey applicationKey : applicationKeys) {
|
||||
if (keyType.equals(applicationKey.getKeyType().toString())) {
|
||||
if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
|
||||
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
|
||||
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
|
||||
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
|
||||
return apiApplicationKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest();
|
||||
List<String> allowedDomains = new ArrayList<>();
|
||||
if (isAllowedAllDomains) {
|
||||
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
|
||||
} else {
|
||||
allowedDomains.add(APIManagerUtil.getTenantDomain());
|
||||
}
|
||||
applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains);
|
||||
applicationKeyGenerateRequest.setCallbackUrl("");
|
||||
applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION);
|
||||
applicationKeyGenerateRequest.setValidityTime(validityTime);
|
||||
ApplicationKeyGenerateRequest applicationKeyGenerateRequest = new ApplicationKeyGenerateRequest();
|
||||
List<String> allowedDomains = new ArrayList<>();
|
||||
if (isAllowedAllDomains) {
|
||||
allowedDomains.add(ApiApplicationConstants.ALLOWED_DOMAINS);
|
||||
} else {
|
||||
allowedDomains.add(APIManagerUtil.getTenantDomain());
|
||||
}
|
||||
applicationKeyGenerateRequest.setAccessAllowDomains(allowedDomains);
|
||||
applicationKeyGenerateRequest.setCallbackUrl("");
|
||||
applicationKeyGenerateRequest.setKeyType(ApplicationKeyGenerateRequest.KeyTypeEnum.PRODUCTION);
|
||||
applicationKeyGenerateRequest.setValidityTime(validityTime);
|
||||
|
||||
ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost(
|
||||
application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null);
|
||||
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
|
||||
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
|
||||
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
|
||||
return apiApplicationKey;
|
||||
ApplicationKey applicationKey = storeClient.getIndividualApplication().applicationsGenerateKeysPost(
|
||||
application.getApplicationId(), applicationKeyGenerateRequest, CONTENT_TYPE, null, null);
|
||||
if (applicationKey.getConsumerKey() != null && !applicationKey.getConsumerKey().isEmpty()) {
|
||||
ApiApplicationKey apiApplicationKey = new ApiApplicationKey();
|
||||
apiApplicationKey.setConsumerKey(applicationKey.getConsumerKey());
|
||||
apiApplicationKey.setConsumerSecret(applicationKey.getConsumerSecret());
|
||||
return apiApplicationKey;
|
||||
}
|
||||
throw new APIManagerException("Failed to generate keys for tenant: " + tenantDomain);
|
||||
} catch (FeignException e) {
|
||||
throw new APIManagerException("Failed to create api application for tenant: " + tenantDomain, e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.handlers</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Security Handler Component</name>
|
||||
<description>WSO2 Carbon - API Management Security Handler Module</description>
|
||||
|
||||
@ -44,6 +44,8 @@ import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Contains util methods for synapse gateway authentication handler
|
||||
@ -62,21 +64,47 @@ public class Utils {
|
||||
public static IOTServerConfiguration initConfig() {
|
||||
try {
|
||||
|
||||
String IOTServerAPIConfigurationPath =
|
||||
CarbonUtils.getCarbonConfigDirPath() + File.separator + IOT_APIS_CONFIG_FILE;
|
||||
String IOTServerAPIConfigurationPath = CarbonUtils.getCarbonConfigDirPath() + File.separator
|
||||
+ IOT_APIS_CONFIG_FILE;
|
||||
File file = new File(IOTServerAPIConfigurationPath);
|
||||
Document doc = Utils.convertToDocument(file);
|
||||
|
||||
JAXBContext fileContext = JAXBContext.newInstance(IOTServerConfiguration.class);
|
||||
Unmarshaller unmarshaller = fileContext.createUnmarshaller();
|
||||
return (IOTServerConfiguration) unmarshaller.unmarshal(doc);
|
||||
|
||||
IOTServerConfiguration iotServerConfiguration = (IOTServerConfiguration) unmarshaller.unmarshal(
|
||||
doc);
|
||||
iotServerConfiguration.setHostname(replaceProperties(iotServerConfiguration.getHostname()));
|
||||
iotServerConfiguration.setVerificationEndpoint(
|
||||
replaceProperties(iotServerConfiguration.getVerificationEndpoint()));
|
||||
iotServerConfiguration.setDynamicClientRegistrationEndpoint(
|
||||
replaceProperties(iotServerConfiguration.getDynamicClientRegistrationEndpoint()));
|
||||
iotServerConfiguration.setOauthTokenEndpoint(
|
||||
replaceProperties(iotServerConfiguration.getOauthTokenEndpoint()));
|
||||
return iotServerConfiguration;
|
||||
} catch (JAXBException | APIMCertificateMGTException e) {
|
||||
log.error("Error occurred while initializing Data Source config", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method gets the values from system variables and sets to xml.
|
||||
*/
|
||||
public static String replaceProperties(String text) {
|
||||
String regex = "\\$\\{(.*?)\\}";
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matchPattern = pattern.matcher(text);
|
||||
while (matchPattern.find()) {
|
||||
String sysPropertyName = matchPattern.group(1);
|
||||
String sysPropertyValue = System.getProperty(sysPropertyName);
|
||||
if (sysPropertyValue != null && !sysPropertyName.isEmpty()) {
|
||||
text = text.replaceAll("\\$\\{(" + sysPropertyName + ")\\}", sysPropertyValue);
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* This class build the iot-api-config.xml file.
|
||||
* @param file
|
||||
|
||||
@ -19,22 +19,22 @@
|
||||
|
||||
<ServerConfiguration>
|
||||
<!-- IoT server host name, this is referred from APIM gateway to call to IoT server for certificate validation-->
|
||||
<Hostname>https://localhost:9443/</Hostname>
|
||||
<Hostname>https://${iot.core.host}:${iot.core.https.port}/</Hostname>
|
||||
|
||||
<!--End point to verify the certificate-->
|
||||
<VerificationEndpoint>https://localhost:9443/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
<VerificationEndpoint>https://${iot.core.host}:${iot.core.https.port}/api/certificate-mgt/v1.0/admin/certificates/verify/</VerificationEndpoint>
|
||||
|
||||
<!--Admin username/password - this is to use for oauth token generation-->
|
||||
<Username>admin</Username>
|
||||
<Password>admin</Password>
|
||||
|
||||
<!--Dynamic client registration endpoint-->
|
||||
<DynamicClientRegistrationEndpoint>https://localhost:9443/dynamic-client-web/register</DynamicClientRegistrationEndpoint>
|
||||
<DynamicClientRegistrationEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/client-registration/v0.11/register</DynamicClientRegistrationEndpoint>
|
||||
|
||||
<!--Oauth token endpoint-->
|
||||
<OauthTokenEndpoint>https://localhost:9443/oauth2/token</OauthTokenEndpoint>
|
||||
<OauthTokenEndpoint>https://${iot.keymanager.host}:${iot.keymanager.https.port}/oauth2/token</OauthTokenEndpoint>
|
||||
|
||||
<APIS>
|
||||
<ContextPath>/services/echo</ContextPath>
|
||||
<ContextPath>/services</ContextPath>
|
||||
</APIS>
|
||||
</ServerConfiguration>
|
||||
@ -13,13 +13,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.client</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
|
||||
@ -21,24 +21,43 @@ package org.wso2.carbon.apimgt.integration.client.util;
|
||||
|
||||
import feign.Client;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLSession;
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import javax.net.ssl.TrustManager;
|
||||
import javax.net.ssl.X509TrustManager;
|
||||
import javax.net.ssl.*;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.io.InputStream;
|
||||
import java.security.*;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import feign.Logger;
|
||||
import feign.Request;
|
||||
import feign.Response;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
|
||||
public class Utils {
|
||||
|
||||
private static final Log log = LogFactory.getLog(Utils.class);
|
||||
|
||||
private static final String KEY_STORE_TYPE = "JKS";
|
||||
/**
|
||||
* Default truststore type of the client
|
||||
*/
|
||||
private static final String TRUST_STORE_TYPE = "JKS";
|
||||
/**
|
||||
* Default keymanager type of the client
|
||||
*/
|
||||
private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type
|
||||
/**
|
||||
* Default trustmanager type of the client
|
||||
*/
|
||||
private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type
|
||||
|
||||
private static final String SSLV3 = "SSLv3";
|
||||
|
||||
|
||||
//This method is only used if the mb features are within DAS.
|
||||
public static String replaceProperties(String text) {
|
||||
String regex = "\\$\\{(.*?)\\}";
|
||||
@ -55,15 +74,20 @@ public class Utils {
|
||||
}
|
||||
|
||||
public static Client getSSLClient() {
|
||||
return new Client.Default(getTrustedSSLSocketFactory(), new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String s, SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
boolean isIgnoreHostnameVerification = Boolean.parseBoolean(System.getProperty("org.wso2.ignoreHostnameVerification"));
|
||||
if(isIgnoreHostnameVerification) {
|
||||
return new Client.Default(getSimpleTrustedSSLSocketFactory(), new HostnameVerifier() {
|
||||
@Override
|
||||
public boolean verify(String s, SSLSession sslSession) {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
}else {
|
||||
return new Client.Default(getTrustedSSLSocketFactory(), null);
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLSocketFactory getTrustedSSLSocketFactory() {
|
||||
private static SSLSocketFactory getSimpleTrustedSSLSocketFactory() {
|
||||
try {
|
||||
TrustManager[] trustAllCerts = new TrustManager[]{
|
||||
new X509TrustManager() {
|
||||
@ -86,4 +110,60 @@ public class Utils {
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static SSLSocketFactory getTrustedSSLSocketFactory() {
|
||||
try {
|
||||
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
|
||||
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
|
||||
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Password");
|
||||
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Location");
|
||||
KeyStore keyStore = loadKeyStore(keyStoreLocation,keyStorePassword,KEY_STORE_TYPE);
|
||||
KeyStore trustStore = loadTrustStore(trustStoreLocation,trustStorePassword);
|
||||
|
||||
return initSSLConnection(keyStore,keyStorePassword,trustStore);
|
||||
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException
|
||||
|CertificateException | IOException | UnrecoverableKeyException e) {
|
||||
log.error("Error while creating the SSL socket factory due to "+e.getMessage(),e);
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static SSLSocketFactory initSSLConnection(KeyStore keyStore,String keyStorePassword,KeyStore trustStore) throws NoSuchAlgorithmException, UnrecoverableKeyException,
|
||||
KeyStoreException, KeyManagementException {
|
||||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
|
||||
keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
|
||||
trustManagerFactory.init(trustStore);
|
||||
|
||||
// Create and initialize SSLContext for HTTPS communication
|
||||
SSLContext sslContext = SSLContext.getInstance(SSLV3);
|
||||
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
|
||||
SSLContext.setDefault(sslContext);
|
||||
return sslContext.getSocketFactory();
|
||||
}
|
||||
|
||||
|
||||
private static KeyStore loadKeyStore(String keyStorePath, String ksPassword,String type)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
InputStream fileInputStream = null;
|
||||
try {
|
||||
char[] keypassChar = ksPassword.toCharArray();
|
||||
KeyStore keyStore = KeyStore.getInstance(type);
|
||||
fileInputStream = new FileInputStream(keyStorePath);
|
||||
keyStore.load(fileInputStream, keypassChar);
|
||||
return keyStore;
|
||||
} finally {
|
||||
if (fileInputStream != null) {
|
||||
fileInputStream.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static KeyStore loadTrustStore(String trustStorePath, String tsPassword)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
return loadKeyStore(trustStorePath,tsPassword,TRUST_STORE_TYPE);
|
||||
}
|
||||
}
|
||||
@ -13,13 +13,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.integration.generated.client</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Integration Generated Client</name>
|
||||
<description>WSO2 Carbon - API Management Integration Client</description>
|
||||
|
||||
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - API Management Webapp Publisher</name>
|
||||
<description>WSO2 Carbon - API Management Webapp Publisher</description>
|
||||
|
||||
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>apimgt-extensions</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>WSO2 Carbon - API Management Extensions Component</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
@ -22,13 +22,13 @@
|
||||
<parent>
|
||||
<artifactId>application-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.application.mgt.api</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>war</packaging>
|
||||
<name>WSO2 Carbon - Application Management API</name>
|
||||
<description>WSO2 Carbon - Application Management API</description>
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>application-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.application.mgt.common</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Application Management Common</name>
|
||||
<description>WSO2 Carbon - Application Management Common</description>
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>application-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.application.mgt.core</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Application Management Core</name>
|
||||
<description>WSO2 Carbon - Application Management Core</description>
|
||||
|
||||
@ -22,14 +22,14 @@
|
||||
<parent>
|
||||
<artifactId>application-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.application.mgt.ui</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<name>WSO2 Carbon - Application Management Base UI</name>
|
||||
<description>WSO2 Carbon - Application Management Base UI</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -38,8 +38,8 @@
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -38,8 +38,8 @@
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
|
||||
@ -21,13 +21,13 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Certificate Management Core</name>
|
||||
<description>WSO2 Carbon - Certificate Management Core</description>
|
||||
|
||||
@ -22,14 +22,14 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>certificate-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>WSO2 Carbon - Certificate Management Component</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -112,7 +112,7 @@
|
||||
org.w3c.dom,
|
||||
org.wso2.carbon.context,
|
||||
org.wso2.carbon.device.mgt.common.*,
|
||||
org.wso2.carbon.device.mgt.extensions.*,
|
||||
org.wso2.carbon.device.mgt.extensions.device.type.template.*,
|
||||
org.wso2.carbon.registry.api,
|
||||
org.wso2.carbon.registry.core,
|
||||
org.wso2.carbon.registry.core.*,
|
||||
|
||||
@ -29,12 +29,12 @@ import org.osgi.framework.ServiceRegistration;
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.DeviceTypeConfiguration;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception.DeviceTypeConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.internal.DeviceTypeManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.DeviceTypeConfigIdentifier;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.DeviceTypeManagerService;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.util.DeviceTypeConfigUtil;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeConfigIdentifier;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.DeviceTypeManagerService;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.DeviceTypeConfiguration;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
@ -1,123 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.device.type.deployer;
|
||||
|
||||
import org.apache.axis2.context.ConfigurationContext;
|
||||
import org.apache.axis2.deployment.AbstractDeployer;
|
||||
import org.apache.axis2.deployment.DeploymentException;
|
||||
import org.apache.axis2.deployment.repository.util.DeploymentFileData;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* This is the device deployer that will read and deploy the device type ui files from
|
||||
* "deployment/server/devicetypes-ui"
|
||||
* directory.
|
||||
*/
|
||||
public class DeviceTypeUIDeployer extends AbstractDeployer {
|
||||
|
||||
private static Log log = LogFactory.getLog(DeviceTypeUIDeployer.class);
|
||||
protected Map<String, String> deviceTypeDeployedUIMap = new ConcurrentHashMap<String, String>();
|
||||
private static final String DEVICEMGT_JAGGERY_APP_PATH = CarbonUtils.getCarbonRepository() + File.separator
|
||||
+ "jaggeryapps" + File.separator + "devicemgt" + File.separator + "app" + File.separator + "units"
|
||||
+ File.separator;
|
||||
|
||||
private static final String UNIT_PREFIX = "cdmf.unit.device.type";
|
||||
|
||||
@Override
|
||||
public void init(ConfigurationContext configurationContext) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setDirectory(String s) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setExtension(String s) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {
|
||||
if (!deploymentFileData.getFile().isDirectory()) {
|
||||
return;
|
||||
}
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
|
||||
if (tenantDomain != null && !tenantDomain.isEmpty()) {
|
||||
File jaggeryAppPath = new File(
|
||||
DEVICEMGT_JAGGERY_APP_PATH + tenantDomain + "." + deploymentFileData.getName());
|
||||
try {
|
||||
if (!jaggeryAppPath.exists()) {
|
||||
FileUtils.forceMkdir(jaggeryAppPath);
|
||||
FileUtils.copyDirectory(deploymentFileData.getFile(), jaggeryAppPath);
|
||||
File[] listOfFiles = jaggeryAppPath.listFiles();
|
||||
|
||||
for (int i = 0; i < listOfFiles.length; i++) {
|
||||
if (listOfFiles[i].isFile()) {
|
||||
String content = FileUtils.readFileToString(listOfFiles[i]);
|
||||
FileUtils.writeStringToFile(listOfFiles[i], content.replaceAll(UNIT_PREFIX
|
||||
, tenantDomain + "." + UNIT_PREFIX));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.debug("units already exists " + deploymentFileData.getName());
|
||||
}
|
||||
this.deviceTypeDeployedUIMap.put(deploymentFileData.getAbsolutePath(),
|
||||
jaggeryAppPath.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
if (jaggeryAppPath.exists()) {
|
||||
try {
|
||||
FileUtils.deleteDirectory(jaggeryAppPath);
|
||||
} catch (IOException e1) {
|
||||
log.error("Failed to delete directory " + jaggeryAppPath.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
log.error("Cannot deploy deviceType ui : " + deploymentFileData.getName(), e);
|
||||
throw new DeploymentException(
|
||||
"Device type ui file " + deploymentFileData.getName() + " is not deployed ", e);
|
||||
}
|
||||
|
||||
} else {
|
||||
log.error("Cannot deploy deviceType ui: " + deploymentFileData.getName());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undeploy(String filePath) throws DeploymentException {
|
||||
try {
|
||||
String jaggeryUnitPath = this.deviceTypeDeployedUIMap.remove(filePath);
|
||||
FileUtils.deleteDirectory(new File(jaggeryUnitPath));
|
||||
log.info("Device Type units un deployed successfully.");
|
||||
} catch (IOException e) {
|
||||
throw new DeploymentException("Failed to remove the units: " + filePath);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,198 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.config;
|
||||
|
||||
import javax.xml.bind.JAXBElement;
|
||||
import javax.xml.bind.annotation.XmlElementDecl;
|
||||
import javax.xml.bind.annotation.XmlRegistry;
|
||||
import javax.xml.namespace.QName;
|
||||
|
||||
|
||||
/**
|
||||
* This object contains factory methods for each
|
||||
* Java content interface and Java element interface
|
||||
* generated in the org.wso2.carbon package.
|
||||
* <p>An ObjectFactory allows you to programatically
|
||||
* construct new instances of the Java representation
|
||||
* for XML content. The Java representation of XML
|
||||
* content can consist of schema derived interfaces
|
||||
* and classes representing the binding of schema
|
||||
* type definitions, element declarations and model
|
||||
* groups. Factory methods for each of these are
|
||||
* provided in this class.
|
||||
*
|
||||
*/
|
||||
@XmlRegistry
|
||||
public class ObjectFactory {
|
||||
|
||||
private final static QName _DeviceTypeConfiguration_QNAME = new QName("", "DeviceTypeConfiguration");
|
||||
|
||||
/**
|
||||
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.wso2.carbon
|
||||
*
|
||||
*/
|
||||
public ObjectFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceTypeConfiguration }
|
||||
*
|
||||
*/
|
||||
public DeviceTypeConfiguration createDeviceTypeConfiguration() {
|
||||
return new DeviceTypeConfiguration();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Operation }
|
||||
*
|
||||
*/
|
||||
public Operation createOperation() {
|
||||
return new Operation();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Attributes }
|
||||
*
|
||||
*/
|
||||
public Attributes createAttributes() {
|
||||
return new Attributes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link ProvisioningConfig }
|
||||
*
|
||||
*/
|
||||
public ProvisioningConfig createProvisioningConfig() {
|
||||
return new ProvisioningConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link TableConfig }
|
||||
*
|
||||
*/
|
||||
public TableConfig createTableConfig() {
|
||||
return new TableConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Table }
|
||||
*
|
||||
*/
|
||||
public Table createTable() {
|
||||
return new Table();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Property }
|
||||
*
|
||||
*/
|
||||
public Property createProperty() {
|
||||
return new Property();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link JndiConfig }
|
||||
*
|
||||
*/
|
||||
public JndiConfig createJndiConfig() {
|
||||
return new JndiConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link FormParameters }
|
||||
*
|
||||
*/
|
||||
public FormParameters createFormParameters() {
|
||||
return new FormParameters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Features }
|
||||
*
|
||||
*/
|
||||
public Features createFeatures() {
|
||||
return new Features();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link Feature }
|
||||
*
|
||||
*/
|
||||
public Feature createFeature() {
|
||||
return new Feature();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link PushNotificationProvider }
|
||||
*
|
||||
*/
|
||||
public PushNotificationProvider createPushNotificationProvider() {
|
||||
return new PushNotificationProvider();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DataSource }
|
||||
*
|
||||
*/
|
||||
public DataSource createDataSource() {
|
||||
return new DataSource();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link ConfigProperties }
|
||||
*
|
||||
*/
|
||||
public ConfigProperties createConfigProperties() {
|
||||
return new ConfigProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link License }
|
||||
*
|
||||
*/
|
||||
public License createLicense() {
|
||||
return new License();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceDetails }
|
||||
*
|
||||
*/
|
||||
public DeviceDetails createDeviceDetails() {
|
||||
return new DeviceDetails();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link QueryParameters }
|
||||
*
|
||||
*/
|
||||
public QueryParameters createQueryParameters() {
|
||||
return new QueryParameters();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link JAXBElement }{@code <}{@link DeviceTypeConfiguration }{@code >}}
|
||||
*
|
||||
*/
|
||||
@XmlElementDecl(namespace = "", name = "DeviceTypeConfiguration")
|
||||
public JAXBElement<DeviceTypeConfiguration> createDeviceTypeConfiguration(DeviceTypeConfiguration value) {
|
||||
return new JAXBElement<DeviceTypeConfiguration>(_DeviceTypeConfiguration_QNAME, DeviceTypeConfiguration.class, null, value);
|
||||
}
|
||||
|
||||
}
|
||||
@ -28,7 +28,7 @@ import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.utils.ConfigurationContextService;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.device.mgt.iot.internal.DeviceTypeManagementServiceComponent"
|
||||
* @scr.component name="org.wso2.carbon.device.mgt.iot.internal.DeviceTypeExtensionServiceComponent"
|
||||
* immediate="true"
|
||||
* @scr.reference name="config.context.service"
|
||||
* interface="org.wso2.carbon.utils.ConfigurationContextService"
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.util;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.deployer.config.exception.DeviceTypeConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.extensions.device.type.template.config.exception.DeviceTypeConfigurationException;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
|
||||
@ -22,9 +22,6 @@ package org.wso2.carbon.device.mgt.extensions.device.type.deployer.util;
|
||||
* This holds the constants used for this bundle.
|
||||
*/
|
||||
public class DeviceTypePluginConstants {
|
||||
public static final String MEDIA_TYPE_XML = "application/xml";
|
||||
public static final String CHARSET_UTF8 = "UTF8";
|
||||
public static final String LANGUAGE_CODE_ENGLISH_US = "en_US";
|
||||
|
||||
public static final String CDMF_UI_TYPE = "devicetype/ui";
|
||||
public static final String CDMF_UI_TYPE_DIR = "devicetypes-ui";
|
||||
|
||||
@ -1,128 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
<DeviceTypeConfiguration name="samples">
|
||||
|
||||
<DeviceDetails table-id="SAMPLE_DEVICE_1"/>
|
||||
|
||||
<Features>
|
||||
<Feature code="abc">
|
||||
<Name>abc</Name>
|
||||
<Description>this is a feature</Description>
|
||||
<Operation context="/bulb/{state}" method="PUT" type="application/json">
|
||||
<QueryParameters>
|
||||
<Parameter>deviceId</Parameter>
|
||||
</QueryParameters>
|
||||
<FormParameters>
|
||||
<Parameter>test</Parameter>
|
||||
</FormParameters>
|
||||
</Operation>
|
||||
</Feature>
|
||||
</Features>
|
||||
|
||||
<Claimable enabled="true"/>
|
||||
|
||||
<Sensors table-id="SAMPLE_DEVICE_2">
|
||||
<Sensor code="CPU_Temperature">
|
||||
<Name>temperature sensor fitted</Name>
|
||||
<StreamDefinition>org.wso2.temperature.stream</StreamDefinition>
|
||||
<Description>this is a sensor</Description>
|
||||
<SensorStaticProperties>
|
||||
<Property name="unit">celcius</Property>
|
||||
<Property name="model_number">atmeggga11234</Property>
|
||||
</SensorStaticProperties>
|
||||
</Sensor>
|
||||
<Sensor code="DHT11_Temperature">
|
||||
<Name>temperature sensor fitted</Name>
|
||||
<StreamDefinition>org.wso2.temperature.stream</StreamDefinition>
|
||||
<Description>this is a sensor</Description>
|
||||
<SensorStaticProperties>
|
||||
<Property name="unit">celcius</Property>
|
||||
</SensorStaticProperties>
|
||||
<SensorDynamicProperties>
|
||||
<Property name="model_number"/>
|
||||
</SensorDynamicProperties>
|
||||
</Sensor>
|
||||
</Sensors>
|
||||
|
||||
<ProvisioningConfig>
|
||||
<SharedWithAllTenants>false</SharedWithAllTenants>
|
||||
</ProvisioningConfig>
|
||||
|
||||
<DeviceAuthorizationConfig>
|
||||
<authorizationRequired>true</authorizationRequired>
|
||||
</DeviceAuthorizationConfig>
|
||||
|
||||
<PushNotificationProvider type="MQTT">
|
||||
<FileBasedProperties>true</FileBasedProperties>
|
||||
<!--if file based properties is set to false then the configuration will be picked from platform configuration-->
|
||||
<ConfigProperties>
|
||||
<Property Name="mqttAdapterName">sample.mqtt.adapter</Property>
|
||||
<Property Name="url">tcp://localhost:1883</Property>
|
||||
<Property Name="username">admin</Property>
|
||||
<Property Name="password">admin</Property>
|
||||
<Property Name="qos">0</Property>
|
||||
<Property Name="scopes"/>
|
||||
<Property Name="clearSession">true</Property>
|
||||
</ConfigProperties>
|
||||
</PushNotificationProvider>
|
||||
|
||||
<PolicyMonitoring enabled="true"/>
|
||||
|
||||
<License>
|
||||
<Language>en_US</Language>
|
||||
<Version>1.0.0</Version>
|
||||
<Text>This is license text</Text>
|
||||
</License>
|
||||
|
||||
<TaskConfiguration>
|
||||
<Enable>true</Enable>
|
||||
<Frequency>600000</Frequency>
|
||||
<Operations>
|
||||
<Operation>
|
||||
<Name>DEVICE_INFO</Name>
|
||||
<RecurrentTimes>1</RecurrentTimes>
|
||||
</Operation>
|
||||
<Operation>
|
||||
<Name>APPLICATION_LIST</Name>
|
||||
<RecurrentTimes>5</RecurrentTimes>
|
||||
</Operation>
|
||||
<Operation>
|
||||
<Name>DEVICE_LOCATION</Name>
|
||||
<RecurrentTimes>1</RecurrentTimes>
|
||||
</Operation>
|
||||
</Operations>
|
||||
</TaskConfiguration>
|
||||
|
||||
<DataSource>
|
||||
<jndiConfig>
|
||||
<name>jdbc/SampleDM_DB</name>
|
||||
</jndiConfig>
|
||||
<tableConfig>
|
||||
<Table name="SAMPLE_DEVICE_1">
|
||||
<PrimaryKey>SAMPLE_DEVICE_ID</PrimaryKey>
|
||||
<Attributes>
|
||||
<Attribute>column1</Attribute>
|
||||
<Attribute>column2</Attribute>
|
||||
</Attributes>
|
||||
</Table>
|
||||
</tableConfig>
|
||||
</DataSource>
|
||||
|
||||
</DeviceTypeConfiguration>
|
||||
@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ 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.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions.pull.notification</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Pull Notification Provider Implementation</name>
|
||||
<description>WSO2 Carbon - Pull Notification Provider Implementation</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
|
||||
<Bundle-Description>Pull Notification Provider Bundle</Bundle-Description>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.device.mgt.extensions.pull.notification.internal,
|
||||
org.wso2.carbon.device.mgt.extensions.pull.notification.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
org.osgi.framework,
|
||||
org.osgi.service.component,
|
||||
org.apache.commons.logging,
|
||||
org.wso2.carbon.device.mgt.common.*,
|
||||
org.wso2.carbon.device.mgt.core.service
|
||||
org.wso2.carbon.policy.mgt.core.*,
|
||||
org.wso2.carbon.policy.mgt.core,
|
||||
com.google.gson,
|
||||
org.wso2.carbon.device.mgt.core.service.*
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@ -0,0 +1,102 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.pull.notification;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
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.policy.mgt.monitor.ComplianceFeature;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
|
||||
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationExecutionFailedException;
|
||||
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber;
|
||||
import org.wso2.carbon.device.mgt.extensions.pull.notification.internal.PullNotificationDataHolder;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class PullNotificationSubscriberImpl implements PullNotificationSubscriber {
|
||||
|
||||
public final class OperationCodes {
|
||||
private OperationCodes() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
public static final String POLICY_MONITOR = "POLICY_MONITOR";
|
||||
}
|
||||
|
||||
|
||||
private static final Log log = LogFactory.getLog(PullNotificationSubscriberImpl.class);
|
||||
|
||||
public void init(Map<String, String> properties) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(DeviceIdentifier deviceIdentifier, Operation operation) throws PullNotificationExecutionFailedException {
|
||||
try {
|
||||
if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null &&
|
||||
OperationCodes.POLICY_MONITOR.equals(operation.getCode())) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId());
|
||||
}
|
||||
List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad());
|
||||
PullNotificationDataHolder.getInstance().getPolicyManagerService()
|
||||
.checkCompliance(deviceIdentifier, features);
|
||||
|
||||
} else {
|
||||
PullNotificationDataHolder.getInstance().getDeviceManagementProviderService().updateOperation(
|
||||
deviceIdentifier, operation);
|
||||
}
|
||||
} catch (OperationManagementException e) {
|
||||
throw new PullNotificationExecutionFailedException(e);
|
||||
} catch (PolicyComplianceException e) {
|
||||
throw new PullNotificationExecutionFailedException("Invalid payload format compliant feature", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void clean() {
|
||||
|
||||
}
|
||||
|
||||
private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload) throws
|
||||
PolicyComplianceException {
|
||||
String compliancePayloadString = new Gson().toJson(compliancePayload);
|
||||
if (compliancePayload == null) {
|
||||
return null;
|
||||
}
|
||||
// Parsing json string to get compliance features.
|
||||
JsonElement jsonElement = new JsonParser().parse(compliancePayloadString);
|
||||
JsonArray jsonArray = jsonElement.getAsJsonArray();
|
||||
Gson gson = new Gson();
|
||||
ComplianceFeature complianceFeature;
|
||||
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
|
||||
|
||||
for (JsonElement element : jsonArray) {
|
||||
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
|
||||
complianceFeatures.add(complianceFeature);
|
||||
}
|
||||
return complianceFeatures;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.pull.notification.internal;
|
||||
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||
|
||||
public class PullNotificationDataHolder {
|
||||
|
||||
private DeviceManagementProviderService deviceManagementProviderService;
|
||||
private PolicyManagerService policyManagerService;
|
||||
|
||||
private static PullNotificationDataHolder thisInstance = new PullNotificationDataHolder();
|
||||
|
||||
public static PullNotificationDataHolder getInstance() {
|
||||
return thisInstance;
|
||||
}
|
||||
|
||||
public DeviceManagementProviderService getDeviceManagementProviderService() {
|
||||
return deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) {
|
||||
this.deviceManagementProviderService = deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public PolicyManagerService getPolicyManagerService() {
|
||||
return policyManagerService;
|
||||
}
|
||||
|
||||
public void setPolicyManagerService(PolicyManagerService policyManagerService) {
|
||||
this.policyManagerService = policyManagerService;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.pull.notification.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.device.mgt.extensions.pull.notification.internal.PullNotificationServiceComponent" immediate="true"
|
||||
* @scr.reference name="carbon.device.mgt.provider"
|
||||
* interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setDeviceManagementProviderService"
|
||||
* unbind="unsetDeviceManagementProviderService"
|
||||
* @scr.reference name="org.wso2.carbon.policy.mgt.core"
|
||||
* interface="org.wso2.carbon.policy.mgt.core.PolicyManagerService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setPolicyManagerService"
|
||||
* unbind="unsetPolicyManagerService"
|
||||
*/
|
||||
public class PullNotificationServiceComponent {
|
||||
|
||||
private static final Log log = LogFactory.getLog(PullNotificationServiceComponent.class);
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
protected void activate(ComponentContext componentContext) {
|
||||
try {
|
||||
//Do nothing
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("pull notification provider implementation bundle has been successfully " +
|
||||
"initialized");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while initializing pull notification provider " +
|
||||
"implementation bundle", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void deactivate(ComponentContext componentContext) {
|
||||
//Do nothing
|
||||
}
|
||||
|
||||
protected void setDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) {
|
||||
PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(deviceManagementProviderService);
|
||||
}
|
||||
|
||||
protected void unsetDeviceManagementProviderService(DeviceManagementProviderService deviceManagementProviderService) {
|
||||
PullNotificationDataHolder.getInstance().setDeviceManagementProviderService(null);
|
||||
}
|
||||
|
||||
protected void setPolicyManagerService(PolicyManagerService policyManagerService) {
|
||||
PullNotificationDataHolder.getInstance().setPolicyManagerService(policyManagerService);
|
||||
}
|
||||
|
||||
protected void unsetPolicyManagerService(PolicyManagerService policyManagerService) {
|
||||
PullNotificationDataHolder.getInstance().setPolicyManagerService(null);
|
||||
}
|
||||
|
||||
}
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -57,7 +57,7 @@ public class FCMNotificationStrategy implements NotificationStrategy {
|
||||
public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException {
|
||||
try {
|
||||
Device device =
|
||||
FCMDataHolder.getInstance().getDeviceManagementProviderService().getDevice(ctx.getDeviceId());
|
||||
FCMDataHolder.getInstance().getDeviceManagementProviderService().getDeviceWithTypeProperties(ctx.getDeviceId());
|
||||
this.sendWakeUpCall(ctx.getOperation().getCode(), device);
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new PushNotificationExecutionFailedException("Error occurred while retrieving device information", e);
|
||||
|
||||
@ -1,87 +1,71 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ you may obtain a copy of the License at
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<artifactId>dynamic-client-registration</artifactId>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.dynamic.client.web.app.registration</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions.push.notification.provider.http</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Dynamic client web app registration</name>
|
||||
<description>WSO2 Carbon - Dynamic Client Web-app Registration Service</description>
|
||||
<name>WSO2 Carbon - HTTP Based Push Notification Provider Implementation</name>
|
||||
<description>WSO2 Carbon - HTTP Based Push Notification Provider Implementation</description>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>1.4.0</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
|
||||
<Bundle-Description>Dynamic Client Web App Registration Bundle</Bundle-Description>
|
||||
<Private-Package>org.wso2.carbon.dynamic.client.web.app.registration.internal</Private-Package>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.dynamic.client.web.app.registration.internal,
|
||||
org.wso2.carbon.dynamic.client.web.app.registration.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
javax.xml.bind.*,
|
||||
com.google.*,
|
||||
javax.net.ssl,
|
||||
javax.servlet,
|
||||
org.apache.axis2.context,
|
||||
org.apache.catalina,
|
||||
org.apache.catalina.core,
|
||||
org.apache.commons.*,
|
||||
org.apache.http,
|
||||
org.apache.http.*,
|
||||
org.osgi.framework,
|
||||
org.osgi.service.component,
|
||||
org.wso2.carbon.context,
|
||||
org.wso2.carbon.core,
|
||||
org.wso2.carbon.core.security,
|
||||
org.wso2.carbon.dynamic.client.*,
|
||||
org.wso2.carbon.registry.*,
|
||||
org.wso2.carbon.user.*,
|
||||
org.wso2.carbon.utils
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.governance</groupId>
|
||||
<artifactId>org.wso2.carbon.governance.api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.ws.commons.axiom.wso2</groupId>
|
||||
<artifactId>axiom</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.org.scannotation</groupId>
|
||||
<artifactId>scannotation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
@ -90,26 +74,6 @@
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testng</groupId>
|
||||
<artifactId>testng</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.application.mgt</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.inbound.auth.oauth2</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.oauth</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.tomcat</groupId>
|
||||
<artifactId>tomcat</artifactId>
|
||||
@ -119,28 +83,65 @@
|
||||
<artifactId>tomcat-servlet-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.core</artifactId>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.dynamic.client.registration</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<groupId>commons-lang.wso2</groupId>
|
||||
<artifactId>commons-lang</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
|
||||
<Bundle-Description>MQTT Based Push Notification Provider Bundle</Bundle-Description>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal,
|
||||
org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.*
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
org.apache.commons.logging,
|
||||
org.osgi.service.component,
|
||||
org.wso2.carbon.context,
|
||||
org.wso2.carbon.device.mgt.common.operation.mgt,
|
||||
org.wso2.carbon.device.mgt.common.push.notification,
|
||||
org.wso2.carbon.device.mgt.common,
|
||||
org.wso2.carbon.device.mgt.core.service,
|
||||
org.osgi.framework,
|
||||
org.wso2.carbon.device.mgt.core.operation.mgt,
|
||||
org.wso2.carbon.core,
|
||||
com.google.gson,
|
||||
org.apache.commons.httpclient.*
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@ -16,24 +16,22 @@
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http;
|
||||
|
||||
package org.wso2.carbon.device.mgt.extensions.device.type.deployer.template.dao;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationProvider;
|
||||
|
||||
public class DeviceTypePluginDAOManager {
|
||||
public class HTTPBasedPushNotificationProvider implements PushNotificationProvider {
|
||||
|
||||
private DeviceTypePluginDAO deviceTypePluginDAO;
|
||||
private DeviceTypeDAOHandler deviceTypeDAOHandler;
|
||||
|
||||
public DeviceTypePluginDAOManager(String datasourceName, DeviceDAODefinition deviceDAODefinition) {
|
||||
deviceTypeDAOHandler = new DeviceTypeDAOHandler(datasourceName);
|
||||
deviceTypePluginDAO = new DeviceTypePluginDAO(deviceDAODefinition, deviceTypeDAOHandler);
|
||||
@Override
|
||||
public String getType() {
|
||||
return "HTTP";
|
||||
}
|
||||
|
||||
public DeviceTypePluginDAO getDeviceDAO() {
|
||||
return deviceTypePluginDAO;
|
||||
@Override
|
||||
public NotificationStrategy getNotificationStrategy(PushNotificationConfig config) {
|
||||
return new HTTPNotificationStrategy(config);
|
||||
}
|
||||
|
||||
public DeviceTypeDAOHandler getDeviceTypeDAOHandler() {
|
||||
return deviceTypeDAOHandler;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,94 @@
|
||||
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.apache.commons.httpclient.HostConfiguration;
|
||||
import org.apache.commons.httpclient.HttpClient;
|
||||
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
|
||||
import org.apache.commons.httpclient.methods.PostMethod;
|
||||
import org.apache.commons.httpclient.methods.StringRequestEntity;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
public class HTTPMessageExecutor implements Runnable {
|
||||
|
||||
private String url;
|
||||
private String authorizationHeader;
|
||||
private String payload;
|
||||
private HostConfiguration hostConfiguration;
|
||||
private HttpClient httpClient;
|
||||
private static final String APPLIATION_JSON = "application/json";
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
private static final Log log = LogFactory.getLog(HTTPMessageExecutor.class);
|
||||
|
||||
public HTTPMessageExecutor(NotificationContext notificationContext, String authorizationHeader, String url
|
||||
, HostConfiguration hostConfiguration, HttpClient httpClient) {
|
||||
this.url = url;
|
||||
this.authorizationHeader = authorizationHeader;
|
||||
Gson gson = new Gson();
|
||||
this.payload = gson.toJson(notificationContext);
|
||||
this.hostConfiguration = hostConfiguration;
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getAuthorizationHeader() {
|
||||
return authorizationHeader;
|
||||
}
|
||||
|
||||
public void setAuthorizationHeader(String authorizationHeader) {
|
||||
this.authorizationHeader = authorizationHeader;
|
||||
}
|
||||
|
||||
public String getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
public void setPayload(String payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
public HttpClient getHttpClient() {
|
||||
return httpClient;
|
||||
}
|
||||
|
||||
public void setHttpClient(HttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
EntityEnclosingMethod method = null;
|
||||
|
||||
try {
|
||||
method = new PostMethod(this.getUrl());
|
||||
method.setRequestEntity(new StringRequestEntity(this.getPayload(), APPLIATION_JSON, "UTF-8"));
|
||||
if (authorizationHeader != null && authorizationHeader.isEmpty()) {
|
||||
method.setRequestHeader(AUTHORIZATION_HEADER, authorizationHeader);
|
||||
}
|
||||
|
||||
this.getHttpClient().executeMethod(hostConfiguration, method);
|
||||
|
||||
} catch (UnknownHostException e) {
|
||||
log.error("Push Notification message dropped " + url, e);
|
||||
throw new InvalidConfigurationException("invalid host: url", e);
|
||||
} catch (Throwable e) {
|
||||
log.error("Push Notification message dropped ", e);
|
||||
throw new InvalidConfigurationException("Push Notification message dropped, " + e.getMessage(), e);
|
||||
} finally {
|
||||
if (method != null) {
|
||||
method.releaseConnection();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,103 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http;
|
||||
|
||||
import org.apache.commons.httpclient.HostConfiguration;
|
||||
import org.apache.commons.httpclient.HttpClient;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
|
||||
public class HTTPNotificationStrategy implements NotificationStrategy {
|
||||
|
||||
private static final Log log = LogFactory.getLog(HTTPNotificationStrategy.class);
|
||||
private final PushNotificationConfig config;
|
||||
private static final String URL_PROPERTY = "url";
|
||||
private static final String AUTHORIZATION_HEADER_PROPERTY = "authorization";
|
||||
private String endpoint;
|
||||
private static ExecutorService executorService;
|
||||
private HttpClient httpClient = null;
|
||||
private HostConfiguration hostConfiguration;
|
||||
private String authorizationHeaderValue;
|
||||
private String uri;
|
||||
|
||||
public HTTPNotificationStrategy(PushNotificationConfig config) {
|
||||
this.config = config;
|
||||
if (this.config == null) {
|
||||
throw new InvalidConfigurationException("Properties Cannot be found");
|
||||
}
|
||||
endpoint = config.getProperties().get(URL_PROPERTY);
|
||||
if (endpoint == null || endpoint.isEmpty()) {
|
||||
throw new InvalidConfigurationException("Property - 'url' cannot be found");
|
||||
}
|
||||
try {
|
||||
this.uri = endpoint;
|
||||
URL url = new URL(endpoint);
|
||||
hostConfiguration = new HostConfiguration();
|
||||
hostConfiguration.setHost(url.getHost(), url.getPort(), url.getProtocol());
|
||||
this.authorizationHeaderValue = config.getProperties().get(AUTHORIZATION_HEADER_PROPERTY);
|
||||
executorService = Executors.newFixedThreadPool(1);
|
||||
httpClient = new HttpClient();
|
||||
} catch (MalformedURLException e) {
|
||||
throw new InvalidConfigurationException("Property - 'url' is malformed.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException {
|
||||
try {
|
||||
executorService.submit(new HTTPMessageExecutor(ctx, authorizationHeaderValue, uri, hostConfiguration
|
||||
, httpClient));
|
||||
} catch (RejectedExecutionException e) {
|
||||
log.error("Failed to publish to external endpoint url: " + endpoint, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public NotificationContext buildContext() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void undeploy() {
|
||||
executorService.shutdown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public PushNotificationConfig getConfig() {
|
||||
return config;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.device.mgt.extensions.push.notification.provider.http.internal.HTTPPushNotificationServiceComponent" immediate="true"
|
||||
*/
|
||||
public class HTTPPushNotificationServiceComponent {
|
||||
|
||||
private static final Log log = LogFactory.getLog(HTTPPushNotificationServiceComponent.class);
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
protected void activate(ComponentContext componentContext) {
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Initializing HTTP based push notification provider implementation bundle");
|
||||
}
|
||||
//Do nothing
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("HTTP based push notification provider implementation bundle has been successfully " +
|
||||
"initialized");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while initializing HTTP based push notification provider " +
|
||||
"implementation bundle", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -21,8 +21,8 @@ package org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.Profile;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
@ -46,36 +46,52 @@ public class MQTTNotificationStrategy implements NotificationStrategy {
|
||||
private String mqttAdapterName;
|
||||
private static final Log log = LogFactory.getLog(MQTTNotificationStrategy.class);
|
||||
private final PushNotificationConfig config;
|
||||
private final String providerTenantDomain;
|
||||
private static final Object lockObj = new Object();
|
||||
|
||||
public MQTTNotificationStrategy(PushNotificationConfig config) {
|
||||
this.config = config;
|
||||
OutputEventAdapterConfiguration adapterConfig = new OutputEventAdapterConfiguration();
|
||||
adapterConfig.setType(MQTTAdapterConstants.MQTT_ADAPTER_TYPE);
|
||||
mqttAdapterName = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME);
|
||||
adapterConfig.setName(mqttAdapterName);
|
||||
adapterConfig.setMessageFormat(MessageType.TEXT);
|
||||
|
||||
Map<String, String> configProperties = new HashMap<String, String>();
|
||||
String brokerUrl = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL);
|
||||
if (brokerUrl != null && !brokerUrl.isEmpty()) {
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, brokerUrl);
|
||||
if (config.getProperties() != null && config.getProperties().size() > 0) {
|
||||
String brokerUrl = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL);
|
||||
if (brokerUrl != null && !brokerUrl.isEmpty()) {
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_BROKER_URL, brokerUrl);
|
||||
}
|
||||
mqttAdapterName = config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_NAME);
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS));
|
||||
} else {
|
||||
mqttAdapterName = "mqtt.adapter." + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()
|
||||
.toLowerCase();
|
||||
}
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_USERNAME));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_PASSWORD));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_CLEAR_SESSION));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_SCOPES));
|
||||
configProperties.put(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS,
|
||||
config.getProperty(MQTTAdapterConstants.MQTT_ADAPTER_PROPERTY_MESSAGE_QOS));
|
||||
adapterConfig.setName(mqttAdapterName);
|
||||
adapterConfig.setStaticProperties(configProperties);
|
||||
try {
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig);
|
||||
synchronized (lockObj) {
|
||||
try {
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().isPolled(mqttAdapterName);
|
||||
} catch (OutputEventAdapterException e) {
|
||||
//event adapter not created
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig);
|
||||
}
|
||||
}
|
||||
} catch (OutputEventAdapterException e) {
|
||||
throw new InvalidConfigurationException("Error occurred while initializing MQTT output event adapter", e);
|
||||
}
|
||||
providerTenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -85,42 +101,73 @@ public class MQTTNotificationStrategy implements NotificationStrategy {
|
||||
|
||||
@Override
|
||||
public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException {
|
||||
String adapterName = mqttAdapterName;
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
|
||||
if (!providerTenantDomain.equals(tenantDomain)) {
|
||||
//this is to handle the device type shared with all tenant mode.
|
||||
|
||||
adapterName = "mqtt.adapter." + PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()
|
||||
.toLowerCase();
|
||||
try {
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().isPolled(adapterName);
|
||||
} catch (OutputEventAdapterException e) {
|
||||
//event adapter not created
|
||||
synchronized (lockObj) {
|
||||
OutputEventAdapterConfiguration adapterConfig = new OutputEventAdapterConfiguration();
|
||||
adapterConfig.setType(MQTTAdapterConstants.MQTT_ADAPTER_TYPE);
|
||||
adapterConfig.setMessageFormat(MessageType.TEXT);
|
||||
adapterConfig.setName(adapterName);
|
||||
Map<String, String> configProperties = new HashMap<String, String>();
|
||||
adapterConfig.setStaticProperties(configProperties);
|
||||
try {
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().create(adapterConfig);
|
||||
} catch (OutputEventAdapterException e1) {
|
||||
throw new PushNotificationExecutionFailedException
|
||||
("Error occurred while initializing MQTT output event adapter for shared tenant: "
|
||||
+ tenantDomain, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Operation operation = ctx.getOperation();
|
||||
Properties properties = operation.getProperties();
|
||||
if (properties != null && properties.get(MQTT_ADAPTER_TOPIC) != null) {
|
||||
Map<String, String> dynamicProperties = new HashMap<>();
|
||||
dynamicProperties.put("topic", (String) properties.get(MQTT_ADAPTER_TOPIC));
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties,
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties,
|
||||
operation.getPayLoad());
|
||||
} else {
|
||||
if (PolicyOperation.POLICY_OPERATION_CODE.equals(operation.getCode())) {
|
||||
PolicyOperation policyOperation = (PolicyOperation) operation;
|
||||
List<ProfileOperation> profileOperations = policyOperation.getProfileOperations();
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
|
||||
String deviceType = ctx.getDeviceId().getType();
|
||||
String deviceId = ctx.getDeviceId().getId();
|
||||
for (ProfileOperation profileOperation : profileOperations) {
|
||||
Map<String, String> dynamicProperties = new HashMap<>();
|
||||
String topic = tenantDomain + "/"
|
||||
+ deviceType + "/" + deviceId + "/" + profileOperation.getType()
|
||||
+ deviceType + "/" + deviceId + "/operation/" + profileOperation.getType()
|
||||
.toString().toLowerCase() + "/" + profileOperation.getCode().toLowerCase();
|
||||
dynamicProperties.put("topic", topic);
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties,
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties,
|
||||
profileOperation.getPayLoad());
|
||||
}
|
||||
|
||||
} else {
|
||||
Map<String, String> dynamicProperties = new HashMap<>();
|
||||
String topic = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true) + "/"
|
||||
+ ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/" + operation.getType()
|
||||
.toString().toLowerCase() + "/" + operation.getCode();
|
||||
+ ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/operation/"
|
||||
+ operation.getType().toString().toLowerCase() + "/" + operation.getCode() + "/" + operation.getId();
|
||||
dynamicProperties.put("topic", topic);
|
||||
if (operation.getPayLoad() == null) {
|
||||
operation.setPayLoad("");
|
||||
Object payload;
|
||||
if ("command".equals(operation.getType().toString().toLowerCase())) {
|
||||
payload = operation.getCode();
|
||||
} else {
|
||||
payload = operation.getPayLoad();
|
||||
}
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties,
|
||||
operation.getPayLoad());
|
||||
MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(adapterName, dynamicProperties,
|
||||
payload);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt-extensions</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>carbon-devicemgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -34,10 +34,12 @@
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<modules>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.http</module>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm</module>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt</module>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp</module>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.device.type.deployer</module>
|
||||
<module>org.wso2.carbon.device.mgt.extensions.pull.notification</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@ -3,7 +3,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -66,10 +66,6 @@
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.agent</artifactId>
|
||||
@ -118,6 +114,7 @@
|
||||
org.osgi.framework,
|
||||
org.osgi.service.component,
|
||||
org.apache.commons.logging.*,
|
||||
org.wso2.carbon.utils.multitenancy,
|
||||
org.wso2.carbon.context;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.utils;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.databridge.*;version="${carbon.analytics.common.version.range}",
|
||||
@ -126,14 +123,15 @@
|
||||
org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}",
|
||||
org.json;version="${commons-json.version}",
|
||||
javax.xml.*,
|
||||
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.w3c.dom,
|
||||
org.wso2.carbon.base
|
||||
org.wso2.carbon.base,
|
||||
org.wso2.carbon.utils.multitenancy
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
|
||||
</project>
|
||||
|
||||
@ -21,10 +21,12 @@ package org.wso2.carbon.device.mgt.analytics.data.publisher.service;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.databridge.agent.DataPublisher;
|
||||
import org.wso2.carbon.databridge.commons.utils.DataBridgeCommonsUtils;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.DeviceDataPublisher;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||
|
||||
/**
|
||||
* This is the implementation of Osgi Service which can be used to publish and retireved
|
||||
@ -39,23 +41,37 @@ public class EventsPublisherServiceImpl implements EventsPublisherService {
|
||||
* @param metaDataArray - meta data that needs to pushed
|
||||
* @param correlationDataArray - correlation data that needs to be pushed
|
||||
* @param payloadDataArray - payload data that needs to be pushed
|
||||
* @return
|
||||
* @return if success returns true
|
||||
* @throws DataPublisherConfigurationException
|
||||
*/
|
||||
@Override
|
||||
public boolean publishEvent(String streamName, String version, Object[] metaDataArray,
|
||||
Object[] correlationDataArray,
|
||||
Object[] payloadDataArray) throws DataPublisherConfigurationException {
|
||||
DataPublisher dataPublisher = DeviceDataPublisher.getInstance().getDataPublisher();
|
||||
if (dataPublisher != null) {
|
||||
String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version);
|
||||
return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray, correlationDataArray,
|
||||
payloadDataArray);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
|
||||
if (metaDataArray == null || metaDataArray.length == 0) {
|
||||
throw new DataPublisherConfigurationException("meta data[0] should have the device Id field");
|
||||
} else {
|
||||
metaDataArray[0] = tenantDomain + "@" + metaDataArray[0];
|
||||
}
|
||||
}
|
||||
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext()
|
||||
.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
|
||||
try {
|
||||
DataPublisher dataPublisher = DeviceDataPublisher.getInstance().getDataPublisher();
|
||||
if (dataPublisher != null) {
|
||||
String streamId = DataBridgeCommonsUtils.generateStreamId(streamName, version);
|
||||
return dataPublisher.tryPublish(streamId, System.currentTimeMillis(), metaDataArray,
|
||||
correlationDataArray,
|
||||
payloadDataArray);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -22,7 +22,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -38,8 +38,8 @@
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
<source>1.8</source>
|
||||
<target>1.8</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
@ -167,6 +167,16 @@
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
@ -280,34 +290,78 @@
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>javax.ws.rs-api</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.receiver.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.stream.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.commons</groupId>
|
||||
<artifactId>org.wso2.carbon.application.mgt.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.registry</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.resource</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.identity.framework</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.user.store.count</artifactId>
|
||||
<version>${carbon.identity.framework.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.dataservice.commons</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.receiver.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.stream.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.publisher.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.stream.persistence.stub</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and limitations under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans;
|
||||
|
||||
import io.swagger.annotations.ApiModel;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ApiModel(value = "OperationRequest", description = "Operation details together with deviceIdentifier")
|
||||
public class OperationRequest {
|
||||
|
||||
@ApiModelProperty(name = "deviceIdentifiers", value = "list of devices that needs to be verified against the user", required = true)
|
||||
List<String> deviceIdentifiers;
|
||||
@ApiModelProperty(name = "operation", value = "operation data", required = false)
|
||||
Operation operation;
|
||||
|
||||
public List<String> getDeviceIdentifiers() {
|
||||
return deviceIdentifiers;
|
||||
}
|
||||
|
||||
public void setDeviceIdentifiers(List<String> deviceIdentifiers) {
|
||||
this.deviceIdentifiers = deviceIdentifiers;
|
||||
}
|
||||
|
||||
public Operation getOperation() {
|
||||
return operation;
|
||||
}
|
||||
|
||||
public void setOperation(Operation operation) {
|
||||
this.operation = operation;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* This hold the attribute definition.
|
||||
*/
|
||||
public class Attribute {
|
||||
|
||||
@ApiModelProperty(value = "Event Attribute Name")
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@ApiModelProperty(value = "Event Attribute Type")
|
||||
@JsonProperty("type")
|
||||
private AttributeType type;
|
||||
|
||||
public Attribute() {
|
||||
|
||||
}
|
||||
|
||||
public Attribute(String name, AttributeType attributeType) {
|
||||
this.name = name;
|
||||
this.type = attributeType;
|
||||
}
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public AttributeType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(AttributeType type) {
|
||||
this.type = type;
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
/**
|
||||
* This hold the definition of the attribute type for the attributes.
|
||||
*/
|
||||
public enum AttributeType {
|
||||
STRING, LONG, BOOL, INT, FLOAT, DOUBLE;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
|
||||
/**
|
||||
* This hold stats data record
|
||||
*/
|
||||
public class DeviceTypeEvent {
|
||||
|
||||
private EventAttributeList eventAttributes;
|
||||
private TransportType transport;
|
||||
|
||||
@ApiModelProperty(value = "Attributes related to device type event")
|
||||
@JsonProperty("eventAttributes")
|
||||
public EventAttributeList getEventAttributeList() {
|
||||
return eventAttributes;
|
||||
}
|
||||
|
||||
public void setEventAttributeList(
|
||||
EventAttributeList eventAttributes) {
|
||||
this.eventAttributes = eventAttributes;
|
||||
}
|
||||
|
||||
@ApiModelProperty(value = "Transport to be used for device to server communication.")
|
||||
@JsonProperty("transport")
|
||||
public TransportType getTransportType() {
|
||||
return transport;
|
||||
}
|
||||
|
||||
public void setTransportType(TransportType transport) {
|
||||
this.transport = transport;
|
||||
}
|
||||
}
|
||||
|
||||
@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.BasePaginatedResult;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This holds event attributes
|
||||
*/
|
||||
public class EventAttributeList {
|
||||
|
||||
private List<Attribute> attributes = new ArrayList<>();
|
||||
|
||||
@ApiModelProperty(value = "List of Event Attributes")
|
||||
@JsonProperty("attributes")
|
||||
public List<Attribute> getList() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
public void setList(List<Attribute> attributes) {
|
||||
this.attributes = attributes;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import io.swagger.annotations.ApiModelProperty;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.wso2.carbon.analytics.datasource.commons.Record;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.BasePaginatedResult;
|
||||
|
||||
/**
|
||||
* This hold stats data record
|
||||
*/
|
||||
public class EventRecords extends BasePaginatedResult {
|
||||
|
||||
private List<Record> records = new ArrayList<>();
|
||||
|
||||
@ApiModelProperty(value = "List of records returned")
|
||||
@JsonProperty("records")
|
||||
public List<Record> getRecord() {
|
||||
return records;
|
||||
}
|
||||
|
||||
public void setList(List<Record> records) {
|
||||
this.records = records;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("{\n");
|
||||
|
||||
sb.append(" count: ").append(getCount()).append(",\n");
|
||||
sb.append(" records: [").append(records).append("\n");
|
||||
sb.append("]}\n");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
|
||||
|
||||
/**
|
||||
* This hold the default transport types support by the server.
|
||||
*/
|
||||
public enum TransportType {
|
||||
HTTP, MQTT;
|
||||
}
|
||||
|
||||
@ -140,6 +140,93 @@ public interface ActivityInfoProviderService {
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince);
|
||||
|
||||
|
||||
@GET
|
||||
@Path("/{id}/{devicetype}/{deviceid}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Details of an Activity for a specific device",
|
||||
notes = "Retrieve the details of a specific activity/operation, such as the meta information of " +
|
||||
"an operation, including the responses from a given device",
|
||||
tags = "Activity Info Provider",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:get-activity")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the activity details.",
|
||||
response = Activity.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. \n Empty body because the client already has the latest version of " +
|
||||
"the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 401,
|
||||
message = "Unauthorized. \n Unauthorized request."),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No activity found with the given ID.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the activity data.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getActivityByDevice(
|
||||
@ApiParam(
|
||||
name = "id",
|
||||
value = "Activity id of the operation/activity.",
|
||||
required = true,
|
||||
defaultValue = "ACTIVITY_1")
|
||||
@PathParam("id")
|
||||
@Size(max = 45)
|
||||
String id,
|
||||
@ApiParam(
|
||||
name = "devicetype",
|
||||
value = "The device type name, such as ios, android, windows or fire-alarm.",
|
||||
required = true)
|
||||
@PathParam("devicetype")
|
||||
@Size(max = 45)
|
||||
String type,
|
||||
@ApiParam(
|
||||
name = "deviceid",
|
||||
value = "The device identifier of the device you want ot get details.",
|
||||
required = true)
|
||||
@PathParam("deviceid")
|
||||
@Size(max = 45)
|
||||
String deviceid,
|
||||
@ApiParam(
|
||||
name = "If-Modified-Since",
|
||||
value = "Checks if the requested variant was modified, since the specified date-time\n." +
|
||||
"Provide the value in the Java Date Format: EEE, d MMM yyyy HH:mm:ss Z\n." +
|
||||
"Example: Mon, 05 Jan 2014 15:10:00 +0200",
|
||||
required = false)
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince);
|
||||
|
||||
@GET
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
|
||||
@ -0,0 +1,608 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.api;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Extension;
|
||||
import io.swagger.annotations.ExtensionProperty;
|
||||
import io.swagger.annotations.Info;
|
||||
import io.swagger.annotations.ResponseHeader;
|
||||
import io.swagger.annotations.SwaggerDefinition;
|
||||
import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@SwaggerDefinition(
|
||||
info = @Info(
|
||||
version = "1.0.0",
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "DeviceAgent Service"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/device/agent"),
|
||||
})
|
||||
}
|
||||
),
|
||||
tags = {
|
||||
@Tag(name = "device_agent, device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Api(value = "Device Agent", description = "Device Agent Service")
|
||||
@Path("/device/agent")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Scopes(
|
||||
scopes = {
|
||||
@Scope(
|
||||
name = "Enroll Device",
|
||||
description = "Register a device",
|
||||
key = "perm:device:enroll",
|
||||
permissions = {"/device-mgt/devices/owning-device/add"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Modify Device",
|
||||
description = "Modify a device",
|
||||
key = "perm:device:modify",
|
||||
permissions = {"/device-mgt/devices/owning-device/modify"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Disenroll Device",
|
||||
description = "Disenroll a device",
|
||||
key = "perm:device:disenroll",
|
||||
permissions = {"/device-mgt/devices/owning-device/remove"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Publish Event",
|
||||
description = "publish device event",
|
||||
key = "perm:device:publish-event",
|
||||
permissions = {"/device-mgt/devices/owning-device/event"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Getting Device Operation Details",
|
||||
description = "Getting Device Operation Details",
|
||||
key = "perm:device:operations",
|
||||
permissions = {"/device-mgt/devices/owning-device/view"}
|
||||
)
|
||||
}
|
||||
)
|
||||
public interface DeviceAgentService {
|
||||
|
||||
@POST
|
||||
@Path("/enroll")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Create a device instance",
|
||||
notes = "Create a device Instance",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:enroll")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully created a device instance.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version" +
|
||||
" of the requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n A deviceType with the specified device type was not found.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving the device details.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response enrollDevice(@ApiParam(name = "device", value = "Device object with data.", required = true)
|
||||
@Valid Device device);
|
||||
|
||||
@DELETE
|
||||
@Path("/enroll/{type}/{id}")
|
||||
@ApiOperation(
|
||||
httpMethod = "DELETE",
|
||||
value = "Unregistering a Device",
|
||||
notes = "Use this REST API to unregister a device.",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:disenroll")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully disenrolled the device."),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n The specified resource does not exist."),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while dis-enrolling the device.")
|
||||
})
|
||||
Response disEnrollDevice(
|
||||
@ApiParam(name = "type", value = "The unique device identifier.") @PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The unique device identifier.") @PathParam("id") String id);
|
||||
|
||||
@PUT
|
||||
@Path("/enroll/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "PUT",
|
||||
value = "modify device",
|
||||
notes = "modify device",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:modify")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully updated device instance.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version" +
|
||||
" of the requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n A deviceType with the specified device type was not found.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving the device details.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response updateDevice(@ApiParam(name = "type", value = "The device type, such as ios, android or windows....etc", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId,
|
||||
@ApiParam(name = "device", value = "Device object with data.", required = true)
|
||||
@Valid Device updateDevice);
|
||||
|
||||
@POST
|
||||
@Path("/events/publish/{type}/{deviceId}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Publishing Events",
|
||||
notes = "Publish events received by the device client to the WSO2 Data Analytics Server (DAS) using this API.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully published the event",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests.")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 303,
|
||||
message = "See Other. \n The source can be retrieved from the URL specified in the location header.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Location",
|
||||
description = "The Source URL of the document.")}),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error."),
|
||||
@ApiResponse(
|
||||
code = 415,
|
||||
message = "Unsupported media type. \n The format of the requested entity was not supported."),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while publishing events.")
|
||||
})
|
||||
Response publishEvents(
|
||||
@ApiParam(
|
||||
name = "payloadData",
|
||||
value = "Information of the agent event to be published on DAS.")
|
||||
@Valid
|
||||
Map<String, Object> payloadData,
|
||||
@ApiParam(
|
||||
name = "type",
|
||||
value = "name of the device type")
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "deviceId of the device")
|
||||
@PathParam("deviceId") String deviceId);
|
||||
|
||||
@POST
|
||||
@Path("/events/publish/data/{type}/{deviceId}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Publishing Events data only",
|
||||
notes = "Publish events received by the device client to the WSO2 Data Analytics Server (DAS) using this API.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:publish-event")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully published the event",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests.")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 303,
|
||||
message = "See Other. \n The source can be retrieved from the URL specified in the location header.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Location",
|
||||
description = "The Source URL of the document.")}),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error."),
|
||||
@ApiResponse(
|
||||
code = 415,
|
||||
message = "Unsupported media type. \n The format of the requested entity was not supported."),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while publishing events.")
|
||||
})
|
||||
Response publishEvents(
|
||||
@ApiParam(
|
||||
name = "payloadData",
|
||||
value = "Information of the agent event to be published on DAS.")
|
||||
@Valid
|
||||
List<Object> payloadData,
|
||||
@ApiParam(
|
||||
name = "type",
|
||||
value = "name of the device type")
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "deviceId of the device")
|
||||
@PathParam("deviceId") String deviceId);
|
||||
|
||||
@GET
|
||||
@Path("/pending/operations/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Get pending operation of the given device",
|
||||
notes = "Returns the Operations.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully retrieved the operations.",
|
||||
response = OperationList.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource has been modified the last time.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest " +
|
||||
"version of the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No device is found under the provided type and id.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving information requested device.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getPendingOperations(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId);
|
||||
|
||||
@GET
|
||||
@Path("/next-pending/operation/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Get pending operation of the given device",
|
||||
notes = "Returns the Operation.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully retrieved the operation.",
|
||||
response = Operation.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource has been modified the last time.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest " +
|
||||
"version of the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No device is found under the provided type and id.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving information requested device.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getNextPendingOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId);
|
||||
|
||||
@PUT
|
||||
@Path("/operations/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "PUT",
|
||||
value = "Update Operation",
|
||||
notes = "Update the Operations.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully updated the operations.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource has been modified the last time.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest " +
|
||||
"version of the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No device is found under the provided type and id.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving information requested device.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response updateOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId,
|
||||
@ApiParam(name = "operation", value = "Operation object with data.", required = true)
|
||||
@Valid Operation operation);
|
||||
|
||||
@GET
|
||||
@Path("/status/operations/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Get pending operation of the given device",
|
||||
notes = "Returns the Operations.",
|
||||
tags = "Device Agent Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device:operations")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully retrieved the operations.",
|
||||
response = OperationList.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource has been modified the last time.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest " +
|
||||
"version of the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No device is found under the provided type and id.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving information requested device.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getOperationsByDeviceAndStatus(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId,
|
||||
@ApiParam(name = "status", value = "status of the operation.", required = true)
|
||||
@QueryParam("status")Operation.Status status);
|
||||
|
||||
}
|
||||
@ -0,0 +1,347 @@
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.api;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Extension;
|
||||
import io.swagger.annotations.ExtensionProperty;
|
||||
import io.swagger.annotations.Info;
|
||||
import io.swagger.annotations.ResponseHeader;
|
||||
import io.swagger.annotations.SwaggerDefinition;
|
||||
import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
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.EventRecords;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.TransportType;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@SwaggerDefinition(
|
||||
info = @Info(
|
||||
version = "1.0.0",
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "DeviceEventManagement"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/events"),
|
||||
})
|
||||
}
|
||||
),
|
||||
tags = {
|
||||
@Tag(name = "device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Scopes(
|
||||
scopes = {
|
||||
@Scope(
|
||||
name = "Add or Delete Event Definition for device type",
|
||||
description = "Add or Delete Event Definition for device type",
|
||||
key = "perm:device-types:events",
|
||||
permissions = {"/device-mgt/device-type/add"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Get Events Details of a Device Type",
|
||||
description = "Get Events Details of a Device Type",
|
||||
key = "perm:device-types:events:view",
|
||||
permissions = {"/device-mgt/devices/owning-device/view"}
|
||||
)
|
||||
}
|
||||
)
|
||||
@Path("/events")
|
||||
@Api(value = "Device Event Management", description = "This API corresponds to all tasks related to device " +
|
||||
"event management")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public interface DeviceEventManagementService {
|
||||
|
||||
@POST
|
||||
@Path("/{type}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Add Event Type Defnition",
|
||||
notes = "Add the event definition for the device.",
|
||||
tags = "Device Event Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully added the event defintion.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@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"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response deployDeviceTypeEventDefinition(@ApiParam(name = "type", value = "name of the device type", required = false)
|
||||
@PathParam("type")String deviceType,
|
||||
@ApiParam(name = "deviceTypeEvent", value = "DeviceTypeEvent object with data.", required = true)
|
||||
@Valid DeviceTypeEvent deviceTypeEvent);
|
||||
|
||||
@DELETE
|
||||
@Path("/{type}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "DELETE",
|
||||
value = "Delete Event Type Defnition",
|
||||
notes = "Delete the event definition for the device.",
|
||||
tags = "Device Event Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully deleted the event definition.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@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"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response deleteDeviceTypeEventDefinitions(@ApiParam(name = "type", value = "name of the device type", required = false)
|
||||
@PathParam("type")String deviceType);
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{deviceId}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Device Events",
|
||||
notes = "Get the events for the device.",
|
||||
tags = "Device Event Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the event definition.",
|
||||
response = EventRecords.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@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"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response getData(@ApiParam(name = "deviceId", value = "id of the device ", required = false)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(name = "from", value = "unix timestamp to retrieve", required = false)
|
||||
@QueryParam("from") long from,
|
||||
@ApiParam(name = "to", value = "unix time to retrieve", required = false)
|
||||
@QueryParam("to") long to,
|
||||
@ApiParam(name = "type", value = "name of the device type", required = false)
|
||||
@PathParam("type") String deviceType,
|
||||
@ApiParam(name = "offset", value = "offset of the records that needs to be picked up", required = false)
|
||||
@QueryParam("offset") int offset,
|
||||
@ApiParam(name = "limit", value = "limit of the records that needs to be picked up", required = false)
|
||||
@QueryParam("limit") int limit);
|
||||
|
||||
@GET
|
||||
@Path("last-known/{type}/{deviceId}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Last Known Device Events",
|
||||
notes = "Get the Last Known events for the device.",
|
||||
tags = "Device Event Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the event.",
|
||||
response = EventRecords.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@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"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response getLastKnownData(@ApiParam(name = "deviceId", value = "id of the device ", required = false)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(name = "type", value = "name of the device type", required = false)
|
||||
@PathParam("type") String deviceType);
|
||||
|
||||
@GET
|
||||
@Path("/{type}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Event Type Defnition",
|
||||
notes = "Get the event definition for the device.",
|
||||
tags = "Device Event Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:events:view")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the event defintion.",
|
||||
response = DeviceTypeEvent.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@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"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response getDeviceTypeEventDefinition(@ApiParam(name = "type", value = "name of the device type", required = false)
|
||||
@PathParam("type")String deviceType) ;
|
||||
|
||||
}
|
||||
@ -32,17 +32,22 @@ import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
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.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.NonComplianceData;
|
||||
import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
@ -56,6 +61,7 @@ import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Device related REST-API. This can be used to manipulated device related details.
|
||||
@ -221,6 +227,12 @@ public interface DeviceManagementService {
|
||||
required = false)
|
||||
@QueryParam("user")
|
||||
String user,
|
||||
@ApiParam(
|
||||
name = "userPattern",
|
||||
value = "The pattern of username of the owner of the device.",
|
||||
required = false)
|
||||
@QueryParam("userPattern")
|
||||
String userPattern,
|
||||
@ApiParam(
|
||||
name = "role",
|
||||
value = "A role of device owners. Ex : store-admin",
|
||||
@ -267,6 +279,13 @@ public interface DeviceManagementService {
|
||||
required = false)
|
||||
@HeaderParam("If-Modified-Since")
|
||||
String timestamp,
|
||||
@ApiParam(
|
||||
name = "requireDeviceInfo",
|
||||
value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" +
|
||||
" to the device object.",
|
||||
required = false)
|
||||
@QueryParam("requireDeviceInfo")
|
||||
boolean requireDeviceInfo,
|
||||
@ApiParam(
|
||||
name = "offset",
|
||||
value = "The starting pagination index for the complete list of qualified items.",
|
||||
@ -333,6 +352,13 @@ public interface DeviceManagementService {
|
||||
})
|
||||
@Path("/user-devices")
|
||||
Response getDeviceByUser(
|
||||
@ApiParam(
|
||||
name = "requireDeviceInfo",
|
||||
value = "Boolean flag indicating whether to include device-info (location, application list etc) \n" +
|
||||
" to the device object.",
|
||||
required = false)
|
||||
@QueryParam("requireDeviceInfo")
|
||||
boolean requireDeviceInfo,
|
||||
@ApiParam(
|
||||
name = "offset",
|
||||
value = "The starting pagination index for the complete list of qualified items.",
|
||||
@ -423,6 +449,60 @@ public interface DeviceManagementService {
|
||||
@HeaderParam("If-Modified-Since")
|
||||
String ifModifiedSince);
|
||||
|
||||
@PUT
|
||||
@Path("/{type}/{id}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Get device enrollment status",
|
||||
notes = "Get device enrollment status",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully created a device instance.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version" +
|
||||
" of the requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n A deviceType with the specified device type was not found.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving the device details.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response isEnrolled(@ApiParam(name = "type", value = "The device type, such as ios, android or windows.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "id", value = "The device id.", required = true)
|
||||
@PathParam("id") String deviceId);
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{id}/location")
|
||||
@ -1233,4 +1313,62 @@ public interface DeviceManagementService {
|
||||
@QueryParam("newStatus")
|
||||
EnrolmentInfo.Status newStatus);
|
||||
|
||||
@POST
|
||||
@Path("/{type}/operations")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Add operation to set of devices for a given device type",
|
||||
notes = "Returns the Activity Related to the operation.",
|
||||
tags = "Device Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:operations")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 201,
|
||||
message = "OK. \n Successfully added the operation.",
|
||||
response = Activity.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description = "Date and time the resource has been modified the last time.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest " +
|
||||
"version of the requested resource."),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n No device is found under the provided type and id.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n " +
|
||||
"Server error occurred while retrieving information requested device.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response addOperation(@ApiParam(name = "type", value = "The device type, such as ios, android or windows... etc.", required = true)
|
||||
@PathParam("type") String type,
|
||||
@ApiParam(name = "deviceOperation", value = "Operation object with device ids.", required = true)
|
||||
@Valid OperationRequest operationRequest);
|
||||
|
||||
|
||||
}
|
||||
|
||||
@ -31,6 +31,7 @@ import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.ResponseHeader;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
@ -206,4 +207,103 @@ public interface DeviceTypeManagementService {
|
||||
@HeaderParam("If-Modified-Since")
|
||||
String ifModifiedSince);
|
||||
|
||||
@GET
|
||||
@Path("/all/{type}")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting Details of a Device Type",
|
||||
notes = "Get the details of a device by searching via the device type and the tenant domain.",
|
||||
response = DeviceType.class,
|
||||
tags = "Device Type Management Administrative Service",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the device type.",
|
||||
response = DeviceType.class,
|
||||
responseContainer = "List",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version of the " +
|
||||
"requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 401,
|
||||
message = "Unauthorized.\n The unauthorized access to the requested resource.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found.\n The specified device does not exist",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getDeviceTypeByName(
|
||||
@ApiParam(
|
||||
name = "type",
|
||||
value = "The device type name, such as ios, android, windows or fire-alarm.",
|
||||
required = true)
|
||||
@PathParam("type")
|
||||
@Size(min = 2, max = 45)
|
||||
String type);
|
||||
|
||||
@GET
|
||||
@Path("/all")
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Retrieve device types information",
|
||||
notes = "Retrieve device types information.",
|
||||
response = DeviceType.class,
|
||||
tags = "Device Type Management Administrative Service",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:device-types:types")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully fetched the device type.",
|
||||
response = DeviceType.class,
|
||||
responseContainer = "List",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version of the " +
|
||||
"requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 401,
|
||||
message = "Unauthorized.\n The unauthorized access to the requested resource.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found.\n The specified device does not exist",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response getDeviceTypes();
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,478 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.api;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Extension;
|
||||
import io.swagger.annotations.ExtensionProperty;
|
||||
import io.swagger.annotations.Info;
|
||||
import io.swagger.annotations.ResponseHeader;
|
||||
import io.swagger.annotations.SwaggerDefinition;
|
||||
import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@SwaggerDefinition(
|
||||
info = @Info(
|
||||
version = "1.0.0",
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "geo_services"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/geo-services"),
|
||||
})
|
||||
}
|
||||
),
|
||||
tags = {
|
||||
@Tag(name = "device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Scopes(
|
||||
scopes = {
|
||||
@Scope(
|
||||
name = "View Analytics",
|
||||
description = "",
|
||||
key = "perm:geo-service:analytics-view",
|
||||
permissions = {"/device-mgt/devices/owning-device/view-analytics"}
|
||||
),
|
||||
@Scope(
|
||||
name = "Manage Alerts",
|
||||
description = "",
|
||||
key = "perm:geo-service:alerts-manage",
|
||||
permissions = {"/device-mgt/devices/owning-device/manage-alerts"}
|
||||
)
|
||||
}
|
||||
)
|
||||
@Path("/geo-services")
|
||||
@Api(value = "Geo Service",
|
||||
description = "This carries all the resources related to the geo service functionalities.")
|
||||
public interface GeoLocationBasedService {
|
||||
/**
|
||||
* Retrieve Analytics for the device type
|
||||
*/
|
||||
@GET
|
||||
@Path("stats/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "GET",
|
||||
value = "Retrieve Analytics for the device type",
|
||||
notes = "",
|
||||
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 Device Identifiers 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 getGeoDeviceStats(
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "device-type",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType")
|
||||
@Size(max = 45)
|
||||
String deviceType,
|
||||
@ApiParam(
|
||||
name = "from",
|
||||
value = "Get stats from what time",
|
||||
required = true)
|
||||
@QueryParam("from") long from,
|
||||
@ApiParam(
|
||||
name = "to",
|
||||
value = "Get stats up to what time",
|
||||
required = true)
|
||||
@QueryParam("to") long to);
|
||||
|
||||
/**
|
||||
* Create Geo alerts
|
||||
*/
|
||||
@POST
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "GET",
|
||||
value = "Create Geo alerts for the device",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "Geo Service Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK.",
|
||||
response = Response.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid Device Identifiers 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 createGeoAlerts(
|
||||
@ApiParam(
|
||||
name = "alert",
|
||||
value = "The alert object",
|
||||
required = true)
|
||||
@Valid Alert alert,
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "device-type",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType")
|
||||
@Size(max = 45)
|
||||
String deviceType,
|
||||
@ApiParam(
|
||||
name = "alertType",
|
||||
value = "The alert type, such as Within, Speed, Stationary",
|
||||
required = true)
|
||||
@PathParam("alertType") String alertType);
|
||||
|
||||
/**
|
||||
* Update Geo alerts
|
||||
*/
|
||||
@PUT
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "GET",
|
||||
value = "Update Geo alerts for the device",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "Geo Service Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK.",
|
||||
response = Response.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid Device Identifiers 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 updateGeoAlerts(
|
||||
@ApiParam(
|
||||
name = "alert",
|
||||
value = "The alert object",
|
||||
required = true)
|
||||
@Valid Alert alert,
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "device-type",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType")
|
||||
@Size(max = 45)
|
||||
String deviceType,
|
||||
@ApiParam(
|
||||
name = "alertType",
|
||||
value = "The alert type, such as Within, Speed, Stationary",
|
||||
required = true)
|
||||
@PathParam("alertType") String alertType);
|
||||
|
||||
/**
|
||||
* Retrieve Geo alerts
|
||||
*/
|
||||
@GET
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "GET",
|
||||
value = "Retrieve Geo alerts for the device",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "Geo Service Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
|
||||
})
|
||||
}
|
||||
)
|
||||
@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 Device Identifiers 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 getGeoAlerts(
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "device-type",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType")
|
||||
@Size(max = 45)
|
||||
String deviceType,
|
||||
@ApiParam(
|
||||
name = "alertType",
|
||||
value = "The alert type, such as Within, Speed, Stationary",
|
||||
required = true)
|
||||
@PathParam("alertType") String alertType);
|
||||
|
||||
/**
|
||||
* Retrieve Geo alerts history
|
||||
*/
|
||||
@GET
|
||||
@Path("alerts/history/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "GET",
|
||||
value = "Retrieve Geo alerts history for the device",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "Geo Service Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
|
||||
})
|
||||
}
|
||||
)
|
||||
@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 Device Identifiers 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 getGeoAlertsHistory(
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "device-type",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType")
|
||||
@Size(max = 45)
|
||||
String deviceType,
|
||||
@ApiParam(
|
||||
name = "from",
|
||||
value = "Get stats from what time",
|
||||
required = true)
|
||||
@QueryParam("from") long from,
|
||||
@ApiParam(
|
||||
name = "to",
|
||||
value = "Get stats up to what time",
|
||||
required = true)
|
||||
@QueryParam("to") long to);
|
||||
|
||||
@DELETE
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@ApiOperation(
|
||||
consumes = "application/json",
|
||||
produces = "application/json",
|
||||
httpMethod = "DELETE",
|
||||
value = "Deletes Geo alerts for the device",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "Geo Service Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:geo-service:alerts-manage")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK.",
|
||||
response = Response.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid Device Identifiers 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 removeGeoAlerts(
|
||||
@ApiParam(
|
||||
name = "deviceId",
|
||||
value = "The registered device Id.",
|
||||
required = true)
|
||||
@PathParam("deviceId") String deviceId,
|
||||
@ApiParam(
|
||||
name = "deviceType",
|
||||
value = "The device type, such as ios, android or windows.",
|
||||
required = true)
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@ApiParam(
|
||||
name = "alertType",
|
||||
value = "The alert type, such as Within, Speed, Stationary",
|
||||
required = true)
|
||||
@PathParam("alertType") String alertType,
|
||||
@ApiParam(
|
||||
name = "queryName",
|
||||
value = "The query name.",
|
||||
required = true)
|
||||
@QueryParam("queryName") String queryName);
|
||||
}
|
||||
|
||||
@ -115,4 +115,43 @@ public interface DeviceAccessAuthorizationAdminService {
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response isAuthorized(AuthorizationRequest authorizationRequest);
|
||||
|
||||
@POST
|
||||
@Path("/stat")
|
||||
@ApiOperation(
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Check for device access authorization for stat\n",
|
||||
notes = "This is an internal API that can be used to check for authorization.",
|
||||
response = DeviceAuthorizationResult.class,
|
||||
tags = "Authorization Administrative Service",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:authorization:verify")
|
||||
})
|
||||
})
|
||||
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Authorized device list will be delivered to the requested services",
|
||||
response = DeviceAuthorizationResult.class),
|
||||
@ApiResponse(
|
||||
code = 400,
|
||||
message = "Bad Request. \n Invalid request or validation error.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found. \n The specified resource does not exist."),
|
||||
@ApiResponse(
|
||||
code = 415,
|
||||
message = "Unsupported media type. \n The entity of the request was in a not supported format."),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while checking the authorization" +
|
||||
" for a specified set of devices.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response isAuthorizedForStat(AuthorizationRequest authorizationRequest);
|
||||
}
|
||||
|
||||
@ -38,8 +38,8 @@ import javax.ws.rs.core.Response;
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "DeviceTypePublisherAdminService"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/devicetype"),
|
||||
@ExtensionProperty(name = "name", value = "DeviceAnalyticsArtifactUploaderAdminService"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/publish-artifact"),
|
||||
})
|
||||
}
|
||||
),
|
||||
@ -47,7 +47,7 @@ import javax.ws.rs.core.Response;
|
||||
@Tag(name = "device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Path("/admin/devicetype")
|
||||
@Path("/admin/publish-artifact")
|
||||
@Api(value = "Devicetype deployment Administrative Service", description = "This an API intended to be used to " +
|
||||
"deploy device type components" +
|
||||
"Further, this is strictly restricted to admin users only ")
|
||||
@ -62,7 +62,7 @@ import javax.ws.rs.core.Response;
|
||||
}
|
||||
)
|
||||
|
||||
public interface DeviceTypePublisherAdminService {
|
||||
public interface DeviceAnalyticsArtifactUploaderAdminService {
|
||||
|
||||
@POST
|
||||
@Path("/deploy/{type}")
|
||||
@ -0,0 +1,227 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.api.admin;
|
||||
|
||||
import io.swagger.annotations.Api;
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import io.swagger.annotations.ApiResponse;
|
||||
import io.swagger.annotations.ApiResponses;
|
||||
import io.swagger.annotations.Extension;
|
||||
import io.swagger.annotations.ExtensionProperty;
|
||||
import io.swagger.annotations.Info;
|
||||
import io.swagger.annotations.ResponseHeader;
|
||||
import io.swagger.annotations.SwaggerDefinition;
|
||||
import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
@SwaggerDefinition(
|
||||
info = @Info(
|
||||
version = "1.0.0",
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "DeviceTypeManagementAdminService"),
|
||||
@ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/admin/device-types"),
|
||||
})
|
||||
}
|
||||
),
|
||||
tags = {
|
||||
@Tag(name = "device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Path("/admin/device-types")
|
||||
@Api(value = "Device Type Management Administrative Service", description = "This an API intended to be used by " +
|
||||
"'internal' components to log in as an admin user and do a selected number of operations. " +
|
||||
"Further, this is strictly restricted to admin users only ")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
@Scopes(
|
||||
scopes = {
|
||||
@Scope(
|
||||
name = "Getting Details of a Device",
|
||||
description = "Getting Details of a Device",
|
||||
key = "perm:admin:device-type",
|
||||
permissions = {"/device-mgt/admin/device-type"}
|
||||
)
|
||||
}
|
||||
)
|
||||
public interface DeviceTypeManagementAdminService {
|
||||
|
||||
@GET
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Getting the Supported Device Type with Meta Definition",
|
||||
notes = "Get the list of device types supported by WSO2 IoT.",
|
||||
tags = "Device Type Management",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(
|
||||
value = {
|
||||
@ApiResponse(
|
||||
code = 200,
|
||||
message = "OK. \n Successfully fetched the list of supported device types.",
|
||||
response = DeviceTypeList.class,
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body"),
|
||||
@ResponseHeader(
|
||||
name = "ETag",
|
||||
description = "Entity Tag of the response resource.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
@ResponseHeader(
|
||||
name = "Last-Modified",
|
||||
description =
|
||||
"Date and time the resource was last modified.\n" +
|
||||
"Used by caches, or in conditional requests."),
|
||||
}
|
||||
),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message =
|
||||
"Not Modified. \n Empty body because the client already has the latest version " +
|
||||
"of the requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the " +
|
||||
"list of supported device types.",
|
||||
response = ErrorResponse.class)
|
||||
}
|
||||
)
|
||||
Response getDeviceTypes();
|
||||
|
||||
@POST
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Add a Device Type",
|
||||
notes = "Add the details of a device type.",
|
||||
tags = "Device Type Management Administrative Service",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully added the device type.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version of the " +
|
||||
"requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 401,
|
||||
message = "Unauthorized.\n The unauthorized access to the requested resource.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found.\n The specified device does not exist",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response addDeviceType(@ApiParam(
|
||||
name = "type",
|
||||
value = "The device type such as ios, android, windows or fire-alarm.",
|
||||
required = true)DeviceType deviceType);
|
||||
|
||||
@PUT
|
||||
@ApiOperation(
|
||||
produces = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "PUT",
|
||||
value = "Update Device Type",
|
||||
notes = "Update the details of a device type.",
|
||||
response = DeviceType.class,
|
||||
tags = "Device Type Management Administrative Service",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:device-type")
|
||||
})
|
||||
}
|
||||
)
|
||||
@ApiResponses(value = {
|
||||
@ApiResponse(code = 200, message = "OK. \n Successfully updated the device type.",
|
||||
responseHeaders = {
|
||||
@ResponseHeader(
|
||||
name = "Content-Type",
|
||||
description = "The content type of the body")
|
||||
}),
|
||||
@ApiResponse(
|
||||
code = 304,
|
||||
message = "Not Modified. Empty body because the client already has the latest version of the " +
|
||||
"requested resource.\n"),
|
||||
@ApiResponse(
|
||||
code = 401,
|
||||
message = "Unauthorized.\n The unauthorized access to the requested resource.",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 404,
|
||||
message = "Not Found.\n The specified device does not exist",
|
||||
response = ErrorResponse.class),
|
||||
@ApiResponse(
|
||||
code = 406,
|
||||
message = "Not Acceptable.\n The requested media type is not supported"),
|
||||
@ApiResponse(
|
||||
code = 500,
|
||||
message = "Internal Server Error. \n Server error occurred while fetching the device list.",
|
||||
response = ErrorResponse.class)
|
||||
})
|
||||
Response updateDeviceType(@ApiParam(
|
||||
name = "type",
|
||||
value = "The device type such as ios, android, windows or fire-alarm.",
|
||||
required = true) DeviceType deviceType);
|
||||
|
||||
}
|
||||
@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.jaxrs.service.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
@ -72,6 +73,43 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@GET
|
||||
@Override
|
||||
@Path("/{id}/{devicetype}/{deviceid}")
|
||||
public Response getActivityByDevice(@PathParam("id")
|
||||
@Size(max = 45) String id,
|
||||
@PathParam("devicetype")
|
||||
@Size(max = 45) String devicetype,
|
||||
@PathParam("deviceid")
|
||||
@Size(max = 45) String deviceid,
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
|
||||
Activity activity;
|
||||
DeviceManagementProviderService dmService;
|
||||
try {
|
||||
RequestValidationUtil.validateActivityId(id);
|
||||
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceid);
|
||||
deviceIdentifier.setType(devicetype);
|
||||
|
||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
activity = dmService.getOperationByActivityIdAndDevice(id, deviceIdentifier);
|
||||
if (activity == null) {
|
||||
return Response.status(404).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage("No activity can be " +
|
||||
"found upon the provided activity id '" + id + "'").build()).build();
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity(activity).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String msg = "ErrorResponse occurred while fetching the activity for the supplied id.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@GET
|
||||
@Override
|
||||
public Response getActivities(@QueryParam("since") String since, @QueryParam("offset") int offset,
|
||||
@ -83,6 +121,10 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
long timestamp = 0;
|
||||
boolean isIfModifiedSinceSet = false;
|
||||
boolean isSinceSet = false;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("getActivities since: " + since + " , offset: " + offset + " ,limit: " + limit + " ," +
|
||||
"ifModifiedSince: " + ifModifiedSince);
|
||||
}
|
||||
RequestValidationUtil.validatePaginationParameters(offset, limit);
|
||||
if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
|
||||
Date ifSinceDate;
|
||||
@ -112,14 +154,32 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
|
||||
timestamp = sinceTimestamp / 1000;
|
||||
}
|
||||
|
||||
if (timestamp == 0) {
|
||||
//If timestamp is not sent by the user, a default value is set, that is equal to current time-12 hours.
|
||||
long time = System.currentTimeMillis() / 1000;
|
||||
timestamp = time - 42300;
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("getActivities final timestamp " + timestamp);
|
||||
}
|
||||
|
||||
List<Activity> activities;
|
||||
ActivityList activityList = new ActivityList();
|
||||
DeviceManagementProviderService dmService;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Calling database to get activities.");
|
||||
}
|
||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
activities = dmService.getActivitiesUpdatedAfter(timestamp, limit, offset);
|
||||
activityList.setList(activities);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Calling database to get activity count.");
|
||||
}
|
||||
int count = dmService.getActivityCountUpdatedAfter(timestamp);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Activity count: " + count);
|
||||
}
|
||||
activityList.setCount(count);
|
||||
if (activities == null || activities.size() == 0) {
|
||||
if (isIfModifiedSinceSet) {
|
||||
|
||||
@ -0,0 +1,574 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.apache.axis2.AxisFault;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
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.policy.mgt.monitor.ComplianceFeature;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.monitor.PolicyComplianceException;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
|
||||
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.EventAttributeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceAgentService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Path("/device/agent")
|
||||
public class DeviceAgentServiceImpl implements DeviceAgentService {
|
||||
private static final Log log = LogFactory.getLog(DeviceAgentServiceImpl.class);
|
||||
private static final String POLICY_MONITOR = "POLICY_MONITOR";
|
||||
@POST
|
||||
@Path("/enroll")
|
||||
@Override
|
||||
public Response enrollDevice(@Valid Device device) {
|
||||
if (device == null) {
|
||||
String errorMessage = "The payload of the device enrollment is incorrect.";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
try {
|
||||
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
if (device.getType() == null || device.getDeviceIdentifier() == null) {
|
||||
String errorMessage = "The payload of the device enrollment is incorrect.";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getDeviceIdentifier(), device.getType()));
|
||||
if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice
|
||||
.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
|
||||
String errorMessage = "An active enrolment exists";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser());
|
||||
device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis());
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());
|
||||
boolean status = dms.enrollDevice(device);
|
||||
return Response.status(Response.Status.OK).entity(status).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling the device, which carries the id '" +
|
||||
device.getDeviceIdentifier() + "'";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (InvalidConfigurationException e) {
|
||||
log.error("failed to add operation", e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/enroll/{type}/{id}")
|
||||
@Override
|
||||
public Response disEnrollDevice(@PathParam("type") String type, @PathParam("id") String id) {
|
||||
boolean result;
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type);
|
||||
try {
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().disenrollDevice(deviceIdentifier);
|
||||
if (result) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NO_CONTENT).entity(type + " device that carries id '" + id +
|
||||
"' has not been dis-enrolled").build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while enrolling the device, which carries the id '" + id + "'";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/enroll/{type}/{id}")
|
||||
@Override
|
||||
public Response updateDevice(@PathParam("type") String type, @PathParam("id") String id, @Valid Device updateDevice) {
|
||||
Device device;
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(id);
|
||||
deviceIdentifier.setType(type);
|
||||
try {
|
||||
device = DeviceMgtAPIUtils.getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while getting enrollment details of the device that carries the id '" +
|
||||
id + "'";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
|
||||
if (updateDevice == null) {
|
||||
String errorMessage = "The payload of the device enrollment is incorrect.";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
if (device == null) {
|
||||
String errorMessage = "The device to be modified doesn't exist.";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.NOT_FOUND).entity(errorMessage).build();
|
||||
}
|
||||
if (device.getEnrolmentInfo().getStatus() == EnrolmentInfo.Status.ACTIVE ) {
|
||||
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
|
||||
DeviceMgtAPIUtils.getDeviceAccessAuthorizationService();
|
||||
boolean status;
|
||||
try {
|
||||
status = deviceAccessAuthorizationService.isUserAuthorized(new DeviceIdentifier(id, type));
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" +
|
||||
id + "'";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
if (!status) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).build();
|
||||
}
|
||||
}
|
||||
if(updateDevice.getEnrolmentInfo() != null) {
|
||||
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());
|
||||
device.setEnrolmentInfo(device.getEnrolmentInfo());
|
||||
}
|
||||
device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser());
|
||||
if(updateDevice.getDeviceInfo() != null) {
|
||||
device.setDeviceInfo(updateDevice.getDeviceInfo());
|
||||
}
|
||||
device.setDeviceIdentifier(id);
|
||||
if(updateDevice.getDescription() != null) {
|
||||
device.setDescription(updateDevice.getDescription());
|
||||
}
|
||||
if(updateDevice.getName() != null) {
|
||||
device.setName(updateDevice.getName());
|
||||
}
|
||||
if(updateDevice.getFeatures() != null) {
|
||||
device.setFeatures(updateDevice.getFeatures());
|
||||
}
|
||||
if(updateDevice.getProperties() != null) {
|
||||
device.setProperties(updateDevice.getProperties());
|
||||
}
|
||||
boolean result;
|
||||
try {
|
||||
device.setType(type);
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().modifyEnrollment(device);
|
||||
if (result) {
|
||||
return Response.status(Response.Status.ACCEPTED).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while modifying enrollment of the Android device that carries the id '" +
|
||||
id + "'";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/events/publish/{type}/{deviceId}")
|
||||
@Override
|
||||
public Response publishEvents(@Valid Map<String, Object> payload, @PathParam("type") String type
|
||||
, @PathParam("deviceId") String deviceId) {
|
||||
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
|
||||
try {
|
||||
if (payload == null) {
|
||||
String msg = "invalid payload structure";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
} else {
|
||||
boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized
|
||||
(new DeviceIdentifier(type, deviceId));
|
||||
if (!authorized) {
|
||||
String msg = "Does not have permission to access the device.";
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
|
||||
}
|
||||
}
|
||||
Object metaData[] = new Object[1];
|
||||
metaData[0] = deviceId;
|
||||
EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type);
|
||||
if (eventAttributeList == null) {
|
||||
String streamName = DeviceMgtAPIUtils.getStreamDefinition(type, tenantDomain);
|
||||
eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto(
|
||||
streamName + ":" + Constants.DEFAULT_STREAM_VERSION);
|
||||
if (eventStreamDefinitionDto == null) {
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
} else {
|
||||
EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData();
|
||||
List<Attribute> attributes = new ArrayList<>();
|
||||
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
|
||||
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
|
||||
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
|
||||
|
||||
}
|
||||
if (payload.size() != attributes.size()) {
|
||||
String msg = "Payload does not match with the stream definition";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
}
|
||||
eventAttributeList = new EventAttributeList();
|
||||
eventAttributeList.setList(attributes);
|
||||
DeviceMgtAPIUtils.getDynamicEventCache().put(type, eventAttributeList);
|
||||
}
|
||||
}
|
||||
int i = 0;
|
||||
Object[] payloadData = new Object[eventAttributeList.getList().size()];
|
||||
for (Attribute attribute : eventAttributeList.getList()) {
|
||||
if (attribute.getType() == AttributeType.INT) {
|
||||
payloadData[i] = ((Double) payload.get(attribute.getName())).intValue();
|
||||
} else if (attribute.getType() == AttributeType.LONG) {
|
||||
payloadData[i] = ((Double) payload.get(attribute.getName())).longValue();
|
||||
} else {
|
||||
payloadData[i] = payload.get(attribute.getName());
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type
|
||||
, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
|
||||
, Constants.DEFAULT_STREAM_VERSION, metaData
|
||||
, null, payloadData)) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
String msg = "Error occurred while publishing the event.";
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
} catch (DataPublisherConfigurationException e) {
|
||||
String msg = "Error occurred while publishing the event.";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
String msg = "Error occurred when checking for authorization";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (AxisFault e) {
|
||||
log.error("Failed to retrieve event definitions for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to connect with the remote services:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JWTClientException e) {
|
||||
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} finally {
|
||||
if (eventStreamAdminServiceStub != null) {
|
||||
try {
|
||||
eventStreamAdminServiceStub.cleanup();
|
||||
} catch (AxisFault axisFault) {
|
||||
log.warn("Failed to clean eventStreamAdminServiceStub");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/events/publish/data/{type}/{deviceId}")
|
||||
@Override
|
||||
public Response publishEvents(@Valid List<Object> payload, @PathParam("type") String type
|
||||
, @PathParam("deviceId") String deviceId) {
|
||||
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
|
||||
try {
|
||||
if (payload == null) {
|
||||
String msg = "Invalid payload structure";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
} else {
|
||||
boolean authorized = DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized
|
||||
(new DeviceIdentifier(type, deviceId));
|
||||
if (!authorized) {
|
||||
String msg = "Does not have permission to access the device.";
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
|
||||
}
|
||||
}
|
||||
Object metaData[] = new Object[1];
|
||||
metaData[0] = deviceId;
|
||||
EventAttributeList eventAttributeList = DeviceMgtAPIUtils.getDynamicEventCache().get(type);
|
||||
if (eventAttributeList == null) {
|
||||
String streamName = DeviceMgtAPIUtils.getStreamDefinition(type, tenantDomain);
|
||||
eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto(
|
||||
streamName + ":" + Constants.DEFAULT_STREAM_VERSION);
|
||||
if (eventStreamDefinitionDto == null) {
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
} else {
|
||||
EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData();
|
||||
List<Attribute> attributes = new ArrayList<>();
|
||||
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
|
||||
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
|
||||
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
|
||||
|
||||
}
|
||||
if (payload.size() != attributes.size()) {
|
||||
String msg = "Payload does not match with the stream definition";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
}
|
||||
eventAttributeList = new EventAttributeList();
|
||||
eventAttributeList.setList(attributes);
|
||||
DeviceMgtAPIUtils.getDynamicEventCache().put(type, eventAttributeList);
|
||||
}
|
||||
}
|
||||
int i = 0;
|
||||
Object[] payloadData = new Object[eventAttributeList.getList().size()];
|
||||
for (Attribute attribute : eventAttributeList.getList()) {
|
||||
if (attribute.getType() == AttributeType.INT) {
|
||||
payloadData[i] = ((Double) payload.get(i)).intValue();
|
||||
} else if (attribute.getType() == AttributeType.LONG) {
|
||||
payloadData[i] = ((Double) payload.get(i)).longValue();
|
||||
} else {
|
||||
payloadData[i] = payload.get(i);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
if (DeviceMgtAPIUtils.getEventPublisherService().publishEvent(DeviceMgtAPIUtils.getStreamDefinition(type
|
||||
, PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain())
|
||||
, Constants.DEFAULT_STREAM_VERSION, metaData
|
||||
, null, payloadData)) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
String msg = "Error occurred while publishing the event.";
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
} catch (DataPublisherConfigurationException e) {
|
||||
String msg = "Error occurred while publishing the event.";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
String msg = "Error occurred when checking for authorization";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (AxisFault e) {
|
||||
log.error("Failed to retrieve event definitions for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to connect with the remote services:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JWTClientException e) {
|
||||
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} finally {
|
||||
if (eventStreamAdminServiceStub != null) {
|
||||
try {
|
||||
eventStreamAdminServiceStub.cleanup();
|
||||
} catch (AxisFault axisFault) {
|
||||
log.warn("Failed to clean eventStreamAdminServiceStub");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/pending/operations/{type}/{id}")
|
||||
public Response getPendingOperations(@PathParam("type") String type, @PathParam("id") String deviceId) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
|
||||
String errorMessage = "Device identifier list is empty";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type);
|
||||
if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) {
|
||||
String msg = "Device not found for identifier '" + deviceId + "'";
|
||||
log.error(msg);
|
||||
return Response.status(Response.Status.NO_CONTENT).entity(msg).build();
|
||||
}
|
||||
List<? extends Operation> operations = DeviceMgtAPIUtils.getDeviceManagementService().getPendingOperations(
|
||||
deviceIdentifier);
|
||||
OperationList operationsList = new OperationList();
|
||||
operationsList.setList(operations);
|
||||
operationsList.setCount(operations.size());
|
||||
return Response.status(Response.Status.OK).entity(operationsList).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String errorMessage = "Issue in retrieving operation management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMessage = "Issue in retrieving deivce management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/next-pending/operation/{type}/{id}")
|
||||
public Response getNextPendingOperation(@PathParam("type") String type, @PathParam("id") String deviceId) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
|
||||
String errorMessage = "Device type is invalid";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type);
|
||||
if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) {
|
||||
String msg = "Device not found for identifier '" + deviceId + "'";
|
||||
log.error(msg);
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
}
|
||||
Operation operation = DeviceMgtAPIUtils.getDeviceManagementService().getNextPendingOperation(
|
||||
deviceIdentifier);
|
||||
return Response.status(Response.Status.OK).entity(operation).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String errorMessage = "Issue in retrieving operation management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMessage = "Issue in retrieving deivce management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
}
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/operations/{type}/{id}")
|
||||
public Response updateOperation(@PathParam("type") String type, @PathParam("id") String deviceId, @Valid Operation operation) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
|
||||
String errorMessage = "Device type is invalid";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
if (operation == null) {
|
||||
String errorMessage = "Operation cannot empty";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, type);
|
||||
if (!DeviceMgtAPIUtils.isValidDeviceIdentifier(deviceIdentifier)) {
|
||||
String msg = "Device not found for identifier '" + deviceId + "'";
|
||||
log.error(msg);
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
}
|
||||
if (!Operation.Status.ERROR.equals(operation.getStatus()) && operation.getCode() != null &&
|
||||
POLICY_MONITOR.equals(operation.getCode())) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.info("Received compliance status from POLICY_MONITOR operation ID: " + operation.getId());
|
||||
}
|
||||
List<ComplianceFeature> features = getComplianceFeatures(operation.getPayLoad());
|
||||
DeviceMgtAPIUtils.getPolicyManagementService().checkCompliance(deviceIdentifier, features);
|
||||
|
||||
} else {
|
||||
DeviceMgtAPIUtils.getDeviceManagementService().updateOperation(deviceIdentifier, operation);
|
||||
}
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String errorMessage = "Issue in retrieving operation management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMessage = "Issue in retrieving deivce management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
} catch (PolicyComplianceException e) {
|
||||
String errorMessage = "Issue in retrieving deivce management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/status/operations/{type}/{id}")
|
||||
public Response getOperationsByDeviceAndStatus(@PathParam("type") String type, @PathParam("id") String deviceId,
|
||||
@QueryParam("status") Operation.Status status) {
|
||||
if (status == null) {
|
||||
String errorMessage = "Status is empty";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
|
||||
String errorMessage = "Invalid Device Type";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
List<? extends Operation> operations = DeviceMgtAPIUtils.getDeviceManagementService()
|
||||
.getOperationsByDeviceAndStatus(new DeviceIdentifier(deviceId, type), status);
|
||||
OperationList operationsList = new OperationList();
|
||||
operationsList.setList(operations);
|
||||
operationsList.setCount(operations.size());
|
||||
return Response.status(Response.Status.OK).entity(operationsList).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String errorMessage = "Issue in retrieving operation management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMessage = "Issue in retrieving device management service";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorMessage).build();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<ComplianceFeature> getComplianceFeatures(Object compliancePayload) throws
|
||||
PolicyComplianceException {
|
||||
String compliancePayloadString = new Gson().toJson(compliancePayload);
|
||||
if (compliancePayload == null) {
|
||||
return null;
|
||||
}
|
||||
// Parsing json string to get compliance features.
|
||||
JsonElement jsonElement = new JsonParser().parse(compliancePayloadString);
|
||||
|
||||
JsonArray jsonArray = jsonElement.getAsJsonArray();
|
||||
Gson gson = new Gson();
|
||||
ComplianceFeature complianceFeature;
|
||||
List<ComplianceFeature> complianceFeatures = new ArrayList<ComplianceFeature>(jsonArray.size());
|
||||
|
||||
for (JsonElement element : jsonArray) {
|
||||
complianceFeature = gson.fromJson(element, ComplianceFeature.class);
|
||||
complianceFeatures.add(complianceFeature);
|
||||
}
|
||||
return complianceFeatures;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,590 @@
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
|
||||
|
||||
import org.apache.axis2.AxisFault;
|
||||
import org.apache.axis2.client.Stub;
|
||||
import org.apache.commons.logging.Log;
|
||||
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.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.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.DeviceTypeEvent;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventRecords;
|
||||
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.EventAttributeList;
|
||||
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.util.Constants;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler;
|
||||
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
|
||||
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceCallbackHandler;
|
||||
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
|
||||
import org.wso2.carbon.event.receiver.stub.types.BasicInputAdapterPropertyDto;
|
||||
import org.wso2.carbon.event.receiver.stub.types.EventReceiverConfigurationDto;
|
||||
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamAttributeDto;
|
||||
import org.wso2.carbon.event.stream.stub.types.EventStreamDefinitionDto;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.rmi.RemoteException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This is used for device type integration with DAS, to create streams and receiver dynamically and a common endpoint
|
||||
* to retrieve data.
|
||||
*/
|
||||
@Path("/events")
|
||||
public class DeviceEventManagementServiceImpl implements DeviceEventManagementService {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceEventManagementServiceImpl.class);
|
||||
|
||||
private static final String DEFAULT_EVENT_STORE_NAME = "EVENT_STORE";
|
||||
private static final String DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE = "secured-websocket";
|
||||
private static final String OAUTH_MQTT_ADAPTER_TYPE = "oauth-mqtt";
|
||||
private static final String THRIFT_ADAPTER_TYPE = "iot-event";
|
||||
private static final String DEFAULT_DEVICE_ID_ATTRIBUTE = "deviceId";
|
||||
private static final String DEFAULT_META_DEVICE_ID_ATTRIBUTE = "meta_deviceId";
|
||||
private static final String MQTT_CONTENT_TRANSFORMER = "device-meta-transformer";
|
||||
private static final String MQTT_CONTENT_TRANSFORMER_TYPE = "contentTransformer";
|
||||
private static final String MQTT_CONTENT_VALIDATOR_TYPE = "contentValidator";
|
||||
private static final String MQTT_CONTENT_VALIDATOR = "default";
|
||||
private static final String TIMESTAMP_FIELD_NAME = "_timestamp";
|
||||
|
||||
/**
|
||||
* Retrieves the stream definition from das for the given device type.
|
||||
* @return dynamic event attribute list
|
||||
*/
|
||||
@GET
|
||||
@Path("/{type}")
|
||||
@Override
|
||||
public Response getDeviceTypeEventDefinition(@PathParam("type") String deviceType) {
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
|
||||
EventReceiverAdminServiceStub eventReceiverAdminServiceStub = null;
|
||||
try {
|
||||
if (deviceType == null ||
|
||||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
|
||||
String errorMessage = "Invalid device type";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain);
|
||||
eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = eventStreamAdminServiceStub.getStreamDefinitionDto(
|
||||
streamName + ":" + Constants.DEFAULT_STREAM_VERSION);
|
||||
if (eventStreamDefinitionDto == null) {
|
||||
return Response.status(Response.Status.NO_CONTENT).build();
|
||||
}
|
||||
|
||||
EventStreamAttributeDto[] eventStreamAttributeDtos = eventStreamDefinitionDto.getPayloadData();
|
||||
EventAttributeList eventAttributeList = new EventAttributeList();
|
||||
List<Attribute> attributes = new ArrayList<>();
|
||||
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
|
||||
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
|
||||
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
|
||||
}
|
||||
eventAttributeList.setList(attributes);
|
||||
|
||||
DeviceTypeEvent deviceTypeEvent = new DeviceTypeEvent();
|
||||
deviceTypeEvent.setEventAttributeList(eventAttributeList);
|
||||
deviceTypeEvent.setTransportType(TransportType.HTTP);
|
||||
eventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
|
||||
EventReceiverConfigurationDto eventReceiverConfigurationDto = eventReceiverAdminServiceStub
|
||||
.getActiveEventReceiverConfiguration(getReceiverName(deviceType, tenantDomain, TransportType.MQTT));
|
||||
if (eventReceiverConfigurationDto != null) {
|
||||
deviceTypeEvent.setTransportType(TransportType.MQTT);
|
||||
}
|
||||
return Response.ok().entity(deviceTypeEvent).build();
|
||||
} catch (AxisFault e) {
|
||||
log.error("Failed to retrieve event definitions for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to connect with the remote services:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JWTClientException e) {
|
||||
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} finally {
|
||||
cleanup(eventStreamAdminServiceStub);
|
||||
cleanup(eventReceiverAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deploy Event Stream, Receiver, Publisher and Store Configuration.
|
||||
*/
|
||||
@POST
|
||||
@Path("/{type}")
|
||||
@Override
|
||||
public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
|
||||
@Valid DeviceTypeEvent deviceTypeEvent) {
|
||||
TransportType transportType = deviceTypeEvent.getTransportType();
|
||||
EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
try {
|
||||
if (eventAttributes == null || eventAttributes.getList() == null || eventAttributes.getList().size() == 0 ||
|
||||
deviceType == null || transportType == null ||
|
||||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
|
||||
String errorMessage = "Invalid Payload";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain);
|
||||
String streamNameWithVersion = streamName + ":" + Constants.DEFAULT_STREAM_VERSION;
|
||||
publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
|
||||
publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, deviceType);
|
||||
publishEventStore(streamName, Constants.DEFAULT_STREAM_VERSION, eventAttributes);
|
||||
publishWebsocketPublisherDefinition(streamNameWithVersion, deviceType);
|
||||
try {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
|
||||
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
|
||||
publishStreamDefinitons(streamName, Constants.DEFAULT_STREAM_VERSION, deviceType, eventAttributes);
|
||||
publishEventReceivers(streamNameWithVersion, transportType, tenantDomain, deviceType);
|
||||
}
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
return Response.ok().build();
|
||||
} catch (AxisFault e) {
|
||||
log.error("Failed to create event definitions for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to connect with the remote services:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JWTClientException e) {
|
||||
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException e) {
|
||||
log.error("Failed to create event store for, tenantDomain: " + tenantDomain + " deviceType" + deviceType,
|
||||
e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete device type specific artifacts from DAS.
|
||||
*/
|
||||
@DELETE
|
||||
@Path("/{type}")
|
||||
@Override
|
||||
public Response deleteDeviceTypeEventDefinitions(@PathParam("type") String deviceType) {
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
EventReceiverAdminServiceStub eventReceiverAdminServiceStub = null;
|
||||
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = null;
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = null;
|
||||
|
||||
EventReceiverAdminServiceStub tenantBasedEventReceiverAdminServiceStub = null;
|
||||
EventStreamAdminServiceStub tenantBasedEventStreamAdminServiceStub = null;
|
||||
try {
|
||||
if (deviceType == null ||
|
||||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
|
||||
String errorMessage = "Invalid device type";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher";
|
||||
String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain);
|
||||
eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamName + ":" + Constants.DEFAULT_STREAM_VERSION) == null) {
|
||||
return Response.status(Response.Status.NO_CONTENT).build();
|
||||
}
|
||||
eventStreamAdminServiceStub.removeEventStreamDefinition(streamName, Constants.DEFAULT_STREAM_VERSION);
|
||||
EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler =
|
||||
new EventReceiverAdminServiceCallbackHandler() {};
|
||||
EventPublisherAdminServiceCallbackHandler eventPublisherAdminServiceCallbackHandler =
|
||||
new EventPublisherAdminServiceCallbackHandler() {};
|
||||
|
||||
|
||||
String eventReceiverName = getReceiverName(deviceType, tenantDomain, TransportType.MQTT);
|
||||
eventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
|
||||
if (eventReceiverAdminServiceStub.getInactiveEventReceiverConfigurationContent(eventReceiverName) == null) {
|
||||
eventReceiverName = getReceiverName(deviceType, tenantDomain, TransportType.HTTP);
|
||||
}
|
||||
eventReceiverAdminServiceStub.startundeployInactiveEventReceiverConfiguration(eventReceiverName
|
||||
, eventReceiverAdminServiceCallbackHandler);
|
||||
|
||||
eventPublisherAdminServiceStub = DeviceMgtAPIUtils.getEventPublisherAdminServiceStub();
|
||||
eventPublisherAdminServiceStub.startundeployInactiveEventPublisherConfiguration(eventPublisherName
|
||||
, eventPublisherAdminServiceCallbackHandler);
|
||||
|
||||
try {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
|
||||
MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
|
||||
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
|
||||
tenantBasedEventReceiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
|
||||
tenantBasedEventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
tenantBasedEventStreamAdminServiceStub.removeEventStreamDefinition(streamName,
|
||||
Constants.DEFAULT_STREAM_VERSION);
|
||||
|
||||
tenantBasedEventReceiverAdminServiceStub.startundeployInactiveEventReceiverConfiguration(
|
||||
eventReceiverName, eventReceiverAdminServiceCallbackHandler);
|
||||
|
||||
}
|
||||
} finally {
|
||||
cleanup(tenantBasedEventReceiverAdminServiceStub);
|
||||
cleanup(tenantBasedEventStreamAdminServiceStub);
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
return Response.ok().build();
|
||||
} catch (AxisFault e) {
|
||||
log.error("Failed to delete event definitions for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (RemoteException e) {
|
||||
log.error("Failed to connect with the remote services:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (JWTClientException e) {
|
||||
log.error("Failed to generate jwt token for tenantDomain:" + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (UserStoreException e) {
|
||||
log.error("Failed to connect with the user store, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error("Failed to access device management service, tenantDomain: " + tenantDomain, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} finally {
|
||||
cleanup(eventStreamAdminServiceStub);
|
||||
cleanup(eventPublisherAdminServiceStub);
|
||||
cleanup(eventReceiverAdminServiceStub);
|
||||
cleanup(eventReceiverAdminServiceStub);
|
||||
cleanup(eventStreamAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns device specific data for the give period of time.
|
||||
*/
|
||||
@GET
|
||||
@Path("/{type}/{deviceId}")
|
||||
@Override
|
||||
public Response getData(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
|
||||
@QueryParam("to") long to, @PathParam("type") String deviceType, @QueryParam("offset")
|
||||
int offset, @QueryParam("limit") int limit) {
|
||||
if (from == 0 || to == 0) {
|
||||
String errorMessage = "Invalid values for from/to";
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
|
||||
}
|
||||
String fromDate = String.valueOf(from);
|
||||
String toDate = String.valueOf(to);
|
||||
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId
|
||||
+ " AND _timestamp : [" + fromDate + " TO " + toDate + "]";
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain));
|
||||
try {
|
||||
if (deviceType == null ||
|
||||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
|
||||
String errorMessage = "Invalid device type";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
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);
|
||||
sortByFields.add(sortByField);
|
||||
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, offset, limit);
|
||||
return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build();
|
||||
} catch (AnalyticsException e) {
|
||||
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
|
||||
log.error(errorMsg);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
|
||||
log.error(errorMsg);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last know data point of the device type.
|
||||
*/
|
||||
@GET
|
||||
@Path("/last-known/{type}/{deviceId}")
|
||||
@Override
|
||||
public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType) {
|
||||
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId;
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String sensorTableName = getTableName(DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain));
|
||||
try {
|
||||
if (deviceType == null ||
|
||||
!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(deviceType)) {
|
||||
String errorMessage = "Invalid device type";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
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);
|
||||
sortByFields.add(sortByField);
|
||||
EventRecords eventRecords = getAllEventsForDevice(sensorTableName, query, sortByFields, 0, 1);
|
||||
return Response.status(Response.Status.OK.getStatusCode()).entity(eventRecords).build();
|
||||
} catch (AnalyticsException e) {
|
||||
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
|
||||
log.error(errorMsg);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
|
||||
log.error(errorMsg);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
|
||||
}
|
||||
}
|
||||
|
||||
private void publishEventReceivers(String streamNameWithVersion, TransportType transportType
|
||||
, String requestedTenantDomain, String deviceType)
|
||||
throws RemoteException, UserStoreException, JWTClientException {
|
||||
EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
|
||||
try {
|
||||
TransportType transportTypeToBeRemoved = TransportType.HTTP;
|
||||
if (transportType == TransportType.HTTP) {
|
||||
transportTypeToBeRemoved = TransportType.MQTT;
|
||||
}
|
||||
String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
|
||||
EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub
|
||||
.getActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved);
|
||||
if (eventReceiverConfigurationDto != null) {
|
||||
EventReceiverAdminServiceCallbackHandler eventReceiverAdminServiceCallbackHandler =
|
||||
new EventReceiverAdminServiceCallbackHandler() {};
|
||||
receiverAdminServiceStub.startundeployActiveEventReceiverConfiguration(eventRecieverNameTobeRemoved
|
||||
, eventReceiverAdminServiceCallbackHandler);
|
||||
}
|
||||
|
||||
String adapterType = OAUTH_MQTT_ADAPTER_TYPE;
|
||||
BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[];
|
||||
if (transportType == TransportType.MQTT) {
|
||||
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3];
|
||||
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", requestedTenantDomain
|
||||
+ "/" + deviceType + "/+/events");
|
||||
basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE
|
||||
, MQTT_CONTENT_TRANSFORMER);
|
||||
basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE
|
||||
, MQTT_CONTENT_VALIDATOR);
|
||||
} else {
|
||||
adapterType = THRIFT_ADAPTER_TYPE;
|
||||
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1];
|
||||
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false");
|
||||
}
|
||||
String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType);
|
||||
if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
|
||||
if (transportType == TransportType.MQTT) {
|
||||
receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion
|
||||
, adapterType, null, basicInputAdapterPropertyDtos, false);
|
||||
} else {
|
||||
receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion
|
||||
, adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
cleanup(receiverAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishStreamDefinitons(String streamName, String version, String deviceType
|
||||
, EventAttributeList eventAttributes)
|
||||
throws RemoteException, UserStoreException, JWTClientException {
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
|
||||
try {
|
||||
EventStreamDefinitionDto eventStreamDefinitionDto = new EventStreamDefinitionDto();
|
||||
eventStreamDefinitionDto.setName(streamName);
|
||||
eventStreamDefinitionDto.setVersion(version);
|
||||
EventStreamAttributeDto eventStreamAttributeDtos[] =
|
||||
new EventStreamAttributeDto[eventAttributes.getList().size()];
|
||||
EventStreamAttributeDto metaStreamAttributeDtos[] =
|
||||
new EventStreamAttributeDto[1];
|
||||
int i = 0;
|
||||
for (Attribute attribute : eventAttributes.getList()) {
|
||||
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
|
||||
eventStreamAttributeDto.setAttributeName(attribute.getName());
|
||||
eventStreamAttributeDto.setAttributeType(attribute.getType().toString());
|
||||
eventStreamAttributeDtos[i] = eventStreamAttributeDto;
|
||||
i++;
|
||||
}
|
||||
|
||||
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
|
||||
eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE);
|
||||
eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString());
|
||||
metaStreamAttributeDtos[0] = eventStreamAttributeDto;
|
||||
eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos);
|
||||
eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos);
|
||||
String streamId = streamName + ":" + version;
|
||||
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) {
|
||||
eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId);
|
||||
} else {
|
||||
eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto);
|
||||
}
|
||||
} finally {
|
||||
cleanup(eventStreamAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishEventStore(String streamName, String version, EventAttributeList eventAttributes)
|
||||
throws RemoteException, UserStoreException, JWTClientException,
|
||||
EventStreamPersistenceAdminServiceEventStreamPersistenceAdminServiceExceptionException {
|
||||
EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub =
|
||||
DeviceMgtAPIUtils.getEventStreamPersistenceAdminServiceStub();
|
||||
try {
|
||||
AnalyticsTable analyticsTable = new AnalyticsTable();
|
||||
analyticsTable.setRecordStoreName(DEFAULT_EVENT_STORE_NAME);
|
||||
analyticsTable.setStreamVersion(version);
|
||||
analyticsTable.setTableName(streamName);
|
||||
analyticsTable.setMergeSchema(false);
|
||||
analyticsTable.setPersist(true);
|
||||
AnalyticsTableRecord analyticsTableRecords[] = new AnalyticsTableRecord[eventAttributes.getList().size() + 1];
|
||||
int i = 0;
|
||||
for (Attribute attribute : eventAttributes.getList()) {
|
||||
AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
|
||||
analyticsTableRecord.setColumnName(attribute.getName());
|
||||
analyticsTableRecord.setColumnType(attribute.getType().toString().toUpperCase());
|
||||
analyticsTableRecord.setFacet(false);
|
||||
analyticsTableRecord.setIndexed(false);
|
||||
analyticsTableRecord.setPersist(true);
|
||||
analyticsTableRecord.setPrimaryKey(false);
|
||||
analyticsTableRecord.setScoreParam(false);
|
||||
analyticsTableRecords[i] = analyticsTableRecord;
|
||||
i++;
|
||||
}
|
||||
AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
|
||||
analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE);
|
||||
analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase());
|
||||
analyticsTableRecord.setFacet(false);
|
||||
analyticsTableRecord.setIndexed(true);
|
||||
analyticsTableRecord.setPersist(true);
|
||||
analyticsTableRecord.setPrimaryKey(false);
|
||||
analyticsTableRecord.setScoreParam(false);
|
||||
analyticsTableRecords[i] = analyticsTableRecord;
|
||||
analyticsTable.setAnalyticsTableRecords(analyticsTableRecords);
|
||||
eventStreamPersistenceAdminServiceStub.addAnalyticsTable(analyticsTable);
|
||||
} finally {
|
||||
cleanup(eventStreamPersistenceAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
private void publishWebsocketPublisherDefinition(String streamNameWithVersion, String deviceType)
|
||||
throws RemoteException, UserStoreException, JWTClientException {
|
||||
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = DeviceMgtAPIUtils
|
||||
.getEventPublisherAdminServiceStub();
|
||||
try {
|
||||
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher";
|
||||
if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) {
|
||||
eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName
|
||||
, streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null
|
||||
, null, false);
|
||||
}
|
||||
} finally {
|
||||
cleanup(eventPublisherAdminServiceStub);
|
||||
}
|
||||
}
|
||||
|
||||
private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) {
|
||||
BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto();
|
||||
basicInputAdapterPropertyDto.setKey(key);
|
||||
basicInputAdapterPropertyDto.setValue(value);
|
||||
return basicInputAdapterPropertyDto;
|
||||
}
|
||||
|
||||
private String getTableName(String streamName) {
|
||||
return streamName.toUpperCase().replace('.', '_');
|
||||
}
|
||||
|
||||
private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType) {
|
||||
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver";
|
||||
}
|
||||
|
||||
private static AnalyticsDataAPI getAnalyticsDataAPI() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
AnalyticsDataAPI analyticsDataAPI =
|
||||
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
|
||||
if (analyticsDataAPI == null) {
|
||||
String msg = "Analytics api service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return analyticsDataAPI;
|
||||
}
|
||||
|
||||
private static EventRecords getAllEventsForDevice(String tableName, String query, List<SortByField> sortByFields
|
||||
, int offset, int limit) throws AnalyticsException {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
|
||||
EventRecords eventRecords = new EventRecords();
|
||||
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
|
||||
if (eventCount == 0) {
|
||||
eventRecords.setCount(0);
|
||||
}
|
||||
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, offset, limit,
|
||||
sortByFields);
|
||||
List<String> recordIds = getRecordIds(resultEntries);
|
||||
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
|
||||
eventRecords.setCount(eventCount);
|
||||
eventRecords.setList(AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response));
|
||||
return eventRecords;
|
||||
}
|
||||
|
||||
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (SearchResultEntry searchResult : searchResults) {
|
||||
ids.add(searchResult.getId());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private void cleanup(Stub stub) {
|
||||
if (stub != null) {
|
||||
try {
|
||||
stub.cleanup();
|
||||
} catch (AxisFault axisFault) {
|
||||
log.warn("Failed to clean the stub " + stub.getClass());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -18,17 +18,19 @@
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
|
||||
|
||||
import io.swagger.annotations.ApiParam;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
|
||||
@ -36,6 +38,7 @@ import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
|
||||
@ -45,6 +48,8 @@ import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
||||
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
|
||||
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
@ -52,6 +57,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceCompliance;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
@ -59,6 +65,8 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
|
||||
import javax.security.auth.login.Configuration;
|
||||
import javax.validation.Valid;
|
||||
import javax.validation.constraints.Size;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
@ -84,6 +92,27 @@ import java.util.List;
|
||||
public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagementServiceImpl.class);
|
||||
public static final String DATE_FORMAT_NOW = "yyyy-MM-dd HH:mm:ss";
|
||||
|
||||
@GET
|
||||
@Path("/{type}/{id}/status")
|
||||
@Override
|
||||
public Response isEnrolled(@PathParam("type") String type, @PathParam("id") String id) {
|
||||
boolean result;
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type);
|
||||
try {
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().isEnrolled(deviceIdentifier);
|
||||
if (result) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NO_CONTENT).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while checking enrollment status of the device.";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
}
|
||||
}
|
||||
|
||||
@GET
|
||||
@Override
|
||||
@ -91,12 +120,14 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
@QueryParam("name") String name,
|
||||
@QueryParam("type") String type,
|
||||
@QueryParam("user") String user,
|
||||
@QueryParam("userPattern") String userPattern,
|
||||
@QueryParam("role") String role,
|
||||
@QueryParam("ownership") String ownership,
|
||||
@QueryParam("status") String status,
|
||||
@QueryParam("groupId") int groupId,
|
||||
@QueryParam("since") String since,
|
||||
@HeaderParam("If-Modified-Since") String ifModifiedSince,
|
||||
@QueryParam("requireDeviceInfo") boolean requireDeviceInfo,
|
||||
@QueryParam("offset") int offset,
|
||||
@QueryParam("limit") int limit) {
|
||||
try {
|
||||
@ -126,9 +157,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
if (type != null && !type.isEmpty()) {
|
||||
request.setDeviceType(type);
|
||||
}
|
||||
if (user != null && !user.isEmpty()) {
|
||||
request.setOwner(user);
|
||||
}
|
||||
if (ownership != null && !ownership.isEmpty()) {
|
||||
RequestValidationUtil.validateOwnershipType(ownership);
|
||||
request.setOwnership(ownership);
|
||||
@ -151,6 +179,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
if (deviceAccessAuthorizationService.isDeviceAdminUser()) {
|
||||
if (user != null && !user.isEmpty()) {
|
||||
request.setOwner(MultitenantUtils.getTenantAwareUsername(user));
|
||||
} else if (userPattern != null && !userPattern.isEmpty()) {
|
||||
request.setOwnerPattern(userPattern);
|
||||
}
|
||||
} else {
|
||||
if (user != null && !user.isEmpty()) {
|
||||
@ -180,7 +210,12 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
"string is provided in 'If-Modified-Since' header").build()).build();
|
||||
}
|
||||
request.setSince(sinceDate);
|
||||
result = dms.getAllDevices(request);
|
||||
if (requireDeviceInfo) {
|
||||
result = dms.getAllDevices(request);
|
||||
} else {
|
||||
result = dms.getAllDevices(request, false);
|
||||
}
|
||||
|
||||
if (result == null || result.getData() == null || result.getData().size() <= 0) {
|
||||
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
|
||||
"after the timestamp provided in 'If-Modified-Since' header").build();
|
||||
@ -196,14 +231,22 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
"string is provided in 'since' filter").build()).build();
|
||||
}
|
||||
request.setSince(sinceDate);
|
||||
result = dms.getAllDevices(request);
|
||||
if (requireDeviceInfo) {
|
||||
result = dms.getAllDevices(request);
|
||||
} else {
|
||||
result = dms.getAllDevices(request, false);
|
||||
}
|
||||
if (result == null || result.getData() == null || result.getData().size() <= 0) {
|
||||
devices.setList(new ArrayList<Device>());
|
||||
devices.setCount(0);
|
||||
return Response.status(Response.Status.OK).entity(devices).build();
|
||||
}
|
||||
} else {
|
||||
result = dms.getAllDevices(request);
|
||||
if (requireDeviceInfo) {
|
||||
result = dms.getAllDevices(request);
|
||||
} else {
|
||||
result = dms.getAllDevices(request, false);
|
||||
}
|
||||
int resultCount = result.getRecordsTotal();
|
||||
if (resultCount == 0) {
|
||||
Response.status(Response.Status.OK).entity(devices).build();
|
||||
@ -229,7 +272,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
@GET
|
||||
@Override
|
||||
@Path("/user-devices")
|
||||
public Response getDeviceByUser(@QueryParam("offset") int offset,
|
||||
public Response getDeviceByUser(@QueryParam("requireDeviceInfo") boolean requireDeviceInfo,
|
||||
@QueryParam("offset") int offset,
|
||||
@QueryParam("limit") int limit) {
|
||||
|
||||
RequestValidationUtil.validatePaginationParameters(offset, limit);
|
||||
@ -241,7 +285,11 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
request.setOwner(currentUser);
|
||||
|
||||
try {
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request);
|
||||
if (requireDeviceInfo) {
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request);
|
||||
} else {
|
||||
result = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(request, false);
|
||||
}
|
||||
devices.setList((List<Device>) result.getData());
|
||||
devices.setCount(result.getRecordsTotal());
|
||||
return Response.status(Response.Status.OK).entity(devices).build();
|
||||
@ -261,7 +309,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
|
||||
Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier);
|
||||
Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, true);
|
||||
if (persistedDevice == null) {
|
||||
return Response.status(Response.Status.NOT_FOUND).build();
|
||||
}
|
||||
@ -287,7 +335,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
try {
|
||||
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
|
||||
(deviceId, deviceType));
|
||||
(deviceId, deviceType), true);
|
||||
persistedDevice.setName(device.getName());
|
||||
boolean response = deviceManagementProviderService.modifyEnrollment(persistedDevice);
|
||||
return Response.status(Response.Status.CREATED).entity(response).build();
|
||||
@ -534,7 +582,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
RequestValidationUtil.validateDeviceIdentifier(type, id);
|
||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||
Policy policy;
|
||||
NonComplianceData complianceData = null;
|
||||
NonComplianceData complianceData;
|
||||
DeviceCompliance deviceCompliance = new DeviceCompliance();
|
||||
|
||||
try {
|
||||
@ -586,7 +634,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, type);
|
||||
Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier);
|
||||
Device persistedDevice = deviceManagementProviderService.getDevice(deviceIdentifier, false);
|
||||
if (persistedDevice == null) {
|
||||
return Response.status(Response.Status.NOT_FOUND).build();
|
||||
}
|
||||
@ -600,4 +648,78 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{type}/operations")
|
||||
public Response addOperation(@PathParam("type") String type, @Valid OperationRequest operationRequest) {
|
||||
try {
|
||||
if (operationRequest == null || operationRequest.getDeviceIdentifiers() == null
|
||||
|| operationRequest.getOperation() == null) {
|
||||
String errorMessage = "Operation cannot be empty";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
if (!DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes().contains(type)) {
|
||||
String errorMessage = "Device Type is invalid";
|
||||
log.error(errorMessage);
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
Operation.Type operationType = operationRequest.getOperation().getType();
|
||||
if (operationType == Operation.Type.COMMAND || operationType == Operation.Type.CONFIG) {
|
||||
DeviceIdentifier deviceIdentifier;
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
for (String deviceId : operationRequest.getDeviceIdentifiers()) {
|
||||
deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(type);
|
||||
deviceIdentifiers.add(deviceIdentifier);
|
||||
}
|
||||
Operation operation;
|
||||
if (operationType == Operation.Type.COMMAND) {
|
||||
Operation commandOperation = operationRequest.getOperation();
|
||||
operation = new CommandOperation();
|
||||
operation.setType(Operation.Type.COMMAND);
|
||||
operation.setCode(commandOperation.getCode());
|
||||
operation.setEnabled(commandOperation.isEnabled());
|
||||
operation.setStatus(commandOperation.getStatus());
|
||||
|
||||
} else {
|
||||
Operation configOperation = operationRequest.getOperation();
|
||||
operation = new ConfigOperation();
|
||||
operation.setType(Operation.Type.CONFIG);
|
||||
operation.setCode(configOperation.getCode());
|
||||
operation.setEnabled(configOperation.isEnabled());
|
||||
operation.setPayLoad(configOperation.getPayLoad());
|
||||
operation.setStatus(configOperation.getStatus());
|
||||
}
|
||||
String date = new SimpleDateFormat(DATE_FORMAT_NOW).format(new Date());
|
||||
operation.setCreatedTimeStamp(date);
|
||||
Activity activity = DeviceMgtAPIUtils.getDeviceManagementService().addOperation(type, operation,
|
||||
deviceIdentifiers);
|
||||
return Response.status(Response.Status.CREATED).entity(activity).build();
|
||||
} else {
|
||||
String message = "Only Command and Config operation is supported through this api";
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE).entity(message).build();
|
||||
}
|
||||
|
||||
} catch (InvalidDeviceException e) {
|
||||
String errorMessage = "Invalid Device Identifiers found.";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String errorMessage = "Issue in retrieving operation management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String errorMessage = "Issue in retrieving deivce management service instance";
|
||||
log.error(errorMessage, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
|
||||
} catch (InvalidConfigurationException e) {
|
||||
log.error("failed to add operation", e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -23,6 +23,9 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceTypeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
@ -35,7 +38,9 @@ import javax.ws.rs.GET;
|
||||
import javax.ws.rs.HeaderParam;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Path("/device-types")
|
||||
@ -86,4 +91,62 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
|
||||
return Response.status(Response.Status.OK).entity(features).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
@GET
|
||||
@Path("/config")
|
||||
public Response getDeviceTypes() {
|
||||
try {
|
||||
List<DeviceType> deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceTypes();
|
||||
List<DeviceType> filteredDeviceTypes = new ArrayList<>();
|
||||
for (DeviceType deviceType : deviceTypes) {
|
||||
filteredDeviceTypes.add(clearMetaEntryInfo(deviceType));
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity(filteredDeviceTypes).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred at server side while fetching device type.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(msg).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@GET
|
||||
@Path("/config/{type}")
|
||||
public Response getDeviceTypeByName(@PathParam("type") String type) {
|
||||
if (type != null && type.length() > 0) {
|
||||
try {
|
||||
DeviceType deviceType = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(type);
|
||||
if (deviceType == null) {
|
||||
String msg = "Device type does not exist, " + type;
|
||||
return Response.status(Response.Status.NO_CONTENT).entity(msg).build();
|
||||
}
|
||||
return Response.status(Response.Status.OK).entity(deviceType).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred at server side while fetching device type.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(msg).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This cleans up the configs that should not be exposed to iot users.
|
||||
* @param deviceType
|
||||
* @return
|
||||
*/
|
||||
private DeviceType clearMetaEntryInfo(DeviceType deviceType) {
|
||||
DeviceTypeMetaDefinition metaDefinition = deviceType.getDeviceTypeMetaDefinition();
|
||||
if (metaDefinition != null) {
|
||||
metaDefinition.setInitialOperationConfig(null);
|
||||
if (metaDefinition.getPushNotificationConfig() != null) {
|
||||
metaDefinition.setPushNotificationConfig(new PushNotificationConfig(metaDefinition.
|
||||
getPushNotificationConfig().getType(), false, null));
|
||||
}
|
||||
deviceType.setDeviceTypeMetaDefinition(metaDefinition);
|
||||
}
|
||||
return deviceType;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,379 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
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.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants.GeoServices;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.Alert;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.Event;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.GeoFence;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationBasedServiceException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The api for
|
||||
*/
|
||||
public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
|
||||
|
||||
private static Log log = LogFactory.getLog(GeoLocationBasedServiceImpl.class);
|
||||
|
||||
@Path("stats/{deviceType}/{deviceId}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response getGeoDeviceStats(@PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@QueryParam("from") long from, @QueryParam("to") long to) {
|
||||
//First, check whether the Geo Location service has been enabled in the cdmf-config.xml file
|
||||
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance()
|
||||
.getDeviceManagementConfig();
|
||||
if (deviceManagementConfig != null) {
|
||||
if(!deviceManagementConfig.getGeoLocationConfiguration().getPublishLocationOperationResponse()){
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
String tableName = "IOT_PER_DEVICE_STREAM_GEO_FUSEDSPATIALEVENT";
|
||||
String fromDate = String.valueOf(from);
|
||||
String toDate = String.valueOf(to);
|
||||
String query = "id:" + deviceId + " AND type:" + deviceType;
|
||||
if (from != 0 || to != 0) {
|
||||
query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]";
|
||||
}
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
List<SortByField> sortByFields = new ArrayList<>();
|
||||
SortByField sortByField = new SortByField("timeStamp", SortType.ASC);
|
||||
sortByFields.add(sortByField);
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername());
|
||||
|
||||
try {
|
||||
String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
|
||||
int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
|
||||
AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
|
||||
List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
|
||||
0,
|
||||
100,
|
||||
sortByFields);
|
||||
List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
|
||||
searchResults);
|
||||
return Response.ok().entity(events).build();
|
||||
} catch (AnalyticsException | UserStoreException e) {
|
||||
log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);
|
||||
throw DeviceMgtUtil.buildBadRequestException(
|
||||
Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT);
|
||||
}
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@POST
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response createGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@PathParam("alertType") String alertType) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername()
|
||||
);
|
||||
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId(deviceId);
|
||||
identifier.setType(deviceType);
|
||||
|
||||
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
|
||||
geoService.createGeoAlert(alert, identifier, alertType);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
|
||||
String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId;
|
||||
log.error(error, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@PUT
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response updateGeoAlerts(Alert alert, @PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@PathParam("alertType") String alertType) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername()
|
||||
);
|
||||
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId(deviceId);
|
||||
identifier.setType(deviceType);
|
||||
|
||||
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
|
||||
geoService.updateGeoAlert(alert, identifier, alertType);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
|
||||
String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId;
|
||||
log.error(error, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@DELETE
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response removeGeoAlerts(@PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@PathParam("alertType") String alertType,
|
||||
@QueryParam("queryName") String queryName) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername()
|
||||
);
|
||||
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId(deviceId);
|
||||
identifier.setType(deviceType);
|
||||
|
||||
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
|
||||
geoService.removeGeoAlert(alertType, identifier, queryName);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
|
||||
String error = "Error occurred while removing the geo alert for " + deviceType + " with id: " + deviceId;
|
||||
log.error(error, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("alerts/{alertType}/{deviceType}/{deviceId}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response getGeoAlerts(@PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@PathParam("alertType") String alertType) {
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername()
|
||||
);
|
||||
|
||||
DeviceIdentifier identifier = new DeviceIdentifier();
|
||||
identifier.setId(deviceId);
|
||||
identifier.setType(deviceType);
|
||||
|
||||
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
|
||||
|
||||
if (GeoServices.ALERT_TYPE_WITHIN.equals(alertType)) {
|
||||
List<GeoFence> alerts = geoService.getWithinAlerts(identifier);
|
||||
return Response.ok().entity(alerts).build();
|
||||
} else if (GeoServices.ALERT_TYPE_EXIT.equals(alertType)) {
|
||||
List<GeoFence> alerts = geoService.getExitAlerts(identifier);
|
||||
return Response.ok().entity(alerts).build();
|
||||
} else if (GeoServices.ALERT_TYPE_SPEED.equals(alertType)) {
|
||||
String result = geoService.getSpeedAlerts(identifier);
|
||||
return Response.ok().entity(result).build();
|
||||
} else if (GeoServices.ALERT_TYPE_PROXIMITY.equals(alertType)) {
|
||||
String result = geoService.getProximityAlerts(identifier);
|
||||
return Response.ok().entity(result).build();
|
||||
} else if (GeoServices.ALERT_TYPE_STATIONARY.equals(alertType)) {
|
||||
List<GeoFence> alerts = geoService.getStationaryAlerts(identifier);
|
||||
return Response.ok().entity(alerts).build();
|
||||
} else if (GeoServices.ALERT_TYPE_TRAFFIC.equals(alertType)) {
|
||||
List<GeoFence> alerts = geoService.getTrafficAlerts(identifier);
|
||||
return Response.ok().entity(alerts).build();
|
||||
}
|
||||
return null;
|
||||
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
|
||||
String error = "Error occurred while getting the geo alerts for " + deviceType + " with id: " + deviceId;
|
||||
log.error(error, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("alerts/history/{deviceType}/{deviceId}")
|
||||
@GET
|
||||
@Consumes("application/json")
|
||||
@Produces("application/json")
|
||||
public Response getGeoAlertsHistory(@PathParam("deviceId") String deviceId,
|
||||
@PathParam("deviceType") String deviceType,
|
||||
@QueryParam("from") long from, @QueryParam("to") long to) {
|
||||
String tableName = "IOT_PER_DEVICE_STREAM_GEO_ALERTNOTIFICATIONS";
|
||||
String fromDate = String.valueOf(from);
|
||||
String toDate = String.valueOf(to);
|
||||
String query = "id:" + deviceId + " AND type:" + deviceType;
|
||||
if (from != 0 || to != 0) {
|
||||
query += " AND timeStamp : [" + fromDate + " TO " + toDate + "]";
|
||||
}
|
||||
try {
|
||||
if (!DeviceMgtAPIUtils.getDeviceAccessAuthorizationService().isUserAuthorized(
|
||||
new DeviceIdentifier(deviceId, deviceType),
|
||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
List<SortByField> sortByFields = new ArrayList<>();
|
||||
SortByField sortByField = new SortByField("timeStamp", SortType.ASC);
|
||||
sortByFields.add(sortByField);
|
||||
|
||||
// this is the user who initiates the request
|
||||
String authorizedUser = MultitenantUtils.getTenantAwareUsername(
|
||||
CarbonContext.getThreadLocalCarbonContext().getUsername());
|
||||
|
||||
try {
|
||||
String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
|
||||
int tenantId = DeviceMgtAPIUtils.getRealmService().getTenantManager().getTenantId(tenantDomain);
|
||||
AnalyticsDataAPI analyticsDataAPI = DeviceMgtAPIUtils.getAnalyticsDataAPI();
|
||||
List<SearchResultEntry> searchResults = analyticsDataAPI.search(tenantId, tableName, query,
|
||||
0,
|
||||
100,
|
||||
sortByFields);
|
||||
List<Event> events = getEventBeans(analyticsDataAPI, tenantId, tableName, new ArrayList<String>(),
|
||||
searchResults);
|
||||
return Response.ok().entity(events).build();
|
||||
} catch (AnalyticsException | UserStoreException e) {
|
||||
log.error("Failed to perform search on table: " + tableName + " : " + e.getMessage(), e);
|
||||
throw DeviceMgtUtil.buildBadRequestException(
|
||||
Constants.ErrorMessages.STATUS_BAD_REQUEST_MESSAGE_DEFAULT);
|
||||
}
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage());
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
|
||||
}
|
||||
}
|
||||
|
||||
private List<Event> getEventBeans(AnalyticsDataAPI analyticsDataAPI, int tenantId, String tableName,
|
||||
List<String> columns,
|
||||
List<SearchResultEntry> searchResults) throws AnalyticsException {
|
||||
List<String> ids = getIds(searchResults);
|
||||
List<String> requiredColumns = (columns == null || columns.isEmpty()) ? null : columns;
|
||||
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, requiredColumns, ids);
|
||||
List<Record> records = AnalyticsDataAPIUtil.listRecords(analyticsDataAPI, response);
|
||||
Map<String, Event> eventBeanMap = getEventBeanKeyedWithIds(records);
|
||||
return getSortedEventBeans(eventBeanMap, searchResults);
|
||||
}
|
||||
|
||||
private List<Event> getSortedEventBeans(Map<String, Event> eventBeanMap,
|
||||
List<SearchResultEntry> searchResults) {
|
||||
List<Event> sortedRecords = new ArrayList<>();
|
||||
for (SearchResultEntry entry : searchResults) {
|
||||
sortedRecords.add(eventBeanMap.get(entry.getId()));
|
||||
}
|
||||
return sortedRecords;
|
||||
}
|
||||
|
||||
private Map<String, Event> getEventBeanKeyedWithIds(List<Record> records) {
|
||||
Map<String, Event> eventBeanMap = new HashMap<>();
|
||||
for (Record record : records) {
|
||||
Event event = getEventBean(record);
|
||||
eventBeanMap.put(event.getId(), event);
|
||||
}
|
||||
return eventBeanMap;
|
||||
}
|
||||
|
||||
private List<String> getIds(List<SearchResultEntry> searchResults) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
if (searchResults != null) {
|
||||
for (SearchResultEntry resultEntry : searchResults) {
|
||||
ids.add(resultEntry.getId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static Event getEventBean(Record record) {
|
||||
Event eventBean = new Event();
|
||||
eventBean.setId(record.getId());
|
||||
eventBean.setTableName(record.getTableName());
|
||||
eventBean.setTimestamp(record.getTimestamp());
|
||||
eventBean.setValues(record.getValues());
|
||||
return eventBean;
|
||||
}
|
||||
}
|
||||
@ -173,7 +173,10 @@ public class GroupManagementServiceImpl implements GroupManagementService {
|
||||
.manageGroupSharing(groupId, userRoles);
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} catch (GroupManagementException e) {
|
||||
String msg = "Error occurred while managing group share.";
|
||||
String msg = "Error occurred while managing group share. ";
|
||||
if (e.getErrorMessage() != null){
|
||||
msg += e.getErrorMessage();
|
||||
}
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||
} catch (RoleDoesNotExistException e) {
|
||||
|
||||
@ -128,7 +128,7 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
|
||||
List<DeviceIdentifier> deviceIdentifiers = policyWrapper.getDeviceIdentifiers();
|
||||
if (deviceIdentifiers != null) {
|
||||
for (DeviceIdentifier id : deviceIdentifiers) {
|
||||
devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id));
|
||||
devices.add(DeviceMgtAPIUtils.getDeviceManagementService().getDevice(id, false));
|
||||
}
|
||||
}
|
||||
policy.setDevices(devices);
|
||||
@ -345,11 +345,11 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
|
||||
public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) {
|
||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||
List<Policy> policiesToUpdate = new ArrayList<>(priorityUpdatedPolicies.size());
|
||||
int i;
|
||||
for (i = 0; i < priorityUpdatedPolicies.size(); i++) {
|
||||
|
||||
for (PriorityUpdatedPolicyWrapper priorityUpdatedPolicy : priorityUpdatedPolicies) {
|
||||
Policy policyObj = new Policy();
|
||||
policyObj.setId(priorityUpdatedPolicies.get(i).getId());
|
||||
policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority());
|
||||
policyObj.setId(priorityUpdatedPolicy.getId());
|
||||
policyObj.setPriorityId(priorityUpdatedPolicy.getPriority());
|
||||
policiesToUpdate.add(policyObj);
|
||||
}
|
||||
boolean policiesUpdated;
|
||||
|
||||
@ -22,6 +22,8 @@ import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.CarbonConstants;
|
||||
import org.wso2.carbon.base.MultitenantConstants;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.RegistryType;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleList;
|
||||
@ -30,6 +32,9 @@ import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.FilteringUtil;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
|
||||
import org.wso2.carbon.registry.api.Registry;
|
||||
import org.wso2.carbon.registry.core.session.UserRegistry;
|
||||
import org.wso2.carbon.registry.resource.services.utils.ChangeRolePermissionsUtil;
|
||||
import org.wso2.carbon.user.api.*;
|
||||
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
|
||||
import org.wso2.carbon.user.mgt.UserRealmProxy;
|
||||
@ -296,6 +301,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
|
||||
}
|
||||
}
|
||||
userStoreManager.addRole(roleInfo.getRoleName(), roleInfo.getUsers(), permissions);
|
||||
authorizeRoleForAppmgt(roleInfo.getRoleName(), roleInfo.getPermissions());
|
||||
|
||||
//TODO fix what's returned in the entity
|
||||
return Response.created(new URI(API_BASE_PATH + "/" + URLEncoder.encode(roleInfo.getRoleName(), "UTF-8"))).
|
||||
@ -450,6 +456,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
|
||||
authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION);
|
||||
}
|
||||
}
|
||||
authorizeRoleForAppmgt(roleName, roleInfo.getPermissions());
|
||||
}
|
||||
//TODO: Need to send the updated role information in the entity back to the client
|
||||
return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " +
|
||||
@ -467,6 +474,59 @@ public class RoleManagementServiceImpl implements RoleManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* When presented with role and a set of permissions, if given role has permission to
|
||||
* perform mobile app management, said role will be given rights mobile app collection in the
|
||||
* governance registry.
|
||||
*
|
||||
* @param role
|
||||
* @param permissions
|
||||
* @return state of role update Operation
|
||||
*/
|
||||
private boolean authorizeRoleForAppmgt(String role, String[] permissions) {
|
||||
String permissionString =
|
||||
"ra^true:rd^false:wa^true:wd^false:da^true:dd^false:aa^true:ad^false";
|
||||
String resourcePath = "/_system/governance/mobileapps/";
|
||||
boolean appmPermAvailable = false;
|
||||
|
||||
if (permissions != null) {
|
||||
for (int i = 0; i < permissions.length; i++)
|
||||
switch (permissions[i]) {
|
||||
case "/permission/admin/manage/mobileapp":
|
||||
appmPermAvailable = true;
|
||||
break;
|
||||
case "/permission/admin/manage/mobileapp/create":
|
||||
appmPermAvailable = true;
|
||||
break;
|
||||
case "/permission/admin/manage/mobileapp/publish":
|
||||
appmPermAvailable = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (appmPermAvailable) {
|
||||
try {
|
||||
Registry registry = CarbonContext.getThreadLocalCarbonContext().
|
||||
getRegistry(RegistryType.SYSTEM_GOVERNANCE);
|
||||
ChangeRolePermissionsUtil.changeRolePermissions((UserRegistry) registry,
|
||||
resourcePath, role + ":" + permissionString);
|
||||
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
String msg = "Error while retrieving user registry in order to update permissions "
|
||||
+ "for resource : " + resourcePath;
|
||||
log.error(msg, e);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Mobile App Management permissions not selected, therefore role : " +
|
||||
role + " not given permission for registry collection : " + resourcePath);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{roleName}")
|
||||
@Override
|
||||
|
||||
@ -22,7 +22,9 @@ import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.wst.common.uriresolver.internal.util.URIEncoder;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
|
||||
@ -41,6 +43,7 @@ import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever;
|
||||
import org.wso2.carbon.identity.user.store.count.exception.UserStoreCounterException;
|
||||
import org.wso2.carbon.user.api.Permission;
|
||||
import org.wso2.carbon.user.api.RealmConfiguration;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
@ -304,13 +307,16 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage("User '" +
|
||||
username + "' does not exist for removal.").build()).build();
|
||||
}
|
||||
// Un-enroll all devices for the user
|
||||
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||
deviceManagementService.setStatus(username, EnrolmentInfo.Status.REMOVED);
|
||||
|
||||
userStoreManager.deleteUser(username);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("User '" + username + "' was successfully removed.");
|
||||
}
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} catch (UserStoreException e) {
|
||||
} catch (DeviceManagementException | UserStoreException e) {
|
||||
String msg = "Exception in trying to remove user by username: " + username;
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
@ -412,6 +418,15 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
public Response getUserCount() {
|
||||
try {
|
||||
UserStoreCountRetriever userStoreCountRetrieverService = DeviceMgtAPIUtils.getUserStoreCountRetrieverService();
|
||||
RealmConfiguration secondaryRealmConfiguration = CarbonContext.getThreadLocalCarbonContext().getUserRealm().
|
||||
getRealmConfiguration().getSecondaryRealmConfig();
|
||||
|
||||
if (secondaryRealmConfiguration != null) {
|
||||
if (!secondaryRealmConfiguration.isPrimary() && !Constants.JDBC_USERSTOREMANAGER.
|
||||
equals(secondaryRealmConfiguration.getUserStoreClass().getClass())) {
|
||||
return getUserCountViaUserStoreManager();
|
||||
}
|
||||
}
|
||||
if (userStoreCountRetrieverService != null) {
|
||||
long count = userStoreCountRetrieverService.countUsers("");
|
||||
if (count != -1) {
|
||||
@ -424,6 +439,10 @@ public class UserManagementServiceImpl implements UserManagementService {
|
||||
String msg =
|
||||
"Error occurred while retrieving the count of users that exist within the current tenant";
|
||||
log.error(msg, e);
|
||||
} catch (UserStoreException e) {
|
||||
String msg =
|
||||
"Error occurred while retrieving user stores.";
|
||||
log.error(msg, e);
|
||||
}
|
||||
return getUserCountViaUserStoreManager();
|
||||
}
|
||||
|
||||
@ -36,6 +36,8 @@ import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Path("/admin/authorization")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@ -43,6 +45,7 @@ import javax.ws.rs.core.Response;
|
||||
public class DeviceAccessAuthorizationAdminServiceImpl implements DeviceAccessAuthorizationAdminService {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceAccessAuthorizationAdminServiceImpl.class);
|
||||
private static final String DEFAULT_STAT_PERMISSION = "/permission/admin/device-mgt/device/realtime_analytics";
|
||||
|
||||
@POST
|
||||
@Override
|
||||
@ -90,4 +93,14 @@ public class DeviceAccessAuthorizationAdminServiceImpl implements DeviceAccessAu
|
||||
}
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/stat")
|
||||
@Override
|
||||
public Response isAuthorizedForStat(AuthorizationRequest authorizationRequest) {
|
||||
List<String> permissions = new ArrayList<>();
|
||||
permissions.add(DEFAULT_STAT_PERMISSION);
|
||||
authorizationRequest.setPermissions(permissions);
|
||||
return isAuthorized(authorizationRequest);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -37,13 +37,10 @@ import org.wso2.carbon.application.mgt.stub.upload.types.carbon.UploadedFileItem
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypePublisherAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceAnalyticsArtifactUploaderAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.registry.core.Registry;
|
||||
import org.wso2.carbon.registry.core.Resource;
|
||||
import org.wso2.carbon.registry.core.ResourceImpl;
|
||||
import org.wso2.carbon.registry.core.exceptions.RegistryException;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
@ -55,7 +52,6 @@ import javax.activation.DataHandler;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
@ -72,8 +68,8 @@ import java.security.cert.CertificateException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Path("/admin/devicetype")
|
||||
public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherAdminService {
|
||||
@Path("/admin/publish-artifact")
|
||||
public class DeviceAnalyticsArtifactUploaderAdminServiceImpl implements DeviceAnalyticsArtifactUploaderAdminService {
|
||||
|
||||
/**
|
||||
* required soap header for authorization
|
||||
@ -110,7 +106,7 @@ public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherA
|
||||
|
||||
private String tenantDomain;
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypePublisherAdminServiceImpl.class);
|
||||
private static final Log log = LogFactory.getLog(DeviceAnalyticsArtifactUploaderAdminServiceImpl.class);
|
||||
private static final String DEFAULT_RESOURCE_LOCATION = "/resources/devicetypes";
|
||||
private static final String CAR_FILE_LOCATION = CarbonUtils.getCarbonHome() + File.separator + "repository" +
|
||||
File.separator + "resources" + File.separator + "devicetypes";
|
||||
@ -178,6 +174,9 @@ public class DeviceTypePublisherAdminServiceImpl implements DeviceTypePublisherA
|
||||
publishDynamicEventReceivers(type, MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, receiverFileList);
|
||||
}
|
||||
}
|
||||
if (streamFileList != null) {
|
||||
publishDynamicEventStream(type, tenantDomain, streamFileList);
|
||||
}
|
||||
if (deployAnalyticsCapp(type, list)){
|
||||
return Response.status(Response.Status.BAD_REQUEST)
|
||||
.entity("\"Error, Artifact does not exist.\"").build();
|
||||
@ -25,6 +25,7 @@ import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.DeviceList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceManagementAdminService;
|
||||
@ -53,19 +54,22 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
|
||||
@QueryParam("offset") int offset,
|
||||
@QueryParam("limit") int limit) {
|
||||
RequestValidationUtil.validatePaginationParameters(offset, limit);
|
||||
int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(
|
||||
"Current logged in user is not authorized to perform this operation").build()).build();
|
||||
}
|
||||
try {
|
||||
int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED).entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(
|
||||
"Current logged in user is not authorized to perform this operation").build()).build();
|
||||
}
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
|
||||
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(DeviceMgtAPIUtils.getTenantId(tenantDomain));
|
||||
|
||||
PaginationRequest request = new PaginationRequest(offset, limit);
|
||||
request.setDeviceType(type);
|
||||
request.setDeviceName(name);
|
||||
List<Device> devices = DeviceMgtAPIUtils.getDeviceManagementService().
|
||||
getDevicesByNameAndType(name, type, offset, limit);
|
||||
getDevicesByNameAndType(request, false);
|
||||
|
||||
// setting up paginated result
|
||||
DeviceList deviceList = new DeviceList();
|
||||
|
||||
@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.InvalidConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.DeviceTypeManagementAdminService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.PUT;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Path("/admin/device-types")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class DeviceTypeManagementAdminServiceImpl implements DeviceTypeManagementAdminService {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeManagementAdminServiceImpl.class);
|
||||
private static final String DEVICETYPE_REGEX_PATTERN = "^[^ /]+$";
|
||||
private static final Pattern patternMatcher = Pattern.compile(DEVICETYPE_REGEX_PATTERN);
|
||||
|
||||
@GET
|
||||
@Override
|
||||
public Response getDeviceTypes() {
|
||||
try {
|
||||
List<DeviceType> deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceTypes();
|
||||
return Response.status(Response.Status.OK).entity(deviceTypes).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred while fetching the list of device types.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(
|
||||
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@POST
|
||||
public Response addDeviceType(DeviceType deviceType) {
|
||||
if (deviceType != null && deviceType.getDeviceTypeMetaDefinition() != null) {
|
||||
try {
|
||||
if (DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(deviceType.getName()) != null) {
|
||||
String msg = "Device type already available, " + deviceType.getName();
|
||||
return Response.status(Response.Status.CONFLICT).entity(msg).build();
|
||||
}
|
||||
Matcher matcher = patternMatcher.matcher(deviceType.getName());
|
||||
if(matcher.find()) {
|
||||
DeviceManagementService httpDeviceTypeManagerService =
|
||||
DeviceMgtAPIUtils.getDeviceTypeGeneratorService()
|
||||
.populateDeviceManagementService(deviceType.getName(),
|
||||
deviceType.getDeviceTypeMetaDefinition());
|
||||
DeviceMgtAPIUtils.getDeviceManagementService().registerDeviceType(httpDeviceTypeManagerService);
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity("Device type name does not match the pattern "
|
||||
+ DEVICETYPE_REGEX_PATTERN).build();
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred at server side while adding a device type.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(msg).build();
|
||||
} catch (InvalidConfigurationException e) {
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@PUT
|
||||
public Response updateDeviceType(DeviceType deviceType) {
|
||||
if (deviceType != null && deviceType.getDeviceTypeMetaDefinition() != null) {
|
||||
try {
|
||||
if (DeviceMgtAPIUtils.getDeviceManagementService().getDeviceType(deviceType.getName()) == null) {
|
||||
String msg = "Device type does not exist, " + deviceType.getName();
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
|
||||
}
|
||||
DeviceManagementService httpDeviceTypeManagerService = DeviceMgtAPIUtils.getDeviceTypeGeneratorService()
|
||||
.populateDeviceManagementService(deviceType.getName(), deviceType.getDeviceTypeMetaDefinition());
|
||||
DeviceMgtAPIUtils.getDeviceManagementService().registerDeviceType(httpDeviceTypeManagerService);
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} catch (DeviceManagementException e) {
|
||||
String msg = "Error occurred at server side while updating the device type.";
|
||||
log.error(msg, e);
|
||||
return Response.serverError().entity(msg).build();
|
||||
} catch (InvalidConfigurationException e) {
|
||||
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
|
||||
}
|
||||
} else {
|
||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -27,7 +27,10 @@ public class Constants {
|
||||
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 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 final class ErrorMessages {
|
||||
private ErrorMessages () { throw new AssertionError(); }
|
||||
|
||||
@ -18,24 +18,48 @@
|
||||
|
||||
package org.wso2.carbon.device.mgt.jaxrs.util;
|
||||
|
||||
import org.apache.axis2.AxisFault;
|
||||
import org.apache.axis2.client.Options;
|
||||
import org.apache.axis2.java.security.SSLProtocolSocketFactory;
|
||||
import org.apache.axis2.transport.http.HTTPConstants;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.httpclient.Header;
|
||||
import org.apache.commons.httpclient.protocol.Protocol;
|
||||
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
|
||||
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
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.PlatformConfigurationManagementService;
|
||||
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
|
||||
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
|
||||
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
|
||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.EventAttributeList;
|
||||
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
|
||||
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
|
||||
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
|
||||
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
|
||||
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
|
||||
import org.wso2.carbon.identity.user.store.count.AbstractCountRetrieverFactory;
|
||||
import org.wso2.carbon.identity.user.store.count.UserStoreCountRetriever;
|
||||
@ -54,7 +78,22 @@ import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import javax.cache.Cache;
|
||||
import javax.cache.Caching;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@ -64,7 +103,51 @@ public class DeviceMgtAPIUtils {
|
||||
|
||||
public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON_TYPE;
|
||||
private static final String NOTIFIER_FREQUENCY = "notifierFrequency";
|
||||
private static final String STREAM_DEFINITION_PREFIX = "iot.per.device.stream.";
|
||||
private static final String DEFAULT_HTTP_PROTOCOL = "https";
|
||||
private static final String EVENT_RECIEVER_CONTEXT = "EventReceiverAdminService/";
|
||||
private static final String EVENT_PUBLISHER_CONTEXT = "EventPublisherAdminService/";
|
||||
private static final String EVENT_STREAM_CONTEXT = "EventStreamAdminService/";
|
||||
private static final String EVENT_PERSISTENCE_CONTEXT = "EventStreamPersistenceAdminService/";
|
||||
private static final String AUTHORIZATION_HEADER = "Authorization";
|
||||
private static final String AUTHORIZATION_HEADER_VALUE = "Bearer";
|
||||
public static final String DAS_PORT = "${iot.analytics.https.port}";
|
||||
public static final String DAS_HOST_NAME = "${iot.analytics.host}";
|
||||
private static final String KEY_STORE_TYPE = "JKS";
|
||||
private static final String TRUST_STORE_TYPE = "JKS";
|
||||
private static final String KEY_MANAGER_TYPE = "SunX509"; //Default Key Manager Type
|
||||
private static final String TRUST_MANAGER_TYPE = "SunX509"; //Default Trust Manager Type
|
||||
private static final String SSLV3 = "SSLv3";
|
||||
private static final String EVENT_CACHE_MANAGER_NAME = "mqttAuthorizationCacheManager";
|
||||
private static final String EVENT_CACHE_NAME = "mqttAuthorizationCache";
|
||||
public static final String DAS_ADMIN_SERVICE_EP = "https://" + DAS_HOST_NAME + ":" + DAS_PORT + "/services/";
|
||||
private static SSLContext sslContext;
|
||||
|
||||
private static Log log = LogFactory.getLog(DeviceMgtAPIUtils.class);
|
||||
private static KeyStore keyStore;
|
||||
private static KeyStore trustStore;
|
||||
private static char[] keyStorePassword;
|
||||
|
||||
static {
|
||||
String keyStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Password");
|
||||
String trustStorePassword = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Password");
|
||||
String keyStoreLocation = ServerConfiguration.getInstance().getFirstProperty("Security.KeyStore.Location");
|
||||
String trustStoreLocation = ServerConfiguration.getInstance().getFirstProperty(
|
||||
"Security.TrustStore.Location");
|
||||
|
||||
//Call to load the keystore.
|
||||
try {
|
||||
loadKeyStore(keyStoreLocation, keyStorePassword);
|
||||
//Call to load the TrustStore.
|
||||
loadTrustStore(trustStoreLocation, trustStorePassword);
|
||||
//Create the SSL context with the loaded TrustStore/keystore.
|
||||
initSSLConnection();
|
||||
} catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException
|
||||
| UnrecoverableKeyException | KeyManagementException e) {
|
||||
log.error("publishing dynamic event receiver is failed due to " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
public static int getNotifierFrequency(PlatformConfiguration tenantConfiguration) {
|
||||
List<ConfigurationEntry> configEntryList = tenantConfiguration.getConfiguration();
|
||||
@ -113,6 +196,30 @@ public class DeviceMgtAPIUtils {
|
||||
return deviceManagementProviderService;
|
||||
}
|
||||
|
||||
public static DeviceTypeGeneratorService getDeviceTypeGeneratorService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
DeviceTypeGeneratorService deviceTypeGeneratorService =
|
||||
(DeviceTypeGeneratorService) ctx.getOSGiService(DeviceTypeGeneratorService.class, null);
|
||||
if (deviceTypeGeneratorService == null) {
|
||||
String msg = "DeviceTypeGeneratorService service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return deviceTypeGeneratorService;
|
||||
}
|
||||
|
||||
public static boolean isValidDeviceIdentifier(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
|
||||
Device device = getDeviceManagementService().getDevice(deviceIdentifier);
|
||||
if (device == null || device.getDeviceIdentifier() == null ||
|
||||
device.getDeviceIdentifier().isEmpty() || device.getEnrolmentInfo() == null) {
|
||||
return false;
|
||||
} else if (EnrolmentInfo.Status.REMOVED.equals(device.getEnrolmentInfo().getStatus())) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static UserStoreCountRetriever getUserStoreCountRetrieverService()
|
||||
throws UserStoreCounterException {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
@ -320,6 +427,28 @@ public class DeviceMgtAPIUtils {
|
||||
return gadgetDataService;
|
||||
}
|
||||
|
||||
public static GeoLocationProviderService getGeoService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
GeoLocationProviderService
|
||||
geoService = (GeoLocationProviderService) ctx.getOSGiService(GeoLocationProviderService.class, null);
|
||||
if (geoService == null) {
|
||||
throw new IllegalStateException("Geo Service has not been initialized.");
|
||||
}
|
||||
return geoService;
|
||||
}
|
||||
|
||||
public static AnalyticsDataAPI getAnalyticsDataAPI() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
AnalyticsDataAPI analyticsDataAPI =
|
||||
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
|
||||
if (analyticsDataAPI == null) {
|
||||
String msg = "Analytics api service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return analyticsDataAPI;
|
||||
}
|
||||
|
||||
public static int getTenantId(String tenantDomain) throws DeviceManagementException {
|
||||
RealmService realmService =
|
||||
(RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(RealmService.class, null);
|
||||
@ -344,4 +473,212 @@ public class DeviceMgtAPIUtils {
|
||||
return username;
|
||||
}
|
||||
|
||||
public static EventsPublisherService getEventPublisherService() {
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
EventsPublisherService eventsPublisherService =
|
||||
(EventsPublisherService) ctx.getOSGiService(EventsPublisherService.class, null);
|
||||
if (eventsPublisherService == null) {
|
||||
String msg = "Event Publisher service has not initialized.";
|
||||
log.error(msg);
|
||||
throw new IllegalStateException(msg);
|
||||
}
|
||||
return eventsPublisherService;
|
||||
}
|
||||
|
||||
public static String getStreamDefinition(String deviceType, String tenantDomain) {
|
||||
return STREAM_DEFINITION_PREFIX + tenantDomain + "." + deviceType.replace(" ", ".");
|
||||
}
|
||||
|
||||
public static EventStreamAdminServiceStub getEventStreamAdminServiceStub()
|
||||
throws AxisFault, UserStoreException, JWTClientException {
|
||||
EventStreamAdminServiceStub eventStreamAdminServiceStub = new EventStreamAdminServiceStub(
|
||||
Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_STREAM_CONTEXT));
|
||||
Options streamOptions = eventStreamAdminServiceStub._getServiceClient().getOptions();
|
||||
if (streamOptions == null) {
|
||||
streamOptions = new Options();
|
||||
}
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName() + "@" + tenantDomain;
|
||||
JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient();
|
||||
|
||||
String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64(
|
||||
jwtClient.getJwtToken(username).getBytes()));
|
||||
|
||||
List<Header> list = new ArrayList<>();
|
||||
Header httpHeader = new Header();
|
||||
httpHeader.setName(AUTHORIZATION_HEADER);
|
||||
httpHeader.setValue(authValue);
|
||||
list.add(httpHeader);//"https"
|
||||
streamOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
|
||||
streamOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
|
||||
, new Protocol(DEFAULT_HTTP_PROTOCOL
|
||||
, (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext)
|
||||
, Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT))));
|
||||
eventStreamAdminServiceStub._getServiceClient().setOptions(streamOptions);
|
||||
return eventStreamAdminServiceStub;
|
||||
}
|
||||
|
||||
public static EventReceiverAdminServiceStub getEventReceiverAdminServiceStub()
|
||||
throws AxisFault, UserStoreException, JWTClientException {
|
||||
EventReceiverAdminServiceStub receiverAdminServiceStub = new EventReceiverAdminServiceStub(
|
||||
Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_RECIEVER_CONTEXT));
|
||||
Options eventReciverOptions = receiverAdminServiceStub._getServiceClient().getOptions();
|
||||
if (eventReciverOptions == null) {
|
||||
eventReciverOptions = new Options();
|
||||
}
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName() + "@" + tenantDomain;
|
||||
JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient();
|
||||
|
||||
String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64(
|
||||
jwtClient.getJwtToken(username).getBytes()));
|
||||
|
||||
List<Header> list = new ArrayList<>();
|
||||
Header httpHeader = new Header();
|
||||
httpHeader.setName(AUTHORIZATION_HEADER);
|
||||
httpHeader.setValue(authValue);
|
||||
list.add(httpHeader);
|
||||
|
||||
eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
|
||||
eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
|
||||
, new Protocol(DEFAULT_HTTP_PROTOCOL
|
||||
, (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext)
|
||||
, Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT))));
|
||||
|
||||
receiverAdminServiceStub._getServiceClient().setOptions(eventReciverOptions);
|
||||
return receiverAdminServiceStub;
|
||||
}
|
||||
|
||||
public static EventPublisherAdminServiceStub getEventPublisherAdminServiceStub()
|
||||
throws AxisFault, UserStoreException, JWTClientException {
|
||||
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = new EventPublisherAdminServiceStub(
|
||||
Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_PUBLISHER_CONTEXT));
|
||||
Options eventReciverOptions = eventPublisherAdminServiceStub._getServiceClient().getOptions();
|
||||
if (eventReciverOptions == null) {
|
||||
eventReciverOptions = new Options();
|
||||
}
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName() + "@" + tenantDomain;
|
||||
JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient();
|
||||
|
||||
String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64(
|
||||
jwtClient.getJwtToken(username).getBytes()));
|
||||
|
||||
List<Header> list = new ArrayList<>();
|
||||
Header httpHeader = new Header();
|
||||
httpHeader.setName(AUTHORIZATION_HEADER);
|
||||
httpHeader.setValue(authValue);
|
||||
list.add(httpHeader);
|
||||
|
||||
eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
|
||||
eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
|
||||
, new Protocol(DEFAULT_HTTP_PROTOCOL
|
||||
, (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext)
|
||||
, Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT))));
|
||||
eventPublisherAdminServiceStub._getServiceClient().setOptions(eventReciverOptions);
|
||||
return eventPublisherAdminServiceStub;
|
||||
}
|
||||
|
||||
public static EventStreamPersistenceAdminServiceStub getEventStreamPersistenceAdminServiceStub()
|
||||
throws AxisFault, UserStoreException, JWTClientException {
|
||||
EventStreamPersistenceAdminServiceStub eventStreamPersistenceAdminServiceStub
|
||||
= new EventStreamPersistenceAdminServiceStub(
|
||||
Utils.replaceSystemProperty(DAS_ADMIN_SERVICE_EP + EVENT_PERSISTENCE_CONTEXT));
|
||||
Options eventReciverOptions = eventStreamPersistenceAdminServiceStub._getServiceClient().getOptions();
|
||||
if (eventReciverOptions == null) {
|
||||
eventReciverOptions = new Options();
|
||||
}
|
||||
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName() + "@" + tenantDomain;
|
||||
JWTClient jwtClient = DeviceMgtAPIUtils.getJWTClientManagerService().getJWTClient();
|
||||
|
||||
String authValue = AUTHORIZATION_HEADER_VALUE + " " + new String(Base64.encodeBase64(
|
||||
jwtClient.getJwtToken(username).getBytes()));
|
||||
|
||||
List<Header> list = new ArrayList<>();
|
||||
Header httpHeader = new Header();
|
||||
httpHeader.setName(AUTHORIZATION_HEADER);
|
||||
httpHeader.setValue(authValue);
|
||||
list.add(httpHeader);
|
||||
|
||||
eventReciverOptions.setProperty(HTTPConstants.HTTP_HEADERS, list);
|
||||
eventReciverOptions.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER
|
||||
, new Protocol(DEFAULT_HTTP_PROTOCOL
|
||||
, (ProtocolSocketFactory) new SSLProtocolSocketFactory(sslContext)
|
||||
, Integer.parseInt(Utils.replaceSystemProperty(DAS_PORT))));
|
||||
|
||||
eventStreamPersistenceAdminServiceStub._getServiceClient().setOptions(eventReciverOptions);
|
||||
return eventStreamPersistenceAdminServiceStub;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method is used to create the Cache that holds the event definition of the device type..
|
||||
* @return Cachemanager
|
||||
*/
|
||||
public static synchronized Cache<String, EventAttributeList> getDynamicEventCache() {
|
||||
return Caching.getCacheManagerFactory().getCacheManager(EVENT_CACHE_MANAGER_NAME).getCache(EVENT_CACHE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the keystore.
|
||||
*
|
||||
* @param keyStorePath - the path of the keystore
|
||||
* @param ksPassword - the keystore password
|
||||
*/
|
||||
private static void loadKeyStore(String keyStorePath, String ksPassword)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
InputStream fis = null;
|
||||
try {
|
||||
keyStorePassword = ksPassword.toCharArray();
|
||||
keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
|
||||
fis = new FileInputStream(keyStorePath);
|
||||
keyStore.load(fis, keyStorePassword);
|
||||
} finally {
|
||||
if (fis != null) {
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the trustore
|
||||
*
|
||||
* @param trustStorePath - the trustore path in the filesystem.
|
||||
* @param tsPassword - the truststore password
|
||||
*/
|
||||
private static void loadTrustStore(String trustStorePath, String tsPassword)
|
||||
throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
|
||||
|
||||
InputStream fis = null;
|
||||
try {
|
||||
trustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
|
||||
fis = new FileInputStream(trustStorePath);
|
||||
trustStore.load(fis, tsPassword.toCharArray());
|
||||
} finally {
|
||||
if (fis != null) {
|
||||
fis.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the SSL Context
|
||||
*/
|
||||
private static void initSSLConnection() throws NoSuchAlgorithmException, UnrecoverableKeyException,
|
||||
KeyStoreException, KeyManagementException {
|
||||
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
|
||||
keyManagerFactory.init(keyStore, keyStorePassword);
|
||||
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
|
||||
trustManagerFactory.init(trustStore);
|
||||
|
||||
// Create and initialize SSLContext for HTTPS communication
|
||||
sslContext = SSLContext.getInstance(SSLV3);
|
||||
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
|
||||
SSLContext.setDefault(sslContext);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -29,6 +29,7 @@
|
||||
<ref bean="deviceManagementAdminService"/>
|
||||
<ref bean="deviceAccessAuthorizationAdminService"/>
|
||||
<ref bean="deviceTypeManagementService"/>
|
||||
<ref bean="configurationManagementService"/>
|
||||
<ref bean="activityProviderService"/>
|
||||
<ref bean="notificationManagementService"/>
|
||||
<ref bean="policyManagementService"/>
|
||||
@ -36,11 +37,13 @@
|
||||
<ref bean="userManagementService"/>
|
||||
<ref bean="userManagementAdminService"/>
|
||||
<ref bean="groupManagementService"/>
|
||||
<ref bean="geoService"/>
|
||||
<ref bean="groupManagementAdminService"/>
|
||||
<ref bean="applicationManagementAdminService"/>
|
||||
<ref bean="deviceTypeManagementAdminService"/>
|
||||
<ref bean="deviceTypeManagementAdminService"/>
|
||||
<ref bean="deviceTypePublisherAdminServiceImpl"/>
|
||||
<ref bean="deviceAnalyticsArtifactUploaderAdminService"/>
|
||||
<ref bean="deviceEventManagementService"/>
|
||||
<ref bean="deviceAgentService"/>
|
||||
<ref bean="swaggerResource"/>
|
||||
</jaxrs:serviceBeans>
|
||||
<jaxrs:providers>
|
||||
@ -69,21 +72,24 @@
|
||||
</bean>
|
||||
|
||||
<bean id="deviceManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceManagementServiceImpl"/>
|
||||
<bean id="deviceTypeManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ConfigurationServiceImpl"/>
|
||||
<bean id="deviceTypeManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceImpl"/>
|
||||
<bean id="configurationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ConfigurationServiceImpl"/>
|
||||
<bean id="activityProviderService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.ActivityProviderServiceImpl"/>
|
||||
<bean id="notificationManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.NotificationManagementServiceImpl"/>
|
||||
<bean id="policyManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.PolicyManagementServiceImpl"/>
|
||||
<bean id="roleManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.RoleManagementServiceImpl"/>
|
||||
<bean id="userManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.UserManagementServiceImpl"/>
|
||||
<bean id="groupManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.GroupManagementServiceImpl"/>
|
||||
<bean id="geoService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.GeoLocationBasedServiceImpl"/>
|
||||
<bean id="deviceManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceManagementAdminServiceImpl"/>
|
||||
<bean id="applicationManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.ApplicationManagementAdminServiceImpl"/>
|
||||
<bean id="groupManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.GroupManagementAdminServiceImpl"/>
|
||||
<bean id="userManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.UserManagementAdminServiceImpl"/>
|
||||
<bean id="deviceTypeManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceImpl"/>
|
||||
<bean id="deviceTypeManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceTypeManagementAdminServiceImpl"/>
|
||||
<bean id="deviceAccessAuthorizationAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAccessAuthorizationAdminServiceImpl"/>
|
||||
<bean id="deviceTypePublisherAdminServiceImpl" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceTypePublisherAdminServiceImpl"/>
|
||||
|
||||
<bean id="deviceAnalyticsArtifactUploaderAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAnalyticsArtifactUploaderAdminServiceImpl"/>
|
||||
<bean id="deviceEventManagementService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceEventManagementServiceImpl"/>
|
||||
<bean id="deviceAgentService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceAgentServiceImpl"/>
|
||||
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
|
||||
|
||||
<!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>-->
|
||||
|
||||
@ -21,7 +21,7 @@
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>2.0.63-SNAPSHOT</version>
|
||||
<version>3.0.46-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
@ -50,6 +50,7 @@
|
||||
<Import-Package>
|
||||
javax.xml.bind.annotation; version="${javax.xml.bind.imp.pkg.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
|
||||
</Import-Package>
|
||||
</instructions>
|
||||
@ -68,6 +69,14 @@
|
||||
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-annotations</artifactId>
|
||||
</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>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -30,7 +30,7 @@ public class Device implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 1998101711L;
|
||||
|
||||
@ApiModelProperty(name = "id", value = "ID of the device in the WSO2 EMM device information database.",
|
||||
@ApiModelProperty(name = "id", value = "ID of the device in the device information database.",
|
||||
required = true)
|
||||
private int id;
|
||||
|
||||
|
||||
@ -56,7 +56,7 @@ public class DeviceIdentifier implements Serializable{
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type.toLowerCase();
|
||||
this.type = type.trim();
|
||||
}
|
||||
public String getId() {
|
||||
return id;
|
||||
|
||||
@ -61,6 +61,7 @@ public final class DeviceManagementConstants {
|
||||
private LicenseProperties() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static final String PROVIDER = "overview_provider";
|
||||
public static final String NAME = "overview_name";
|
||||
public static final String LANGUAGE = "overview_language";
|
||||
@ -76,6 +77,7 @@ public final class DeviceManagementConstants {
|
||||
private NotificationProperties() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static final String NOTIFICATION_CONFIG_FILE = "notification-messages.xml";
|
||||
}
|
||||
|
||||
@ -83,6 +85,7 @@ public final class DeviceManagementConstants {
|
||||
private DataBaseTypes() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static final String DB_TYPE_MYSQL = "MySQL";
|
||||
public static final String DB_TYPE_ORACLE = "Oracle";
|
||||
public static final String DB_TYPE_MSSQL = "Microsoft SQL Server";
|
||||
@ -91,4 +94,32 @@ public final class DeviceManagementConstants {
|
||||
public static final String DB_TYPE_POSTGRESQL = "PostgreSQL";
|
||||
}
|
||||
|
||||
public static final class GeoServices {
|
||||
private GeoServices() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static final String ALERT_TYPE_SPEED = "Speed";
|
||||
public static final String ALERT_TYPE_WITHIN = "Within";
|
||||
public static final String ALERT_TYPE_EXIT = "Exit";
|
||||
public static final String ALERT_TYPE_PROXIMITY = "Proximity";
|
||||
public static final String ALERT_TYPE_STATIONARY = "Stationery";
|
||||
public static final String ALERT_TYPE_TRAFFIC = "Traffic";
|
||||
public static final String REGISTRY_PATH_FOR_ALERTS = "/_system/governance/geo/alerts/";
|
||||
public static final String PROXIMITY_DISTANCE = "proximityDistance";
|
||||
public static final String PROXIMITY_TIME = "proximityTime";
|
||||
public static final String STATIONARY_NAME = "stationeryName";
|
||||
public static final String STATIONARY_TIME = "stationeryTime";
|
||||
public static final String FLUCTUATION_RADIUS = "fluctuationRadius";
|
||||
public static final String QUERY_NAME = "queryName";
|
||||
public static final String AREA_NAME = "areaName";
|
||||
|
||||
public static final String GEO_FENCE_GEO_JSON = "geoFenceGeoJSON";
|
||||
public static final String SPEED_ALERT_VALUE = "speedAlertValue";
|
||||
|
||||
public static final String DAS_PORT = "${iot.analytics.https.port}";
|
||||
public static final String DAS_HOST_NAME = "${iot.analytics.host}";
|
||||
public static final String DEFAULT_HTTP_PROTOCOL = "https";
|
||||
public static final String DAS_URL = DEFAULT_HTTP_PROTOCOL + "://" + DAS_HOST_NAME + ":" + DAS_PORT;
|
||||
}
|
||||
}
|
||||
|
||||
@ -37,8 +37,9 @@ public interface DeviceManager {
|
||||
|
||||
/**
|
||||
* Method to save platform specific Configuration.
|
||||
*
|
||||
* @param configuration - A Platform configuration object which needs to save
|
||||
* @return Returns the status of the operation
|
||||
* @throws DeviceManagementException If something goes wrong while saving the configuration.
|
||||
*/
|
||||
boolean saveConfiguration(PlatformConfiguration configuration) throws DeviceManagementException;
|
||||
|
||||
@ -46,6 +47,7 @@ public interface DeviceManager {
|
||||
* Method to get platform specific Configuration.
|
||||
*
|
||||
* @return Returns the platform specific tenant configurations
|
||||
* @throws DeviceManagementException If something goes wrong while fetching the configuration.
|
||||
*/
|
||||
PlatformConfiguration getConfiguration() throws DeviceManagementException;
|
||||
|
||||
@ -53,6 +55,7 @@ public interface DeviceManager {
|
||||
* Method to enrolling a particular device of type mobile, IoT, etc within CDM.
|
||||
*
|
||||
* @param device Metadata corresponding to the device being enrolled
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while enrolling a device
|
||||
*/
|
||||
boolean enrollDevice(Device device) throws DeviceManagementException;
|
||||
@ -61,6 +64,7 @@ public interface DeviceManager {
|
||||
* Method to modify the metadata corresponding to device enrollment.
|
||||
*
|
||||
* @param device Modified device enrollment related metadata
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while modify the enrollment of a
|
||||
* device
|
||||
*/
|
||||
@ -70,6 +74,7 @@ public interface DeviceManager {
|
||||
* Method to disenroll a particular device from CDM.
|
||||
*
|
||||
* @param deviceId Fully qualified device identifier
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while disenrolling a device
|
||||
*/
|
||||
boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException;
|
||||
@ -100,6 +105,7 @@ public interface DeviceManager {
|
||||
*
|
||||
* @param deviceId Fully qualified device identifier
|
||||
* @param status Indicates whether the device is active
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while updating the active status
|
||||
* of the device
|
||||
*/
|
||||
@ -127,6 +133,7 @@ public interface DeviceManager {
|
||||
*
|
||||
* @param deviceIdentifier identifier to identify the device
|
||||
* @param device Updated device information related data
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while updating the device info
|
||||
*/
|
||||
boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException;
|
||||
@ -136,6 +143,7 @@ public interface DeviceManager {
|
||||
*
|
||||
* @param deviceId Fully qualified device identifier
|
||||
* @param ownershipType Type of ownership
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws DeviceManagementException If some unusual behaviour is observed while setting the ownership
|
||||
* of the device
|
||||
*/
|
||||
|
||||
@ -0,0 +1,62 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common;
|
||||
|
||||
/**
|
||||
* This class holds plugin specific configurations for Device Status Monitoring Task.
|
||||
*/
|
||||
public class DeviceStatusTaskPluginConfig {
|
||||
|
||||
private boolean requireStatusMonitoring;
|
||||
private int frequency;
|
||||
private int idleTimeToMarkInactive;
|
||||
private int idleTimeToMarkUnreachable;
|
||||
|
||||
public int getFrequency() {
|
||||
return frequency;
|
||||
}
|
||||
|
||||
public void setFrequency(int frequency) {
|
||||
this.frequency = frequency;
|
||||
}
|
||||
|
||||
public int getIdleTimeToMarkInactive() {
|
||||
return idleTimeToMarkInactive;
|
||||
}
|
||||
|
||||
public void setIdleTimeToMarkInactive(int idleTimeToMarkInactive) {
|
||||
this.idleTimeToMarkInactive = idleTimeToMarkInactive;
|
||||
}
|
||||
|
||||
public int getIdleTimeToMarkUnreachable() {
|
||||
return idleTimeToMarkUnreachable;
|
||||
}
|
||||
|
||||
public void setIdleTimeToMarkUnreachable(int idleTimeToMarkUnreachable) {
|
||||
this.idleTimeToMarkUnreachable = idleTimeToMarkUnreachable;
|
||||
}
|
||||
|
||||
public boolean isRequireStatusMonitoring() {
|
||||
return requireStatusMonitoring;
|
||||
}
|
||||
|
||||
public void setRequireStatusMonitoring(boolean requireStatusMonitoring) {
|
||||
this.requireStatusMonitoring = requireStatusMonitoring;
|
||||
}
|
||||
}
|
||||
@ -16,10 +16,10 @@
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp;
|
||||
package org.wso2.carbon.device.mgt.common;
|
||||
|
||||
/**
|
||||
* This exception is thrown whether the xmpp configured with invalid configuration.
|
||||
* This exception is thrown when configured with invalid configuration.
|
||||
*/
|
||||
public class InvalidConfigurationException extends RuntimeException {
|
||||
|
||||
@ -29,6 +29,7 @@ public class PaginationRequest {
|
||||
private int rowCount;
|
||||
private int groupId;
|
||||
private String owner;
|
||||
private String ownerPattern;
|
||||
private String status;
|
||||
private String deviceType;
|
||||
private String deviceName;
|
||||
@ -120,4 +121,12 @@ public class PaginationRequest {
|
||||
public void setOwnerRole(String ownerRole) {
|
||||
this.ownerRole = ownerRole;
|
||||
}
|
||||
|
||||
public String getOwnerPattern() {
|
||||
return ownerPattern;
|
||||
}
|
||||
|
||||
public void setOwnerPattern(String ownerPattern) {
|
||||
this.ownerPattern = ownerPattern;
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,7 +39,7 @@ public interface ApplicationManager {
|
||||
* @param pageNumber Page number of the list.
|
||||
* @param size Number of items in one page.
|
||||
* @return The list of applications belongs to a domain.
|
||||
* @throws ApplicationManagementException
|
||||
* @throws ApplicationManagementException If something goes wrong
|
||||
*/
|
||||
|
||||
Application[] getApplications(String domain, int pageNumber, int size)
|
||||
@ -52,6 +52,7 @@ public interface ApplicationManager {
|
||||
* @param deviceId Device id of the device that the status belongs to.
|
||||
* @param application Application details of the app being updated.
|
||||
* @param status Installed/Uninstalled
|
||||
* @throws ApplicationManagementException If something goes wrong
|
||||
*/
|
||||
void updateApplicationStatus(DeviceIdentifier deviceId, Application application, String status)
|
||||
throws ApplicationManagementException;
|
||||
@ -62,6 +63,7 @@ public interface ApplicationManager {
|
||||
* @param deviceId Device id of the device that the status belongs to.
|
||||
* @param application Application details of the app being searched.
|
||||
* @return Status of the application on the device.
|
||||
* @throws ApplicationManagementException If something goes wrong
|
||||
*/
|
||||
String getApplicationStatus(DeviceIdentifier deviceId, Application application)
|
||||
throws ApplicationManagementException;
|
||||
|
||||
@ -55,8 +55,8 @@ public interface DeviceAccessAuthorizationService {
|
||||
* DeviceIdentifier list.
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and
|
||||
* unauthorized devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
|
||||
@ -68,8 +68,8 @@ public interface DeviceAccessAuthorizationService {
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param groupPermissions - Group Permissions
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and
|
||||
* unauthorized devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String[] groupPermissions)
|
||||
@ -95,8 +95,8 @@ public interface DeviceAccessAuthorizationService {
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param username - User name
|
||||
* @param groupPermissions - Group Permissions
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and
|
||||
* unauthorized devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username,
|
||||
@ -129,8 +129,8 @@ public interface DeviceAccessAuthorizationService {
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param username - Username of the user to be checked for authorization.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result object including the list of authorized devices and
|
||||
* unauthorized devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username) throws
|
||||
|
||||
@ -28,6 +28,7 @@ public interface PlatformConfigurationManagementService {
|
||||
*
|
||||
* @param platformConfiguration Operation to be added.
|
||||
* @param resourcePath Registry resource path.
|
||||
* @return A boolean indicating the status of the operation.
|
||||
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while adding the
|
||||
* configuration.
|
||||
*/
|
||||
@ -38,6 +39,7 @@ public interface PlatformConfigurationManagementService {
|
||||
* Method to retrieve the list of general tenant configurations.
|
||||
*
|
||||
* @param resourcePath Registry resource path.
|
||||
* @return Platform Configuration object.
|
||||
* @throws org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException If some unusual behaviour is observed while fetching the
|
||||
* operation list.
|
||||
*/
|
||||
|
||||
@ -0,0 +1,180 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.common.geo.service;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
/**
|
||||
* The Class Alert Bean.
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlRootElement(name = "alert")
|
||||
public class Alert {
|
||||
|
||||
/**
|
||||
* The parse data.
|
||||
*/
|
||||
@XmlElement(required = true, name = "parseData")
|
||||
private String parseData;
|
||||
|
||||
/**
|
||||
* The execution plan name.
|
||||
*/
|
||||
@XmlElement(required = true, name = "executionPlan")
|
||||
private String executionPlan;
|
||||
|
||||
/**
|
||||
* The custom name.
|
||||
*/
|
||||
@XmlElement(required = false, nillable = true, name = "customName")
|
||||
private String customName;
|
||||
|
||||
/**
|
||||
* The query name.
|
||||
*/
|
||||
@XmlElementWrapper(required = true, name = "queryName")
|
||||
private String queryName;
|
||||
|
||||
/**
|
||||
* The CEP action.
|
||||
*/
|
||||
@XmlElementWrapper(required = true, name = "cepAction")
|
||||
private String cepAction;
|
||||
|
||||
/**
|
||||
* The device id.
|
||||
*/
|
||||
@XmlElementWrapper(required = true, name = "deviceId")
|
||||
private String deviceId;
|
||||
|
||||
/**
|
||||
* The stationery time.
|
||||
*/
|
||||
@XmlElementWrapper(required = false, nillable = true, name = "stationeryTime")
|
||||
private String stationeryTime;
|
||||
|
||||
/**
|
||||
* The fluctuation radius.
|
||||
*/
|
||||
@XmlElementWrapper(required = false, nillable = true, name = "fluctuationRadius")
|
||||
private String fluctuationRadius;
|
||||
|
||||
/**
|
||||
* The proximity distance.
|
||||
*/
|
||||
@XmlElementWrapper(required = false, nillable = true, name = "proximityDistance")
|
||||
private String proximityDistance;
|
||||
|
||||
/**
|
||||
* The proximity time.
|
||||
*/
|
||||
@XmlElementWrapper(required = false, nillable = true, name = "proximityTime")
|
||||
private String proximityTime;
|
||||
|
||||
public String getParseData() {
|
||||
return parseData;
|
||||
}
|
||||
|
||||
public void setParseData(String parseData) {
|
||||
this.parseData = parseData;
|
||||
}
|
||||
|
||||
public String getExecutionPlan() {
|
||||
return executionPlan;
|
||||
}
|
||||
|
||||
public void setExecutionPlan(String executionPlan) {
|
||||
this.executionPlan = executionPlan;
|
||||
}
|
||||
|
||||
public String getCustomName() {
|
||||
return customName;
|
||||
}
|
||||
|
||||
public void setCustomName(String customName) {
|
||||
this.customName = customName;
|
||||
}
|
||||
|
||||
public String getQueryName() {
|
||||
return queryName;
|
||||
}
|
||||
|
||||
public void setQueryName(String queryName) {
|
||||
this.queryName = queryName;
|
||||
}
|
||||
|
||||
public String getCepAction() {
|
||||
return cepAction;
|
||||
}
|
||||
|
||||
public void setCepAction(String cepAction) {
|
||||
this.cepAction = cepAction;
|
||||
}
|
||||
|
||||
public String getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public void setDeviceId(String deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public String getStationeryTime() {
|
||||
return stationeryTime;
|
||||
}
|
||||
|
||||
public void setStationeryTime(String stationeryTime) {
|
||||
this.stationeryTime = stationeryTime;
|
||||
}
|
||||
|
||||
public String getFluctuationRadius() {
|
||||
return fluctuationRadius;
|
||||
}
|
||||
|
||||
public void setFluctuationRadius(String fluctuationRadius) {
|
||||
this.fluctuationRadius = fluctuationRadius;
|
||||
}
|
||||
|
||||
public String getProximityDistance() {
|
||||
return proximityDistance;
|
||||
}
|
||||
|
||||
public void setProximityDistance(String proximityDistance) {
|
||||
this.proximityDistance = proximityDistance;
|
||||
}
|
||||
|
||||
public String getProximityTime() {
|
||||
return proximityTime;
|
||||
}
|
||||
|
||||
public void setProximityTime(String proximityTime) {
|
||||
this.proximityTime = proximityTime;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.format(
|
||||
"{\"queryName\" : %s,\"customName\" : %s,\"cepAction\" : %s,\"deviceId\" : %s }",
|
||||
queryName, customName, cepAction, deviceId);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.common.geo.service;
|
||||
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The Class RecordBean.
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlRootElement(name = "event")
|
||||
public class Event {
|
||||
|
||||
/** The id. */
|
||||
@XmlElement(required = false, name = "id")
|
||||
private String id;
|
||||
|
||||
/** The table name. */
|
||||
@XmlElement(required = false, name = "tableName")
|
||||
private String tableName;
|
||||
|
||||
/** The timestamp. */
|
||||
@XmlElement(required = false, nillable = true, name = "timestamp")
|
||||
private long timestamp;
|
||||
|
||||
/** The values. */
|
||||
@XmlElementWrapper(required = true, name = "values")
|
||||
private Map<String, Object> values;
|
||||
|
||||
/**
|
||||
* Sets the table name.
|
||||
* @param tableName the new table name
|
||||
*/
|
||||
public void setTableName(String tableName) {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the values.
|
||||
* @param values the values
|
||||
*/
|
||||
public void setValues(Map<String, Object> values) {
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the timestamp.
|
||||
* @param timestamp the new timestamp
|
||||
*/
|
||||
public void setTimestamp(long timestamp) {
|
||||
this.timestamp = timestamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the id.
|
||||
* @param id the new id
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the id.
|
||||
* @return the id
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
/**
|
||||
* Gets the table name.
|
||||
* @return the table name
|
||||
*/
|
||||
public String getTableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the values.
|
||||
* @return the values
|
||||
*/
|
||||
public Map<String, Object> getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value.
|
||||
* @param name
|
||||
* the name
|
||||
* @return the value
|
||||
*/
|
||||
public Object getValue(String name) {
|
||||
return this.values.get(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the timestamp.
|
||||
* @return the timestamp
|
||||
*/
|
||||
public long getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(){
|
||||
List<String> valueList = new ArrayList<>();
|
||||
for (Map.Entry<String, Object> entry : values.entrySet()) {
|
||||
valueList.add(entry.getKey() + ":" + entry.getValue());
|
||||
}
|
||||
return valueList.toString();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,114 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.common.geo.service;
|
||||
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
/**
|
||||
* The Class GeoFence.
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlRootElement(name = "fence")
|
||||
public class GeoFence {
|
||||
|
||||
/** The geoJson. */
|
||||
@XmlElement(required = false, name = "geoJson")
|
||||
private String geoJson;
|
||||
|
||||
/** The queryName. */
|
||||
@XmlElement(required = false, name = "queryName")
|
||||
private String queryName;
|
||||
|
||||
/** The areaName. */
|
||||
@XmlElement(required = false, name = "areaName")
|
||||
private String areaName;
|
||||
|
||||
/** The createdTime. */
|
||||
@XmlElement(required = false, nillable = true, name = "createdTime")
|
||||
private long createdTime;
|
||||
|
||||
/** The stationaryTime. */
|
||||
@XmlElement(required = false, name = "stationaryTime")
|
||||
private String stationaryTime;
|
||||
|
||||
/** The fluctuationRadius. */
|
||||
@XmlElement(required = false, name = "fluctuationRadius")
|
||||
private String fluctuationRadius;
|
||||
|
||||
public String getGeoJson() {
|
||||
return geoJson;
|
||||
}
|
||||
|
||||
public void setGeoJson(String geoJson) {
|
||||
this.geoJson = geoJson;
|
||||
}
|
||||
|
||||
public String getQueryName() {
|
||||
return queryName;
|
||||
}
|
||||
|
||||
public void setQueryName(String queryName) {
|
||||
this.queryName = queryName;
|
||||
}
|
||||
|
||||
public String getAreaName() {
|
||||
return areaName;
|
||||
}
|
||||
|
||||
public void setAreaName(String areaName) {
|
||||
this.areaName = areaName;
|
||||
}
|
||||
|
||||
public long getCreatedTime() {
|
||||
return createdTime;
|
||||
}
|
||||
|
||||
public void setCreatedTime(long createdTime) {
|
||||
this.createdTime = createdTime;
|
||||
}
|
||||
|
||||
public void setStationaryTime(String stationaryTime) {
|
||||
this.stationaryTime = stationaryTime;
|
||||
}
|
||||
|
||||
public String getStationaryTime() {
|
||||
return stationaryTime;
|
||||
}
|
||||
|
||||
public void setFluctuationRadius(String fluctuationRadius) {
|
||||
this.fluctuationRadius = fluctuationRadius;
|
||||
}
|
||||
|
||||
public String getFluctuationRadius() {
|
||||
return fluctuationRadius;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "{\"geoJson\": " + geoJson +
|
||||
",\"queryName\": " + queryName +
|
||||
",\"areaName\":" + areaName +
|
||||
",\"createdTime\":" + createdTime +
|
||||
"}";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.common.geo.service;
|
||||
|
||||
/**
|
||||
* Custom exception class of Geo Service related operations.
|
||||
*/
|
||||
public class GeoLocationBasedServiceException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = -7151990041029070298L;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
public GeoLocationBasedServiceException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public GeoLocationBasedServiceException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public GeoLocationBasedServiceException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public GeoLocationBasedServiceException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public GeoLocationBasedServiceException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.geo.service;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* This represents the Geo service functionality which should be implemented by
|
||||
* required GeoServiceManagers.
|
||||
*/
|
||||
public interface GeoLocationProviderService {
|
||||
|
||||
List<GeoFence> getWithinAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
|
||||
List<GeoFence> getExitAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
|
||||
boolean createGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType)
|
||||
throws GeoLocationBasedServiceException;
|
||||
|
||||
boolean updateGeoAlert(Alert alert, DeviceIdentifier identifier, String alertType)
|
||||
throws GeoLocationBasedServiceException;
|
||||
|
||||
boolean removeGeoAlert(String alertType, DeviceIdentifier identifier, String queryName)
|
||||
throws GeoLocationBasedServiceException;
|
||||
|
||||
String getSpeedAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
|
||||
String getProximityAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
|
||||
List<GeoFence> getStationaryAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
|
||||
List<GeoFence> getTrafficAlerts(DeviceIdentifier identifier) throws GeoLocationBasedServiceException;
|
||||
}
|
||||
@ -32,6 +32,7 @@ public interface NotificationManagementService {
|
||||
/**
|
||||
* Method to add a notification to the database.
|
||||
*
|
||||
* @param deviceId - DeviceIdentifier of the device
|
||||
* @param notification - Notification to be added to database.
|
||||
* @return boolean status of the operation.
|
||||
* @throws NotificationManagementException
|
||||
@ -66,7 +67,7 @@ public interface NotificationManagementService {
|
||||
* Method to fetch all the notifications in the database.
|
||||
*
|
||||
* @return List of all Notifications in the database.
|
||||
* @throws NotificationManagementException
|
||||
* @throws NotificationManagementException if something goes wrong while fetching the Notifications.
|
||||
*
|
||||
*/
|
||||
List<Notification> getAllNotifications() throws NotificationManagementException;
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user