diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml
index 748108ec609..5ddd2eacf84 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.api/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
grafana-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml
index 45a1ab13817..b8f04c797d3 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.common/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
grafana-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml
index 15bce921232..020ebeec6b5 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
grafana-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/service/impl/GrafanaQueryServiceImpl.java b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/service/impl/GrafanaQueryServiceImpl.java
index b15ebed76ab..7af9acf5596 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/service/impl/GrafanaQueryServiceImpl.java
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/service/impl/GrafanaQueryServiceImpl.java
@@ -68,8 +68,23 @@ public class GrafanaQueryServiceImpl implements GrafanaQueryService {
int datasourceId = datasourceIdJson.getAsInt();
CacheManager cacheManager = CacheManager.getInstance();
String encodedQuery = cacheManager.getEncodedQueryCache().getIfPresent(rawSql);
- if (cacheManager.getEncodedQueryCache().getIfPresent(rawSql) != null) {
- queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
+ if (encodedQuery != null && !encodedQuery.isEmpty()) {
+ // Checks if the tenant ID in the cached query (encodedQuery) is matching the current tenant ID
+ // taken from Carbon Context and if it's not matching then the query is modified with the current
+ // tenant ID and then added to the cache
+ if (encodedQuery.contains(GrafanaConstants.ENCODED_QUERY_TENANT_ID_KEY)) {
+ String encodedQueryTenantId = GrafanaPreparedQueryBuilder.getEncodedQueryTenantId(encodedQuery);
+ boolean isMatchingTenantId = GrafanaPreparedQueryBuilder.isMatchingTenantId(encodedQueryTenantId);
+ if (isMatchingTenantId) {
+ queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
+ } else {
+ String modifiedEncodedQuery = GrafanaPreparedQueryBuilder.modifyEncodedQuery(encodedQuery);
+ CacheManager.getInstance().getEncodedQueryCache().put(rawSql, modifiedEncodedQuery);
+ queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, modifiedEncodedQuery);
+ }
+ } else {
+ queryObj.addProperty(GrafanaConstants.RAW_SQL_KEY, encodedQuery);
+ }
return;
}
Datasource datasource = cacheManager.getDatasourceAPICache().getIfPresent(datasourceId);
diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/sql/query/GrafanaPreparedQueryBuilder.java b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/sql/query/GrafanaPreparedQueryBuilder.java
index 8b8606dacb8..da14278cafc 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/sql/query/GrafanaPreparedQueryBuilder.java
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/sql/query/GrafanaPreparedQueryBuilder.java
@@ -38,6 +38,7 @@ public class GrafanaPreparedQueryBuilder {
private static final String VAR_PARAM_TEMPLATE = "$param";
private static final String GRAFANA_QUOTED_VAR_REGEX = "('\\$(\\d|\\w|_)+')|('\\$\\{.*?\\}')|(\"\\$(\\d|\\w|_)+\")|(\"\\$\\{.*?\\}\")";
private static final String GRAFANA_VAR_REGEX = "(\\$(\\d|\\w|_)+)|(\\$\\{.*?\\})";
+ private static final String ENCODED_QUERY_TENANT_ID_REGEX = "TENANT_ID\\s=\\s('[^']+'|-?[1-9]\\d*|0)";
public static PreparedQuery build(String queryTemplate, String rawQuery) throws QueryMisMatch {
@@ -125,6 +126,60 @@ public class GrafanaPreparedQueryBuilder {
return new PreparedQuery(preparedQueryBuilder.toString(), parameters);
}
+ /**
+ * Get the tenant ID used in the cached query with the matching regex pattern which are integers that
+ * may or may not have surrounding single quotes and could have a minus sign (e.g., '-1234')
+ * @param encodedQuery the cached query
+ * @return returns the tenant ID extracted from the cached query
+ */
+ public static String getEncodedQueryTenantId(String encodedQuery) {
+ Pattern pattern = Pattern.compile(ENCODED_QUERY_TENANT_ID_REGEX);
+ Matcher matcher = pattern.matcher(encodedQuery);
+ String encodedQueryTenantId = "";
+ while (matcher.find()) {
+ encodedQueryTenantId = matcher.group(1);
+ if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
+ break;
+ }
+ }
+ return unQuoteString(encodedQueryTenantId);
+ }
+
+ /**
+ * Checks if passed tenant ID is matching with tenant ID from Carbon Context
+ * @param encodedQueryTenantId the tenant ID
+ * @return true if tenant IDs match otherwise false
+ */
+ public static boolean isMatchingTenantId(String encodedQueryTenantId) {
+ if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
+ return GrafanaUtil.getTenantId() == Integer.parseInt(encodedQueryTenantId);
+ }
+ return false;
+ }
+
+ /**
+ * Modify the tenant ID used in the cached query to the current tenant ID taken from Carbon Context
+ * with the matching regex pattern which are integers that may or may not have surrounding single quotes and
+ * could have a minus sign (e.g., '-1234')
+ * @param encodedQuery the cached query
+ * @return returns the modified query with the current tenant ID
+ */
+ public static String modifyEncodedQuery(String encodedQuery) {
+ Pattern pattern = Pattern.compile(ENCODED_QUERY_TENANT_ID_REGEX);
+ Matcher matcher = pattern.matcher(encodedQuery);
+ StringBuffer stringBuffer = new StringBuffer(encodedQuery.length());
+ String encodedQueryTenantId = "";
+ while (matcher.find()) {
+ encodedQueryTenantId = matcher.group(1);
+ if (encodedQueryTenantId != null && !encodedQueryTenantId.isEmpty()) {
+ matcher.appendReplacement(stringBuffer, Matcher.quoteReplacement(
+ GrafanaConstants.ENCODED_QUERY_TENANT_ID_KEY + " " + GrafanaUtil.getTenantId()));
+ }
+ }
+ matcher.appendTail(stringBuffer);
+ return stringBuffer.toString();
+ }
+
private static String[] splitByComma(String str) {
// Using regex to avoid splitting by comma inside quotes
return str.split("(\\s|\\t)*,(\\s|\\t)*(?=(?:[^'\"]*['|\"][^'\"]*['|\"])*[^'\"]*$)");
@@ -194,5 +249,4 @@ public class GrafanaPreparedQueryBuilder {
private static String singleQuoteString(String str) {
return "'" + str + "'";
}
-
}
diff --git a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/util/GrafanaConstants.java b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/util/GrafanaConstants.java
index b8a33f8b329..0abed858b79 100644
--- a/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/util/GrafanaConstants.java
+++ b/components/analytics-mgt/grafana-mgt/io.entgra.analytics.mgt.grafana.proxy.core/src/main/java/io/entgra/analytics/mgt/grafana/proxy/core/util/GrafanaConstants.java
@@ -39,6 +39,7 @@ public class GrafanaConstants {
public static final int IFRAME_URL_DASHBOARD_UID_INDEX = 1;
public static final String TENANT_ID_VAR_NAME = "tenantId";
+ public static final String ENCODED_QUERY_TENANT_ID_KEY = "TENANT_ID =";
public static final String VAR_PREFIX = "$";
public static final String TENANT_ID_VAR = VAR_PREFIX + TENANT_ID_VAR_NAME;
public static final String QUERY_PARAM_VAR_PREFIX = "var-";
diff --git a/components/analytics-mgt/grafana-mgt/pom.xml b/components/analytics-mgt/grafana-mgt/pom.xml
index 781fa794dbe..17251bd9496 100644
--- a/components/analytics-mgt/grafana-mgt/pom.xml
+++ b/components/analytics-mgt/grafana-mgt/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
analytics-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/analytics-mgt/pom.xml b/components/analytics-mgt/pom.xml
index 21f5069a74c..9e3978e7176 100644
--- a/components/analytics-mgt/pom.xml
+++ b/components/analytics-mgt/pom.xml
@@ -3,7 +3,7 @@
carbon-devicemgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml
new file mode 100644
index 00000000000..6f1da82ae9a
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/pom.xml
@@ -0,0 +1,119 @@
+
+
+
+
+ apimgt-extensions
+ org.wso2.carbon.devicemgt
+ 5.0.22-SNAPSHOT
+
+
+ 4.0.0
+ io.entgra.device.mgt.core.apimgt.analytics.extension
+ bundle
+ Entgra - API mgt analytics extension
+ http://wso2.org
+
+
+
+ org.wso2.carbon
+ org.wso2.carbon.core
+
+
+ org.wso2.carbon
+ org.wso2.carbon.utils
+
+
+ org.apache.velocity
+ velocity
+ 1.7
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+
+
+ **/Abstract*
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ API Management Application Bundle
+ org.wso2.carbon.apimgt.application.extension.internal
+
+ io.entgra.device.mgt.core.apimgt.analytics.extension.dto,
+ org.apache.velocity,
+ org.apache.velocity.app,
+ org.apache.velocity.context,
+ org.wso2.carbon.utils;version="[4.6,5)"
+
+
+ io.entgra.device.mgt.core.apimgt.analytics.extension.*
+
+
+ scribe;scope=compile|runtime;inline=false;
+
+
+
+
+
+ org.jacoco
+ jacoco-maven-plugin
+
+ ${basedir}/target/coverage-reports/jacoco-unit.exec
+
+
+
+ jacoco-initialize
+
+ prepare-agent
+
+
+
+ jacoco-site
+ test
+
+ report
+
+
+ ${basedir}/target/coverage-reports/jacoco-unit.exec
+ ${basedir}/target/coverage-reports/site
+
+
+
+
+
+
+
+
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java
new file mode 100644
index 00000000000..fcd197bb0e0
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/AnalyticsArtifactsDeployer.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension;
+
+import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventPublisherData;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventReceiverData;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.EventStreamData;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.MetaData;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventPublisherDeployerException;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStreamDeployerException;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+
+import org.apache.velocity.runtime.RuntimeConstants;
+import org.wso2.carbon.utils.CarbonUtils;
+import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.UnsupportedEncodingException;
+
+public class AnalyticsArtifactsDeployer {
+
+ public static final String TEMPLATE_LOCATION = "repository" + File.separator + "resources" + File.separator + "iot-analytics-templates";
+ public static final String EVENT_STREAM_LOCATION = "eventstreams";
+ public static final String EVENT_PUBLISHER_LOCATION = "eventpublishers";
+ public static final String EVENT_RECEIVER_LOCATION = "eventreceivers";
+ public static final String EVENT_STREAM_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_stream.json.template";
+ public static final String EVENT_PUBLISHER_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_publisher.xml.template";
+ public static final String EVENT_RECEIVER_TEMPLATE = TEMPLATE_LOCATION + File.separator + "event_receiver.xml.template";
+
+
+ public void deployEventStream(EventStreamData eventStreamData, int tenantId) throws EventStreamDeployerException {
+ try {
+ VelocityEngine ve = new VelocityEngine();
+ ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
+ ve.init();
+ Template template = ve.getTemplate(EVENT_STREAM_TEMPLATE);
+
+ VelocityContext context = populateContextForEventStreams(eventStreamData);
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ String fileName = eventStreamData.getName() + "_" + eventStreamData.getVersion() + ".json";
+ String fileLocation = null;
+ if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
+ fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ + File.separator + "server" + File.separator + EVENT_STREAM_LOCATION + File.separator + fileName;
+ } else {
+ fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ + EVENT_STREAM_LOCATION + File.separator + fileName;
+ }
+
+ PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
+ printWriter.println(writer.toString());
+ printWriter.close();
+ } catch (FileNotFoundException | UnsupportedEncodingException e) {
+ throw new EventStreamDeployerException("Error while persisting event stream definition ", e);
+ }
+ }
+
+ public void deployEventPublisher(EventPublisherData eventPublisherData, int tenantId) throws EventPublisherDeployerException {
+ try {
+ VelocityEngine ve = new VelocityEngine();
+ ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
+ ve.init();
+ Template template = ve.getTemplate(EVENT_PUBLISHER_TEMPLATE);
+
+ VelocityContext context = populateContextForEventPublisher(eventPublisherData);
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ String fileName = eventPublisherData.getName() + ".xml";
+ String fileLocation = null;
+ if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
+ fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ + File.separator + "server" + File.separator + EVENT_PUBLISHER_LOCATION + File.separator + fileName;
+ } else {
+ fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ + EVENT_PUBLISHER_LOCATION + File.separator + fileName;
+ }
+
+ PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
+ printWriter.println(writer.toString());
+ printWriter.close();
+ } catch (FileNotFoundException | UnsupportedEncodingException e) {
+ throw new EventPublisherDeployerException("Error while persisting rdbms event publisher ", e);
+ }
+ }
+
+ public void deployEventReceiver(EventReceiverData eventReceiverData, int tenantId) throws EventReceiverDeployerException {
+ try {
+ VelocityEngine ve = new VelocityEngine();
+ ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, CarbonUtils.getCarbonHome());
+ ve.init();
+ Template template = ve.getTemplate(EVENT_RECEIVER_TEMPLATE);
+
+ VelocityContext context = populateContextForEventReceiver(eventReceiverData);
+ StringWriter writer = new StringWriter();
+ template.merge(context, writer);
+
+ String fileName = eventReceiverData.getName() + ".xml";
+ String fileLocation = null;
+ if (MultitenantConstants.SUPER_TENANT_ID == tenantId) {
+ fileLocation = CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + "deployment"
+ + File.separator + "server" + File.separator + EVENT_RECEIVER_LOCATION + File.separator + fileName;
+ } else {
+ fileLocation = CarbonUtils.getCarbonTenantsDirPath() + File.separator + tenantId + File.separator
+ + EVENT_RECEIVER_LOCATION + File.separator + fileName;
+ }
+
+ PrintWriter printWriter = new PrintWriter(fileLocation, "UTF-8");
+ printWriter.println(writer.toString());
+ printWriter.close();
+ } catch (FileNotFoundException | UnsupportedEncodingException e) {
+ throw new EventReceiverDeployerException("Error while persisting oauth mqtt event receiver ", e);
+ }
+ }
+
+ private VelocityContext populateContextForEventStreams(EventStreamData eventStreamData) {
+ VelocityContext context = new VelocityContext();
+ context.put("name", eventStreamData.getName());
+ context.put("version", eventStreamData.getVersion());
+ context.put("metaData",
+ eventStreamData.getMetaData() != null ? eventStreamData.getMetaData() : new MetaData("deviceId", "STRING"));
+ if (eventStreamData.getPayloadData() != null) {
+ context.put("properties", eventStreamData.getPayloadData());
+ }
+ return context;
+ }
+
+ private VelocityContext populateContextForEventPublisher(EventPublisherData eventPublisherData) {
+ VelocityContext context = new VelocityContext();
+
+ context.put("name", eventPublisherData.getName());
+ context.put("streamName", eventPublisherData.getStreamName());
+ context.put("streamVersion", eventPublisherData.getStreamVersion());
+ context.put("properties", eventPublisherData.getPropertyList());
+ context.put("eventAdapterType", eventPublisherData.getEventAdaptorType());
+ context.put("customMappingType", eventPublisherData.getCustomMappingType());
+
+ return context;
+ }
+
+ private VelocityContext populateContextForEventReceiver(EventReceiverData eventReceiverData) {
+ VelocityContext context = new VelocityContext();
+
+ context.put("name", eventReceiverData.getName());
+ context.put("streamName", eventReceiverData.getStreamName());
+ context.put("streamVersion", eventReceiverData.getStreamVersion());
+ context.put("properties", eventReceiverData.getPropertyList());
+ context.put("eventAdapterType", eventReceiverData.getEventAdapterType());
+ context.put("customMappingType", eventReceiverData.getCustomMappingType());
+
+ return context;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventPublisherData.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventPublisherData.java
new file mode 100644
index 00000000000..6d1620a5b90
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventPublisherData.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
+
+import java.util.List;
+
+public class EventPublisherData {
+ private String name;
+ private String streamVersion;
+ private String streamName;
+
+ private List propertyList;
+
+ private String eventAdaptorType;
+
+ private String customMappingType;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getStreamVersion() {
+ return streamVersion;
+ }
+
+ public void setStreamVersion(String streamVersion) {
+ this.streamVersion = streamVersion;
+ }
+
+ public String getStreamName() {
+ return streamName;
+ }
+
+ public void setStreamName(String streamName) {
+ this.streamName = streamName;
+ }
+
+ public List getPropertyList() {
+ return propertyList;
+ }
+
+ public void setPropertyList(List propertyList) {
+ this.propertyList = propertyList;
+ }
+
+ public String getEventAdaptorType() {
+ return eventAdaptorType;
+ }
+
+ public void setEventAdaptorType(String eventAdaptorType) {
+ this.eventAdaptorType = eventAdaptorType;
+ }
+
+ public String getCustomMappingType() {
+ return customMappingType;
+ }
+
+ public void setCustomMappingType(String customMappingType) {
+ this.customMappingType = customMappingType;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventReceiverData.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventReceiverData.java
new file mode 100644
index 00000000000..764229c55a3
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventReceiverData.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
+
+import java.util.List;
+
+public class EventReceiverData {
+
+ private String name;
+ private String streamVersion;
+ private String streamName;
+
+ private String eventAdapterType;
+
+ List propertyList;
+
+ private String customMappingType;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getStreamVersion() {
+ return streamVersion;
+ }
+
+ public void setStreamVersion(String streamVersion) {
+ this.streamVersion = streamVersion;
+ }
+
+ public String getStreamName() {
+ return streamName;
+ }
+
+ public void setStreamName(String streamName) {
+ this.streamName = streamName;
+ }
+
+ public String getEventAdapterType() {
+ return eventAdapterType;
+ }
+
+ public void setEventAdapterType(String eventAdapterType) {
+ this.eventAdapterType = eventAdapterType;
+ }
+
+ public List getPropertyList() {
+ return propertyList;
+ }
+
+ public void setPropertyList(List propertyList) {
+ this.propertyList = propertyList;
+ }
+
+ public String getCustomMappingType() {
+ return customMappingType;
+ }
+
+ public void setCustomMappingType(String customMappingType) {
+ this.customMappingType = customMappingType;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventStreamData.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventStreamData.java
new file mode 100644
index 00000000000..a80520bef4b
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/EventStreamData.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
+
+import java.util.List;
+
+public class EventStreamData {
+ private String name;
+ private String version;
+ private MetaData metaData;
+ private List payloadData;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public MetaData getMetaData() {
+ return metaData;
+ }
+
+ public void setMetaData(MetaData metaData) {
+ this.metaData = metaData;
+ }
+
+ public List getPayloadData() {
+ return payloadData;
+ }
+
+ public void setPayloadData(List payloadData) {
+ this.payloadData = payloadData;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/MetaData.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/MetaData.java
new file mode 100644
index 00000000000..ba77d04413b
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/MetaData.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
+
+public class MetaData {
+ String name;
+ String type;
+
+ public MetaData(String name, String type){
+ this.setName(name);
+ this.setType(type);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/Property.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/Property.java
new file mode 100644
index 00000000000..995cf2c5a85
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/dto/Property.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package io.entgra.device.mgt.core.apimgt.analytics.extension.dto;
+
+public class Property {
+ String name;
+ String value;
+
+ public Property(String name, String value){
+ this.setName(name);
+ this.setValue(value);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventPublisherDeployerException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventPublisherDeployerException.java
new file mode 100644
index 00000000000..2f924d0e7ba
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventPublisherDeployerException.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
+
+public class EventPublisherDeployerException extends Exception {
+
+ private static final long serialVersionUID = -3151279311929070299L;
+
+ public EventPublisherDeployerException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public EventPublisherDeployerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public EventPublisherDeployerException(String msg) {
+ super(msg);
+ }
+
+ public EventPublisherDeployerException() {
+ super();
+ }
+
+ public EventPublisherDeployerException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventReceiverDeployerException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventReceiverDeployerException.java
new file mode 100644
index 00000000000..3e0d49e0883
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventReceiverDeployerException.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
+
+public class EventReceiverDeployerException extends Exception {
+
+ private static final long serialVersionUID = -3151279311929070299L;
+
+ public EventReceiverDeployerException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public EventReceiverDeployerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public EventReceiverDeployerException(String msg) {
+ super(msg);
+ }
+
+ public EventReceiverDeployerException() {
+ super();
+ }
+
+ public EventReceiverDeployerException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventStreamDeployerException.java b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventStreamDeployerException.java
new file mode 100644
index 00000000000..1bba4c8cfe9
--- /dev/null
+++ b/components/apimgt-extensions/io.entgra.device.mgt.core.apimgt.analytics.extension/src/main/java/io/entgra/device/mgt/core/apimgt/analytics/extension/exception/EventStreamDeployerException.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.device.mgt.core.apimgt.analytics.extension.exception;
+
+public class EventStreamDeployerException extends Exception {
+
+ private static final long serialVersionUID = -3151279311929070298L;
+
+ public EventStreamDeployerException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public EventStreamDeployerException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public EventStreamDeployerException(String msg) {
+ super(msg);
+ }
+
+ public EventStreamDeployerException() {
+ super();
+ }
+
+ public EventStreamDeployerException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml
index 1783073616e..dec91246ab7 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.annotations/pom.xml
@@ -22,7 +22,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
index 95cc7dbf4ba..e72bcc5d3b4 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension.api/pom.xml
@@ -21,7 +21,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml
index e7a8040eef8..a7bcd9a3d09 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/pom.xml
@@ -22,7 +22,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java
index 68e4dcf1cdd..399ac015199 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.application.extension/src/main/java/org/wso2/carbon/apimgt/application/extension/APIManagementProviderServiceImpl.java
@@ -256,10 +256,14 @@ public class APIManagementProviderServiceImpl implements APIManagementProviderSe
keyManagerId = keyManagerConfigurationDTO.getUuid();
}
}
+ String applicationAccessTokenExpiryTime = "N/A";
+ if (!StringUtils.isEmpty(validityTime)) {
+ applicationAccessTokenExpiryTime = validityTime;
+ }
String jsonString = "{\"grant_types\":\"refresh_token,access_token," +
"urn:ietf:params:oauth:grant-type:saml2-bearer," +
"password,client_credentials,iwa:ntlm,urn:ietf:params:oauth:grant-type:jwt-bearer\"," +
- "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
+ "\"additionalProperties\":\"{\\\"application_access_token_expiry_time\\\":\\\"" + applicationAccessTokenExpiryTime + "\\\"," +
"\\\"user_access_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"refresh_token_expiry_time\\\":\\\"N\\/A\\\"," +
"\\\"id_token_expiry_time\\\":\\\"N\\/A\\\"}\"," +
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml
index 03da5eb4af3..6af6ec43bfa 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/pom.xml
@@ -3,7 +3,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
4.0.0
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java
index 5054e2220d0..7d45e71ef60 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/DCRRequest.java
@@ -40,6 +40,9 @@ public class DCRRequest {
@XmlElement
private boolean isSaasApp;
+ @XmlElement
+ private int validityPeriod;
+
public String getApplicationName() {
return applicationName;
}
@@ -87,4 +90,12 @@ public class DCRRequest {
public void setIsSaasApp(boolean saasApp) {
isSaasApp = saasApp;
}
+
+ public int getValidityPeriod() {
+ return validityPeriod;
+ }
+
+ public void setValidityPeriod(int validityPeriod) {
+ this.validityPeriod = validityPeriod;
+ }
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java
index dfd6af295ab..3775d6d9f17 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerService.java
@@ -46,5 +46,6 @@ public interface KeyManagerService {
@FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username,
- @FormParam("password") String password);
+ @FormParam("password") String password,
+ @FormParam("validityPeriod") int validityPeriod);
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java
index 961951f8659..59d93912b04 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension.api/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/api/KeyManagerServiceImpl.java
@@ -51,7 +51,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
try {
KeyMgtService keyMgtService = new KeyMgtServiceImpl();
DCRResponse resp = keyMgtService.dynamicClientRegistration(dcrRequest.getApplicationName(), dcrRequest.getUsername(),
- dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp());
+ dcrRequest.getGrantTypes(), dcrRequest.getCallBackUrl(), dcrRequest.getTags(), dcrRequest.getIsSaasApp(), dcrRequest.getValidityPeriod());
return Response.status(Response.Status.CREATED).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@@ -69,7 +69,8 @@ public class KeyManagerServiceImpl implements KeyManagerService {
@FormParam("assertion") String assertion,
@FormParam("admin_access_token") String admin_access_token,
@FormParam("username") String username,
- @FormParam("password") String password) {
+ @FormParam("password") String password,
+ @FormParam("validityPeriod") int validityPeriod) {
try {
if (basicAuthHeader == null) {
String msg = "Invalid credentials. Make sure your API call is invoked with a Basic Authorization header.";
@@ -80,7 +81,7 @@ public class KeyManagerServiceImpl implements KeyManagerService {
TokenResponse resp = keyMgtService.generateAccessToken(
new TokenRequest(encodedClientCredentials.split(":")[0],
encodedClientCredentials.split(":")[1], refreshToken, scope,
- grantType, assertion, admin_access_token, username, password));
+ grantType, assertion, admin_access_token, username, password, validityPeriod));
return Response.status(Response.Status.OK).entity(gson.toJson(resp)).build();
} catch (KeyMgtException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml
index 1d064a5656e..c122a2f8028 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/pom.xml
@@ -3,7 +3,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java
index 860b267161f..6bddd30d0b0 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/TokenRequest.java
@@ -29,8 +29,10 @@ public class TokenRequest {
private String username;
private String password;
+ private int validityPeriod;
+
public TokenRequest(String clientId, String clientSecret, String refreshToken, String scope, String grantType,
- String assertion, String admin_access_token, String username, String password) {
+ String assertion, String admin_access_token, String username, String password, int validityPeriod) {
this.clientId = clientId;
this.clientSecret = clientSecret;
this.refreshToken = refreshToken;
@@ -40,6 +42,7 @@ public class TokenRequest {
this.admin_access_token = admin_access_token;
this.username = username;
this.password = password;
+ this.validityPeriod = validityPeriod;
}
public String getClientId() {
@@ -113,4 +116,12 @@ public class TokenRequest {
public void setPassword(String password) {
this.password = password;
}
+
+ public int getValidityPeriod() {
+ return validityPeriod;
+ }
+
+ public void setValidityPeriod(int validityPeriod) {
+ this.validityPeriod = validityPeriod;
+ }
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java
index a9aa2d346a4..4e185d2f4da 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtService.java
@@ -39,7 +39,7 @@ public interface KeyMgtService {
* @throws KeyMgtException if any error occurs during DCR process
*/
DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
- String[] tags, boolean isSaasApp) throws KeyMgtException;
+ String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException;
/***
* This method will handle the access token requests
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java
index 4640fc9a575..1a564e1246c 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.keymgt.extension/src/main/java/org/wso2/carbon/apimgt/keymgt/extension/service/KeyMgtServiceImpl.java
@@ -77,7 +77,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
String subTenantUserUsername, subTenantUserPassword, keyManagerName, msg = null;
public DCRResponse dynamicClientRegistration(String clientName, String owner, String grantTypes, String callBackUrl,
- String[] tags, boolean isSaasApp) throws KeyMgtException {
+ String[] tags, boolean isSaasApp, int validityPeriod) throws KeyMgtException {
if (owner == null) {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
@@ -105,13 +105,13 @@ public class KeyMgtServiceImpl implements KeyMgtService {
kmConfig = getKeyManagerConfig();
if (KeyMgtConstants.SUPER_TENANT.equals(tenantDomain)) {
- OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags);
+ OAuthApplication dcrApplication = createOauthApplication(clientName, kmConfig.getAdminUsername(), tags, validityPeriod);
return new DCRResponse(dcrApplication.getClientId(), dcrApplication.getClientSecret());
} else {
// super-tenant admin dcr and token generation
OAuthApplication superTenantOauthApp = createOauthApplication(
KeyMgtConstants.RESERVED_OAUTH_APP_NAME_PREFIX + KeyMgtConstants.SUPER_TENANT,
- kmConfig.getAdminUsername(), null);
+ kmConfig.getAdminUsername(), null, validityPeriod);
String superAdminAccessToken = createAccessToken(superTenantOauthApp);
// create new key manager for the tenant, under super-tenant space
@@ -133,7 +133,7 @@ public class KeyMgtServiceImpl implements KeyMgtService {
createUserIfNotExists(subTenantUserUsername, subTenantUserPassword);
// DCR for the requesting user
- OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags);
+ OAuthApplication dcrApplication = createOauthApplication(clientName, owner, tags, validityPeriod);
String requestingUserAccessToken = createAccessToken(dcrApplication);
// get application id
@@ -167,7 +167,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
case "client_credentials":
appTokenPayload = new FormBody.Builder()
.add("grant_type", "client_credentials")
- .add("scope", tokenRequest.getScope()).build();
+ .add("scope", tokenRequest.getScope())
+ .add("validityPeriod", String.valueOf(tokenRequest.getValidityPeriod())).build();
break;
case "password":
appTokenPayload = new FormBody.Builder()
@@ -322,8 +323,8 @@ public class KeyMgtServiceImpl implements KeyMgtService {
* @return @{@link OAuthApplication} OAuth application object
* @throws KeyMgtException if any error occurs while creating response object
*/
- private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags) throws KeyMgtException {
- String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags);
+ private OAuthApplication createOauthApplication (String clientName, String owner, String[] tags, int validityPeriod) throws KeyMgtException {
+ String oauthAppCreationPayloadStr = createOauthAppCreationPayload(clientName, owner, tags, validityPeriod);
RequestBody oauthAppCreationPayload = RequestBody.Companion.create(oauthAppCreationPayloadStr, JSON);
kmConfig = getKeyManagerConfig();
String dcrEndpoint = kmConfig.getServerUrl() + KeyMgtConstants.DCR_ENDPOINT;
@@ -442,11 +443,12 @@ public class KeyMgtServiceImpl implements KeyMgtService {
}
}
- private String createOauthAppCreationPayload(String clientName, String owner, String[] tags) {
+ private String createOauthAppCreationPayload(String clientName, String owner, String[] tags, int validityPeriod) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("applicationName", clientName);
jsonObject.put("username", owner);
jsonObject.put("tags", tags);
+ jsonObject.put("validityPeriod", validityPeriod);
return jsonObject.toString();
}
diff --git a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
index 20525b51422..1db744409df 100644
--- a/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
+++ b/components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/pom.xml
@@ -22,7 +22,7 @@
apimgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/apimgt-extensions/pom.xml b/components/apimgt-extensions/pom.xml
index c09f37daa44..93638f60da4 100644
--- a/components/apimgt-extensions/pom.xml
+++ b/components/apimgt-extensions/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
@@ -39,6 +39,7 @@
org.wso2.carbon.apimgt.annotations
org.wso2.carbon.apimgt.keymgt.extension
org.wso2.carbon.apimgt.keymgt.extension.api
+ io.entgra.device.mgt.core.apimgt.analytics.extension
diff --git a/components/application-mgt/io.entgra.application.mgt.addons/pom.xml b/components/application-mgt/io.entgra.application.mgt.addons/pom.xml
index 26c496befd0..5b018fa6912 100644
--- a/components/application-mgt/io.entgra.application.mgt.addons/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.addons/pom.xml
@@ -20,7 +20,7 @@
application-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.api/pom.xml
index 93e0c641b49..34e852922e5 100644
--- a/components/application-mgt/io.entgra.application.mgt.api/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.api/pom.xml
@@ -22,7 +22,7 @@
application-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.common/pom.xml b/components/application-mgt/io.entgra.application.mgt.common/pom.xml
index 54ddd889e8f..ec5c4ecbc85 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.common/pom.xml
@@ -21,7 +21,7 @@
org.wso2.carbon.devicemgt
application-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java
index 82e78096b14..dcc63be3b3f 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationManager.java
@@ -17,7 +17,7 @@
package io.entgra.application.mgt.common.services;
import io.entgra.application.mgt.common.ApplicationType;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.dto.ApplicationDTO;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
import org.apache.cxf.jaxrs.ext.multipart.Attachment;
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationStorageManager.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationStorageManager.java
index 39be94cc3de..9c8ffb06547 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationStorageManager.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/services/ApplicationStorageManager.java
@@ -22,6 +22,7 @@ import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.application.mgt.common.exception.ApplicationStorageManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import java.io.InputStream;
import java.util.List;
@@ -121,4 +122,14 @@ public interface ApplicationStorageManager {
* @throws ApplicationStorageManagementException throws if an error occurs when accessing the file.
*/
InputStream getFileStream(String deviceType, String tenantDomain) throws ApplicationStorageManagementException;
+
+ /**
+ * Useful to generate MD5 string of {@link InputStream}
+ *
+ * @param inputStream {@link InputStream}
+ * @return md5 string of provided input stream
+ *
+ * @throws StorageManagementException if errors while generating md5 string
+ */
+ String getMD5(InputStream inputStream) throws StorageManagementException;
}
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java
index 566e67d5d5a..e2d49c5dcb5 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/CustomAppReleaseWrapper.java
@@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java
index 6fdb22dc80e..e73f948a1ed 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/EntAppReleaseWrapper.java
@@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java
index 3fdbdab0b45..011f0837536 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/PublicAppReleaseWrapper.java
@@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java
index 3d0a343c74d..41fed3a76b7 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java
+++ b/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/wrapper/WebAppReleaseWrapper.java
@@ -16,7 +16,7 @@
*/
package io.entgra.application.mgt.common.wrapper;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
diff --git a/components/application-mgt/io.entgra.application.mgt.core/pom.xml b/components/application-mgt/io.entgra.application.mgt.core/pom.xml
index 2c882ffc3cb..79bfb74e1e0 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.core/pom.xml
@@ -21,7 +21,7 @@
org.wso2.carbon.devicemgt
application-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Artifacts.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Artifacts.java
index 8e745c77eb1..43721fbe37a 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Artifacts.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/config/Artifacts.java
@@ -28,7 +28,7 @@ public class Artifacts {
private String imageLocation;
private String binaryLocation;
- @XmlElement(name = "ImageLocation", required = true)
+ @XmlElement(name = "ImageLocationType", required = true)
public String getImageLocation() {
return imageLocation;
}
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java
index 9ad0b9d4c0c..bfce4e31fa0 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/dao/impl/application/SQLServerApplicationDAOImpl.java
@@ -94,6 +94,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
|| StringUtils.isNotEmpty(filter.getAppReleaseType())) {
sql += "LEFT JOIN AP_APP_RELEASE ON AP_APP.ID = AP_APP_RELEASE.AP_APP_ID ";
}
+ sql += "WHERE AP_APP.TENANT_ID = ? ";
if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) {
sql += "AND AP_APP.TYPE = ? ";
}
@@ -128,7 +129,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
sql += filter.getSortBy() +" ";
}
if (filter.getLimit() != -1) {
- sql += "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ";
+ sql += "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY ";
}
sql += ") AS app_data ON app_data.ID = AP_APP.ID "
+ "LEFT JOIN ("
@@ -145,6 +146,7 @@ public class SQLServerApplicationDAOImpl extends GenericApplicationDAOImpl {
Connection conn = this.getDBConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
int paramIndex = 1;
+ stmt.setInt(paramIndex++, tenantId);
if (StringUtils.isNotEmpty(filter.getAppType()) && !Constants.ALL.equalsIgnoreCase(filter.getAppType())) {
stmt.setString(paramIndex++, filter.getAppType());
}
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java
index 157d73241df..98a50e427a1 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationManagerImpl.java
@@ -17,7 +17,7 @@
package io.entgra.application.mgt.core.impl;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.core.dao.SPApplicationDAO;
import io.entgra.application.mgt.core.util.ApplicationManagementUtil;
import org.apache.commons.codec.digest.DigestUtils;
@@ -86,7 +86,7 @@ import io.entgra.application.mgt.core.internal.DataHolder;
import io.entgra.application.mgt.core.lifecycle.LifecycleStateManager;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import io.entgra.application.mgt.core.util.Constants;
-import io.entgra.application.mgt.core.util.StorageManagementUtil;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
@@ -402,7 +402,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private void validateRemoveAppFromFavouritesRequest(int appId) throws ApplicationManagementException {
if (!isFavouriteApp(appId)) {
- String msg = "Provided appId " + appId + " is not a favourite app in order remove from favourites";
+ String msg = "Provided application is not a favourite app in order remove from favourites";
throw new BadRequestException(msg);
}
}
@@ -417,11 +417,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
try {
getApplication(appId);
} catch (NotFoundException e) {
- String msg = " No application exists for the provided appId " + appId;
+ String msg = "Requested application does not exists for add to favourites.";
throw new BadRequestException(msg);
}
if (isFavouriteApp(appId)) {
- String msg = "Provided appId " + appId + " is already a favourite app";
+ String msg = "Requested application is already in favourites list.";
throw new BadRequestException(msg);
}
}
@@ -600,16 +600,17 @@ public class ApplicationManagerImpl implements ApplicationManager {
*/
private String generateMD5OfApp(ApplicationArtifact applicationArtifact, byte[] content) throws ApplicationManagementException {
try {
- String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content));
+ ApplicationStorageManager applicationStorageManager = APIUtil.getApplicationStorageManager();
+ String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
log.error(msg);
throw new ApplicationManagementException(msg);
}
return md5OfApp;
- } catch( ApplicationStorageManagementException e) {
+ } catch(StorageManagementException e) {
String msg = "Error occurred while generating md5sum value of " + applicationArtifact.getInstallerName();
- log.error(msg);
+ log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
}
@@ -689,7 +690,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new ApplicationManagementException(msg);
}
- String md5OfApp = StorageManagementUtil.getMD5(new ByteArrayInputStream(content));
+ String md5OfApp = applicationStorageManager.getMD5(new ByteArrayInputStream(content));
if (md5OfApp == null) {
String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ applicationReleaseDTO.getUuid();
@@ -708,6 +709,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationStorageManager
.uploadReleaseArtifact(applicationReleaseDTO, deviceType, binaryDuplicate, tenantId);
}
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while md5sum value retrieving process: application UUID "
+ + applicationReleaseDTO.getUuid();
+ log.error(msg, e);
+ throw new ApplicationStorageManagementException(msg, e);
} catch (DBConnectionException e) {
String msg = "Error occurred when getting database connection for verifying app release data.";
log.error(msg, e);
@@ -752,7 +758,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
- String md5OfApp = StorageManagementUtil.getMD5(binaryClone);
+ String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for application "
@@ -818,6 +824,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
}
}
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while retrieving md5sum value from the binary file for application "
+ + "release UUID " + applicationReleaseDTO.getUuid();
+ log.error(msg, e);
+ throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: " + applicationArtifact
.getInstallerName();
@@ -1494,7 +1505,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
- String msg = "Error occured when getting, either application tags or application categories";
+ String msg = "Error occurred when getting, either application tags or application categories";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@@ -1768,7 +1779,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (LifeCycleManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while deleting life-cycle state data of application releases of the application"
+ String msg = "Error occurred while deleting life-cycle state data of application releases of the application"
+ " which has application ID: " + applicationDTO.getId();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -1885,7 +1896,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occurred while verifying whether application relase has an subscription or "
+ String msg = "Error occurred while verifying whether application release has an subscription or "
+ "not. Application release UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -1934,7 +1945,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.commitDBTransaction();
} catch (DBConnectionException e) {
String msg =
- "Error occured when getting DB connection to update image artifacts of the application release "
+ "Error occurred when getting DB connection to update image artifacts of the application release "
+ "which has uuid " + uuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -1946,13 +1957,13 @@ public class ApplicationManagerImpl implements ApplicationManager {
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
String msg =
- "Error occured while getting application release data for updating image artifacts of the application release uuid "
+ "Error occurred while getting application release data for updating image artifacts of the application release uuid "
+ uuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while updating image artifacts of the application release uuid " + uuid + ".";
+ String msg = "Error occurred while updating image artifacts of the application release uuid " + uuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg , e);
} finally {
@@ -1981,7 +1992,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new BadRequestException(msg);
}
} catch (DeviceManagementException e) {
- String msg = "Error occured while getting supported device types in IoTS";
+ String msg = "Error occurred while getting supported device types in IoTS";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
}
@@ -2023,16 +2034,16 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while getting/updating APPM DB for updating application Installer.";
+ String msg = "Error occurred while getting/updating APPM DB for updating application Installer.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) {
- String msg = "Error occured while starting the transaction to update application release artifact which has "
+ String msg = "Error occurred while starting the transaction to update application release artifact which has "
+ "application uuid " + releaseUuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "Error occured when getting DB connection to update application release artifact of the "
+ String msg = "Error occurred when getting DB connection to update application release artifact of the "
+ "application release uuid " + releaseUuid + ".";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -2043,7 +2054,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when updating application installer.";
+ String msg = "Error occurred when updating application installer.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@@ -2162,9 +2173,9 @@ public class ApplicationManagerImpl implements ApplicationManager {
ConnectionManagerUtil.closeDBConnection();
}
}
-
+
public ApplicationRelease changeLifecycleState(ApplicationReleaseDTO applicationReleaseDTO, LifecycleChanger lifecycleChanger) throws ApplicationManagementException {
-
+
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (lifecycleChanger == null || StringUtils.isEmpty(lifecycleChanger.getAction())) {
@@ -2172,7 +2183,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
-
+
try{
if (lifecycleStateManager
.isValidStateChange(applicationReleaseDTO.getCurrentState(), lifecycleChanger.getAction(), userName,
@@ -2241,7 +2252,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when getting existing categories or when inserting new application categories.";
+ String msg = "Error occurred when getting existing categories or when inserting new application categories.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} finally {
@@ -2563,7 +2574,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
applicationDAO.deleteApplicationTag(tag.getId(), applicationDTO.getId(), tenantId);
ConnectionManagerUtil.commitDBTransaction();
} else {
- String msg = "Tag " + tagName + " is not an application tag. Application ID: " + appId;
+ String msg = "Tag " + tagName + " is not an application tag. Application name: " + applicationDTO.getName();
log.error(msg);
throw new BadRequestException(msg);
}
@@ -2771,7 +2782,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
.collect(Collectors.toList());
} else {
String msg = "Tag list is either null or empty. In order to add new tags for application which has "
- + "application ID: " + appId +", tag list should be a list of Stings. Therefore please "
+ + "application name: " + applicationDTO.getName() +", tag list should be a list of Stings. Therefore please "
+ "verify the payload.";
log.error(msg);
throw new BadRequestException(msg);
@@ -2877,11 +2888,17 @@ public class ApplicationManagerImpl implements ApplicationManager {
@Override
public void updateCategory(String oldCategoryName, String newCategoryName) throws ApplicationManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ if (StringUtils.isEmpty(oldCategoryName) || StringUtils.isEmpty(newCategoryName)) {
+ String msg = "Either old category name or new category name contains empty/null value. Hence please verify the "
+ + "request.";
+ log.error(msg);
+ throw new BadRequestException(msg);
+ }
try {
ConnectionManagerUtil.beginDBTransaction();
CategoryDTO category = applicationDAO.getCategoryForCategoryName(oldCategoryName, tenantId);
if (category == null){
- String msg = "Couldn't found a category for tag name " + oldCategoryName + ".";
+ String msg = "Couldn't found a category for category name " + oldCategoryName + ".";
log.error(msg);
throw new NotFoundException(msg);
}
@@ -2893,7 +2910,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (TransactionManagementException e) {
- String msg = "Database access error is occurred when updating categiry.";
+ String msg = "Database access error is occurred when updating category.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
@@ -3068,11 +3085,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when updating Ent Application release of UUID: " + releaseUuid;
+ String msg = "Error occurred when updating Ent Application release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
- String msg = "Error occured when updating application release artifact in the file system. Ent App release "
+ String msg = "Error occurred when updating application release artifact in the file system. Ent App release "
+ "UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -3137,11 +3154,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when updating public app release of UUID: " + releaseUuid;
+ String msg = "Error occurred when updating public app release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
- String msg = "Error occured when updating public app release artifact in the file system. Public app "
+ String msg = "Error occurred when updating public app release artifact in the file system. Public app "
+ "release UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -3202,11 +3219,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when updating web app release for web app Release UUID: " + releaseUuid;
+ String msg = "Error occurred when updating web app release for web app Release UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
- String msg = "Error occured when updating web app release artifact in the file system. Web app "
+ String msg = "Error occurred when updating web app release artifact in the file system. Web app "
+ "release UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -3254,7 +3271,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
try {
byte[] content = IOUtils.toByteArray(applicationArtifact.getInstallerStream());
try (ByteArrayInputStream binaryClone = new ByteArrayInputStream(content)) {
- String md5OfApp = StorageManagementUtil.getMD5(binaryClone);
+ String md5OfApp = applicationStorageManager.getMD5(binaryClone);
if (md5OfApp == null) {
String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ "application release UUID " + applicationReleaseDTO.get().getUuid();
@@ -3300,6 +3317,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
}
}
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while retrieving md5sum value from the binary file for "
+ + "application release UUID " + applicationReleaseDTO.get().getUuid();
+ log.error(msg, e);
+ throw new ApplicationStorageManagementException(msg, e);
} catch (IOException e) {
String msg = "Error occurred when getting byte array of binary file. Installer name: "
+ applicationArtifact.getInstallerName();
@@ -3327,11 +3349,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new ApplicationManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured when updating Ent Application release of UUID: " + releaseUuid;
+ String msg = "Error occurred when updating Ent Application release of UUID: " + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (ResourceManagementException e) {
- String msg = "Error occured when updating application release artifact in the file system. Ent App release "
+ String msg = "Error occurred when updating application release artifact in the file system. Ent App release "
+ "UUID:" + releaseUuid;
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -3434,6 +3456,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
String userName = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
int deviceTypeId = -1;
String appName;
+ int appNameLength = 20;
List appCategories;
List unrestrictedRoles;
@@ -3445,6 +3468,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
+ if (appName.length() > appNameLength) {
+ String msg = "Application name must be less than or equal to 20 characters in length.";
+ log.error(msg);
+ throw new BadRequestException(msg);
+ }
appCategories = applicationWrapper.getCategories();
if (appCategories == null) {
String msg = "Application category can't be null.";
@@ -3477,6 +3505,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
+ if (appName.length() > appNameLength) {
+ String msg = "Application name must be less than or equal to 20 characters in length.";
+ log.error(msg);
+ throw new BadRequestException(msg);
+ }
appCategories = webAppWrapper.getCategories();
if (appCategories == null) {
String msg = "Web Clip category can't be null.";
@@ -3510,6 +3543,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
+ if (appName.length() > appNameLength) {
+ String msg = "Application name must be less than or equal to 20 characters in length.";
+ log.error(msg);
+ throw new BadRequestException(msg);
+ }
appCategories = publicAppWrapper.getCategories();
if (appCategories == null) {
String msg = "Application category can't be null.";
@@ -3542,6 +3580,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
log.error(msg);
throw new BadRequestException(msg);
}
+ if (appName.length() > appNameLength) {
+ String msg = "Application name must be less than or equal to 20 characters in length.";
+ log.error(msg);
+ throw new BadRequestException(msg);
+ }
appCategories = customAppWrapper.getCategories();
if (appCategories == null) {
String msg = "Application category can't be null.";
@@ -3684,7 +3727,7 @@ public class ApplicationManagerImpl implements ApplicationManager {
throw new BadRequestException(msg);
}
if (StringUtils.isEmpty(webAppReleaseWrapper.getUrl())) {
- String msg = "URL should't be null for the application release creating request for application type "
+ String msg = "URL shouldn't be null for the application release creating request for application type "
+ "WEB_CLIP";
log.error(msg);
throw new BadRequestException(msg);
@@ -3864,11 +3907,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
- String msg = "Error occured while updating app subscription status of the device.";
+ String msg = "Error occurred while updating app subscription status of the device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "Error occurred while obersving the database connection to update aoo subscription status of "
+ String msg = "Error occurred while observing the database connection to update aoo subscription status of "
+ "device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
@@ -3895,11 +3938,11 @@ public class ApplicationManagerImpl implements ApplicationManager {
}
ConnectionManagerUtil.commitDBTransaction();
} catch (ApplicationManagementDAOException e) {
- String msg = "Error occured while updating app subscription status of the device.";
+ String msg = "Error occurred while updating app subscription status of the device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "Error occurred while obersving the database connection to update aoo subscription status of "
+ String msg = "Error occurred while observing the database connection to update aoo subscription status of "
+ "device.";
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationStorageManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationStorageManagerImpl.java
index 91e3f4579b4..09b7b208487 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationStorageManagerImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ApplicationStorageManagerImpl.java
@@ -19,6 +19,7 @@ package io.entgra.application.mgt.core.impl;
import com.dd.plist.NSDictionary;
import net.dongliu.apk.parser.bean.ApkMeta;
+import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -31,12 +32,13 @@ import io.entgra.application.mgt.common.services.ApplicationStorageManager;
import io.entgra.application.mgt.core.exception.ParsingException;
import io.entgra.application.mgt.core.util.ArtifactsParser;
import io.entgra.application.mgt.core.util.Constants;
-import io.entgra.application.mgt.core.util.StorageManagementUtil;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
+import org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil;
import java.io.*;
import java.util.List;
-import static io.entgra.application.mgt.core.util.StorageManagementUtil.saveFile;
+import static org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil.saveFile;
/**
* This class contains the default concrete implementation of ApplicationStorage Management.
@@ -112,6 +114,11 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ApplicationStorageManagementException(msg, e);
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while uploading image artifacts. UUID: "
+ + applicationReleaseDTO.getUuid();
+ log.error(msg, e);
+ throw new ResourceManagementException(msg, e);
}
}
@@ -159,6 +166,11 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
+ applicationReleaseDTO.getUuid();
log.error(msg, e);
throw new ResourceManagementException( msg, e);
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while uploading image artifacts. UUID: "
+ + applicationReleaseDTO.getUuid();
+ log.error(msg, e);
+ throw new ResourceManagementException(msg, e);
}
}
@@ -286,4 +298,15 @@ public class ApplicationStorageManagerImpl implements ApplicationStorageManager
throw new ApplicationStorageManagementException(msg);
}
}
+
+ @Override
+ public String getMD5(InputStream inputStream) throws StorageManagementException {
+ try {
+ return DigestUtils.md5Hex(inputStream);
+ } catch (IOException e) {
+ String msg = "IO Exception occurred while trying to get the md5sum value of application";
+ log.error(msg, e);
+ throw new StorageManagementException(msg, e);
+ }
+ }
}
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ReviewManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ReviewManagerImpl.java
index 323149d8941..facbfa4163a 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ReviewManagerImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/ReviewManagerImpl.java
@@ -224,7 +224,7 @@ public class ReviewManagerImpl implements ReviewManager {
throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while verifying whether application release is exists or not for UUID " + uuid;
+ String msg = "Error occurred while verifying whether application release is exists or not for UUID " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@@ -360,7 +360,7 @@ public class ReviewManagerImpl implements ReviewManager {
return null;
} catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while getting reviewTmp with reviewTmp id " + reviewId + ".";
+ String msg = "Error occurred while getting reviewTmp with reviewTmp id " + reviewId + ".";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
@@ -393,11 +393,11 @@ public class ReviewManagerImpl implements ReviewManager {
}
return getReviewTree(this.reviewDAO.getAllReleaseReviews(releaseDTO.getId(), request, tenantId));
} catch (ReviewManagementDAOException e) {
- String msg = "Error occured while getting all reviews for application uuid: " + uuid;
+ String msg = "Error occurred while getting all reviews for application uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg ="Error occured while getting the DB connection to get all reviews for application release which"
+ String msg ="Error occurred while getting the DB connection to get all reviews for application release which"
+ " has UUID " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@@ -423,12 +423,12 @@ public class ReviewManagerImpl implements ReviewManager {
ConnectionManagerUtil.openDBConnection();
return getReviewTree(this.reviewDAO.getAllActiveAppReviews(applicationReleaseIds, request, tenantId));
} catch (ReviewManagementDAOException e) {
- String msg = "Error occured while getting all reviews for application which has an "
+ String msg = "Error occurred while getting all reviews for application which has an "
+ "application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "Error occured while getting the DB connection to get app app reviews.";
+ String msg = "Error occurred while getting the DB connection to get app app reviews.";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@@ -458,12 +458,12 @@ public class ReviewManagerImpl implements ReviewManager {
}
return getReviewTree(reviewDtos);
} catch (ReviewManagementDAOException e) {
- String msg = "Error occured while getting all " + username + "'s reviews for application which has an "
+ String msg = "Error occurred while getting all " + username + "'s reviews for application which has an "
+ "application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "Error occured while getting DB connection to get all " + username + "'s reviews for "
+ String msg = "Error occurred while getting DB connection to get all " + username + "'s reviews for "
+ "application which has an application release of uuid: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@@ -486,7 +486,7 @@ public class ReviewManagerImpl implements ReviewManager {
.collect(Collectors.toList());
} catch (DBConnectionException e) {
String msg =
- "Error occured while getting the DB connection to get application which has application release"
+ "Error occurred while getting the DB connection to get application which has application release"
+ " of UUID: " + uuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@@ -526,7 +526,7 @@ public class ReviewManagerImpl implements ReviewManager {
paginationResult.setRecordsTotal(numOfReviews);
return paginationResult;
} catch (ReviewManagementDAOException e) {
- String msg = "Error occured while getting all reply comments for given review list";
+ String msg = "Error occurred while getting all reply comments for given review list";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
}
@@ -635,11 +635,11 @@ public class ReviewManagerImpl implements ReviewManager {
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
ConnectionManagerUtil.rollbackDBTransaction();
- String msg = "Error occured while deleting review with review id " + reviewId + ".";
+ String msg = "Error occurred while deleting review with review id " + reviewId + ".";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (TransactionManagementException e) {
- String msg = "Error occurred when handleing transaction to delete application reviews.";
+ String msg = "Error occurred when handling transaction to delete application reviews.";
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} finally {
@@ -663,16 +663,16 @@ public class ReviewManagerImpl implements ReviewManager {
return rating;
} catch (ApplicationManagementDAOException e) {
String msg =
- "Error occured while getting the rating value of the application release uuid: " + appReleaseUuid;
+ "Error occurred while getting the rating value of the application release uuid: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (DBConnectionException e) {
- String msg = "DB Connection error occured while getting the rating value of the application release uuid: "
+ String msg = "DB Connection error occurred while getting the rating value of the application release uuid: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
- String msg = "Error occured while getting all rating values for the application release UUID: "
+ String msg = "Error occurred while getting all rating values for the application release UUID: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
@@ -704,18 +704,18 @@ public class ReviewManagerImpl implements ReviewManager {
return rating;
} catch (DBConnectionException e) {
String msg =
- "DB Connection error occured while getting app rating of the application which has application "
+ "DB Connection error occurred while getting app rating of the application which has application "
+ "release for uuid: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ApplicationManagementDAOException e) {
- String msg = "Error occured while getting the application DTO for the application release uuid: "
+ String msg = "Error occurred while getting the application DTO for the application release uuid: "
+ appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
} catch (ReviewManagementDAOException e) {
String msg =
- "Error occured while getting all rating values of application which has the application release "
+ "Error occurred while getting all rating values of application which has the application release "
+ "for UUID: " + appReleaseUuid;
log.error(msg, e);
throw new ReviewManagementException(msg, e);
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java
index 8382f428b59..bd0afe85a61 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SPApplicationManagerImpl.java
@@ -49,6 +49,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import java.util.ArrayList;
import java.util.List;
@@ -327,9 +328,7 @@ public class SPApplicationManagerImpl implements SPApplicationManager {
* @throws BadRequestException if url is invalid
*/
private void validateIdentityServerUrl(String url) throws BadRequestException {
- String[] schemes = {"http","https"};
- UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
- if (!urlValidator.isValid(url)) {
+ if (!HttpUtil.isHttpUrlValid(url)) {
String msg = "Identity server url is not a valid url";
log.error(msg);
throw new BadRequestException(msg);
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SubscriptionManagerImpl.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SubscriptionManagerImpl.java
index 74d423a8732..a2cb17b079b 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SubscriptionManagerImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/impl/SubscriptionManagerImpl.java
@@ -367,14 +367,14 @@ public class SubscriptionManagerImpl implements SubscriptionManager {
try {
device = DataHolder.getInstance().getDeviceManagementService().getDevice(deviceIdentifier, false);
if (device == null) {
- String msg = "Invalid device identifier is received and couldn't find an deveice for the requested "
+ String msg = "Invalid device identifier is received and couldn't find an device for the requested "
+ "device identifier. Device UUID: " + deviceIdentifier.getId() + " Device Type: "
+ deviceIdentifier.getType();
log.error(msg);
throw new BadRequestException(msg);
}
} catch (DeviceManagementException e) {
- String msg = "Error occured while getting device data for given device identifier.Device UUID: "
+ String msg = "Error occurred while getting device data for given device identifier.Device UUID: "
+ deviceIdentifier.getId() + " Device Type: " + deviceIdentifier.getType();
log.error(msg, e);
throw new ApplicationManagementException(msg, e);
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java
index f0ef6c4b299..bb7d65eceda 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/ApplicationManagementUtil.java
@@ -18,13 +18,11 @@
package io.entgra.application.mgt.core.util;
import io.entgra.application.mgt.common.ApplicationArtifact;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.FileDataHolder;
import io.entgra.application.mgt.common.dto.ApplicationDTO;
-import io.entgra.application.mgt.common.dto.ApplicationReleaseDTO;
import io.entgra.application.mgt.common.exception.ApplicationManagementException;
import io.entgra.application.mgt.common.exception.RequestValidatingException;
-import io.entgra.application.mgt.common.exception.ResourceManagementException;
import io.entgra.application.mgt.common.services.SPApplicationManager;
import io.entgra.application.mgt.common.wrapper.ApplicationWrapper;
import io.entgra.application.mgt.common.wrapper.CustomAppReleaseWrapper;
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/StorageManagementUtilTest.java b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/StorageManagementUtilTest.java
index 08644a5fab4..afbe689b978 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/StorageManagementUtilTest.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/StorageManagementUtilTest.java
@@ -23,7 +23,8 @@ import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
-import io.entgra.application.mgt.core.util.StorageManagementUtil;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
+import org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil;
import java.io.File;
import java.io.FileInputStream;
@@ -47,14 +48,14 @@ public class StorageManagementUtilTest {
public void testCreateArtifactDirectory() {
try {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
- } catch (ResourceManagementException e) {
+ } catch (StorageManagementException e) {
e.printStackTrace();
Assert.fail("Directory creation failed.");
}
}
@Test
- public void testSaveFile() throws IOException, ResourceManagementException {
+ public void testSaveFile() throws IOException, ResourceManagementException, StorageManagementException {
StorageManagementUtil.createArtifactDirectory(TEMP_FOLDER);
InputStream apk = new FileInputStream(APK_FILE);
StorageManagementUtil.saveFile(apk, TEMP_FOLDER + APK_FILE_NAME);
@@ -65,7 +66,7 @@ public class StorageManagementUtilTest {
}
@AfterMethod
- public void deleteFileTest() throws IOException, ResourceManagementException {
+ public void deleteFileTest() throws IOException, StorageManagementException {
File file = new File(TEMP_FOLDER);
StorageManagementUtil.delete(file);
if (file.exists()) {
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java
index baccaed9996..8ab3915a28a 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java
+++ b/components/application-mgt/io.entgra.application.mgt.core/src/test/java/io/entgra/application/mgt/core/management/ApplicationManagementTest.java
@@ -42,19 +42,16 @@ import io.entgra.application.mgt.core.impl.ApplicationManagerImpl;
import io.entgra.application.mgt.core.internal.DataHolder;
import io.entgra.application.mgt.core.util.ConnectionManagerUtil;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.core.common.util.FileUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeVersion;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderServiceImpl;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
public class ApplicationManagementTest extends BaseTestCase {
diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml
index f246e392fa1..b866b041e24 100644
--- a/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/pom.xml
@@ -22,7 +22,7 @@
application-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java
index bfc2c7ed61e..1580219385b 100644
--- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java
+++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/ApplicationManagementPublisherAPI.java
@@ -17,7 +17,7 @@
*/
package io.entgra.application.mgt.publisher.api.services;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java
index 3048cc8f1f1..df98b1ee8ac 100644
--- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/ApplicationManagementPublisherAPIImpl.java
@@ -18,7 +18,7 @@ package io.entgra.application.mgt.publisher.api.services.impl;
import io.entgra.application.mgt.common.ApplicationArtifact;
import io.entgra.application.mgt.common.ApplicationList;
-import io.entgra.application.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.Base64File;
import io.entgra.application.mgt.common.Filter;
import io.entgra.application.mgt.common.LifecycleChanger;
import io.entgra.application.mgt.common.exception.ResourceManagementException;
@@ -89,11 +89,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
ApplicationList applications = applicationManager.getApplications(filter);
return Response.status(Response.Status.OK).entity(applications).build();
} catch (BadRequestException e) {
- String msg = "Incompatible request payload is found. Please try with valid request payload.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnexpectedServerErrorException e) {
- String msg = "Error Occured when getting supported device types by Entgra IoTS";
+ String msg = "Error occurred when getting supported device types by Entgra IoTS";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -173,7 +173,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(applicationWrapper, isPublished);
} catch (BadRequestException e) {
- String msg = "Found incompatible payload with ent. app creating request.";
+ String msg = "Found incompatible payload with ent. app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -195,7 +195,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(webAppWrapper, isPublished);
} catch (BadRequestException e) {
- String msg = "Found incompatible payload with web app creating request.";
+ String msg = "Found incompatible payload with web app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -217,7 +217,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(publicAppWrapper, isPublished);
} catch (BadRequestException e) {
- String msg = "Found incompatible payload with pub app creating request.";
+ String msg = "Found incompatible payload with pub app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -239,7 +239,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
return createApplication(customAppWrapper, isPublished);
} catch (BadRequestException e) {
- String msg = "Found incompatible payload with custom app creating request.";
+ String msg = "Found incompatible payload with custom app creating request. Please try with valid request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -267,7 +267,11 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
ApplicationRelease release = applicationManager.createEntAppRelease(appId, entAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(release).build();
} catch (RequestValidatingException e) {
- String msg = "Error occurred while validating binaryArtifact";
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ } catch (BadRequestException e){
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -291,6 +295,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validatePublicAppReleaseCreatingRequest(publicAppReleaseWrapper, deviceTypeName);
ApplicationRelease applicationRelease = applicationManager.createPubAppRelease(appId, publicAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
+ } catch (BadRequestException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while creating application release for the application with the id " + appId;
log.error(msg, e);
@@ -300,7 +308,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RequestValidatingException e) {
- String msg = "Invalid payload found in public app release create request";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
@@ -318,6 +326,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validateWebAppReleaseCreatingRequest(webAppReleaseWrapper);
ApplicationRelease applicationRelease= applicationManager.createWebAppRelease(appId, webAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
+ } catch (BadRequestException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ResourceManagementException e) {
String msg = "Error occurred while uploading application release artifacts";
log.error(msg, e);
@@ -327,7 +339,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (RequestValidatingException e) {
- String msg = "Invalid payload found in web app release create request";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
@@ -346,8 +358,12 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
applicationManager.validateCustomAppReleaseCreatingRequest(customAppReleaseWrapper, deviceTypeName);
ApplicationRelease release = applicationManager.createCustomAppRelease(appId, customAppReleaseWrapper, isPublished);
return Response.status(Response.Status.CREATED).entity(release).build();
+ } catch (BadRequestException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (RequestValidatingException e) {
- String msg = "Error occurred while validating binaryArtifact";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ResourceManagementException e) {
@@ -371,19 +387,28 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
if (appName == null) {
String msg = "Invalid app name, appName query param cannot be empty/null.";
log.error(msg);
- return Response.status(Response.Status.BAD_REQUEST).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ }
+ if (appName.length() > 20) {
+ String msg = "Invalid app name, maximum length of the application name should be 20 characters.";
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
ApplicationManager applicationManager = APIUtil.getApplicationManager();
if (applicationManager.isExistingAppName(appName, deviceType)) {
- return Response.status(Response.Status.CONFLICT).build();
+ String msg = "Invalid app name, app name already exists.";
+ log.error(msg);
+ return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
- log.error("Found invalid device type to check application existence.", e);
- return Response.status(Response.Status.BAD_REQUEST).build();
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
- log.error("Internal Error occurred while checking the application existence.", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ String msg = "Internal Error occurred while checking the application existence.";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
}
@@ -451,6 +476,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
String msg = "Found an invalid device type: " + deviceType + " with the request";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ } catch (ForbiddenException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while updating the image artifacts of the application with the uuid "
+ applicationReleaseUuid;
@@ -474,8 +503,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Error occurred while modifying the application. Found bad request payload for updating the "
- + "application";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -505,8 +533,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
- String msg =
- "Invalid request to update ent app release for application release UUID " + applicationUUID;
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@@ -546,7 +573,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
- String msg = "Invalid request to update public app release for application release UUID " + applicationUUID;
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@@ -586,7 +613,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
- String msg = "Invalid request to update web app release for web app release UUID " + applicationUUID;
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@@ -625,8 +652,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
}
return Response.status(Response.Status.OK).entity(applicationRelease).build();
} catch (BadRequestException e) {
- String msg =
- "Invalid request to update ent app release for application release UUID " + applicationUUID;
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
@@ -676,7 +702,7 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
.changeLifecycleState(applicationUuid, lifecycleChanger);
return Response.status(Response.Status.CREATED).entity(applicationRelease).build();
} catch (BadRequestException e) {
- String msg = "Request payload contains invalid data, hence verify the request payload.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).build();
} catch (ForbiddenException e) {
@@ -838,6 +864,10 @@ public class ApplicationManagementPublisherAPIImpl implements ApplicationManagem
try {
List applicationTags = applicationManager.addApplicationTags(appId, tagNames);
return Response.status(Response.Status.OK).entity(applicationTags).build();
+ } catch (BadRequestException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg, e);
diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java
index 4abe861ce81..4eacf5accf4 100644
--- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/SPApplicationServiceImpl.java
@@ -96,6 +96,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@@ -115,6 +116,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@@ -134,9 +136,10 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "Identity server with the id " + id + " does not exist.";
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
- String errMsg = "Identity server request payload is invalid";
+ String errMsg = e.getMessage();
log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
@@ -156,8 +159,8 @@ public class SPApplicationServiceImpl implements SPApplicationService {
IdentityServerResponse identityServer = spAppManager.createIdentityServer(identityServerDTO);
return Response.status(Response.Status.CREATED).entity(identityServer).build();
} catch (BadRequestException e) {
- String errMsg = "Identity server request payload is invalid";
- log.error(errMsg, e);
+ String errMsg = e.getMessage();
+ log.error(errMsg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@@ -232,6 +235,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String errMsg = "No Identity server exist with the id: " + identityServerId;
log.error(errMsg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(errMsg).build();
} catch (ApplicationManagementException e) {
String errMsg = "Error occurred while trying to merge identity server apps with existing apps";
@@ -252,6 +256,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
@@ -277,6 +282,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Invalid appIds provided";
@@ -343,6 +349,7 @@ public class SPApplicationServiceImpl implements SPApplicationService {
} catch (NotFoundException e) {
String msg = "No identity server exist with the id " + identityServerId;
log.error(msg, e);
+ // TODO : the correct way is to use the NOT_FOUND response here. In order to do it changes are needed for the UI code as well
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (BadRequestException e) {
String msg = "Found incompatible payload with create service provider app request.";
diff --git a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/admin/ApplicationManagementPublisherAdminAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/admin/ApplicationManagementPublisherAdminAPIImpl.java
index 9dae875ca88..6fd83760103 100644
--- a/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/admin/ApplicationManagementPublisherAdminAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.publisher.api/src/main/java/io/entgra/application/mgt/publisher/api/services/impl/admin/ApplicationManagementPublisherAdminAPIImpl.java
@@ -155,6 +155,10 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
applicationManager.updateCategory(oldCategoryName, newCategoryName);
return Response.status(Response.Status.OK)
.entity("Category is updated from " + oldCategoryName + " to " + newCategoryName).build();
+ } catch (BadRequestException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (NotFoundException e) {
String msg = e.getMessage();
log.error(msg, e);
@@ -181,6 +185,10 @@ public class ApplicationManagementPublisherAdminAPIImpl implements ApplicationMa
String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (ForbiddenException e) {
+ String msg = e.getMessage();
+ log.error(msg, e);
+ return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error Occurred while deleting registered category.";
log.error(msg, e);
diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml b/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml
index 3cc8edac9a2..dfbdceb72f1 100644
--- a/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml
+++ b/components/application-mgt/io.entgra.application.mgt.store.api/pom.xml
@@ -22,7 +22,7 @@
application-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ApplicationManagementAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ApplicationManagementAPIImpl.java
index 5f1f124d636..f771645a771 100644
--- a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ApplicationManagementAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ApplicationManagementAPIImpl.java
@@ -58,7 +58,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationManager.addAppToFavourites(appId);
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
- String msg = "Invalid payload found in the request. Hence verify the request payload.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -78,7 +78,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
applicationManager.removeAppFromFavourites(appId);
return Response.status(Response.Status.OK).build();
} catch (BadRequestException e) {
- String msg = "Invalid payload found in the request. Hence verify the request payload.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -147,7 +147,7 @@ public class ApplicationManagementAPIImpl implements ApplicationManagementAPI {
String msg = "Could not found an application release which is in " + applicationManager
.getInstallableLifecycleState() + " state.";
log.error(msg);
- return Response.status(Response.Status.OK).entity(msg).build();
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(application).build();
} catch (NotFoundException e) {
diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java
index 8aa8b728af9..b07f1ea9c61 100644
--- a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/ReviewManagementAPIImpl.java
@@ -131,7 +131,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload data with the request. Hence, please verify the request payload.";
+ String msg = e.getMessage();
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -144,7 +144,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
- String msg = "Error occured while accessing application release for UUID: " + uuid;
+ String msg = "Error occurred while accessing application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@@ -164,7 +164,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
if (isRepliedForReview) {
return Response.status(Response.Status.CREATED).entity(reviewWrapper).build();
} else {
- String msg = "Error occured when adding reply comment for the review. Please contact the administrator..";
+ String msg = "Error occurred when adding reply comment for the review. Please contact the administrator..";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@@ -173,7 +173,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload data with the request to add reply comment. Hence, please verify the "
+ String msg = "Invalid payload data found with the requested add reply comment. Hence, please verify the "
+ "request payload.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
@@ -182,7 +182,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (ApplicationManagementException e) {
- String msg = "Error occured while accessing application release for UUID: " + uuid;
+ String msg = "Error occurred while accessing application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
}
@@ -214,8 +214,12 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
String msg = "Couldn't found application release data for UUID " + uuid + " or Review for review ID: " + reviewId;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (BadRequestException e) {
+ String msg = "Invalid payload data found with the request. Hence, please verify the request payload.";
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
- String msg = "You dont have permission to update application release review.";
+ String msg = "You don't have permission to update application release review.";
log.error(msg, e);
return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
} catch (ApplicationManagementException e) {
@@ -267,7 +271,7 @@ public class ReviewManagementAPIImpl implements ReviewManagementAPI {
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (ReviewManagementException | ApplicationManagementException e) {
- String msg = "Error occured while getting review data for application release UUID: " + uuid;
+ String msg = "Error occurred while getting review data for application release UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java
index 11b1ffa6893..ab13168e174 100644
--- a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/SubscriptionManagementAPIImpl.java
@@ -93,12 +93,11 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
SubAction.valueOf(action.toUpperCase()), timestamp, properties);
}
} catch (NotFoundException e) {
- String msg = "Couldn't found an application release for UUI: " + uuid;
+ String msg = "Couldn't found an application release for UUID: " + uuid;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload for installing application which has UUID: " + uuid + ". Hence verify "
- + "the payload";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -147,8 +146,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload for installing application which has UUID: " + uuid + ". Hence verify "
- + "the payload";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -187,13 +185,12 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
SubAction.valueOf(SubAction.INSTALL.toString().toUpperCase()), timestamp, null);
}
} catch (NotFoundException e) {
- String msg = "Couldn't found an application release for UUI: " + uuid + " to perform ent app installation "
+ String msg = "Couldn't found an application release for UUID: " + uuid + " to perform ent app installation "
+ "on subscriber's devices";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload when performing ent app installation on application which has UUID: "
- + uuid + ". Hence verify the payload of the request.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -237,8 +234,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload when performing ent app installation on application which has UUID: "
- + uuid + ". Hence verify the payload of the request.";
+ String msg = e.getMessage();
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -360,7 +356,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "User requested details are not valid";
+ String msg = "User requested details are not valid. Please verify the payload of the request.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -424,8 +420,7 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Found invalid payload for getting application which has UUID: " + uuid
- + ". Hence verify the payload";
+ String msg = "Invalid payload found when getting application. Hence verify the payload";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ForbiddenException e) {
@@ -502,6 +497,10 @@ public class SubscriptionManagementAPIImpl implements SubscriptionManagementAPI{
String msg = "Application with application release UUID: " + uuid + " is not found";
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (BadRequestException e) {
+ String msg = "Invalid payload found with the request. Please verify the payload.";
+ log.error(msg,e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
String msg = "Error occurred while getting application with the application " +
"release uuid: " + uuid;
diff --git a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java
index 158696d65e0..08226c72bf0 100644
--- a/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java
+++ b/components/application-mgt/io.entgra.application.mgt.store.api/src/main/java/io/entgra/application/mgt/store/api/services/impl/admin/SubscriptionManagementAdminAPIImpl.java
@@ -133,7 +133,7 @@ public class SubscriptionManagementAdminAPIImpl implements SubscriptionManagemen
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "User requested details are not valid";
+ String msg = "User requested details are not valid. Please verify the request payload.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (ApplicationManagementException e) {
diff --git a/components/application-mgt/pom.xml b/components/application-mgt/pom.xml
index 58475ac289d..603debde5b0 100644
--- a/components/application-mgt/pom.xml
+++ b/components/application-mgt/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
index 156ccf9cb01..401bf1e2902 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.api/pom.xml
@@ -22,7 +22,7 @@
certificate-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
index f6175594545..ca00607aa1c 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.cert.admin.api/pom.xml
@@ -22,7 +22,7 @@
certificate-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
index 8521489c1c9..b78bc2a6dc1 100644
--- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
+++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/pom.xml
@@ -38,7 +38,7 @@
org.wso2.carbon.devicemgt
certificate-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/certificate-mgt/pom.xml b/components/certificate-mgt/pom.xml
index a780123240d..34f37128a7e 100644
--- a/components/certificate-mgt/pom.xml
+++ b/components/certificate-mgt/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml
index 21986acdcc7..8e56f845ac9 100644
--- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml
+++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.defaultrole.manager/pom.xml
@@ -23,7 +23,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml
index 4153e2c3374..d71db177578 100644
--- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml
+++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java
index c959eb4885b..2ffa6ffa8d8 100644
--- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java
+++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.logger/src/main/java/io/entgra/device/mgt/extensions/logger/spi/EntgraLogger.java
@@ -48,6 +48,22 @@ public interface EntgraLogger extends Log {
void warn(Object object, Throwable t, LogContext logContext);
+ void info(String message, LogContext logContext);
+
+ void debug(String message, LogContext logContext);
+
+ void error(String message, LogContext logContext);
+
+ void error(String message, Throwable t, LogContext logContext);
+
+ void warn(String message, LogContext logContext);
+
+ void warn(String message, Throwable t, LogContext logContext);
+
+ void trace(String message, LogContext logContext);
+
+ void fatal(String message, LogContext logContext);
+
void clearLogContext();
}
diff --git a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml
index 2dd1025f8bd..ac423deb81a 100644
--- a/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml
+++ b/components/device-mgt-extensions/io.entgra.device.mgt.extensions.stateengine/pom.xml
@@ -23,7 +23,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml
index 65c27150c01..a16f0e46ca4 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.device.type.deployer/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml
index a6f43d0f7d8..3d9e19dd8a0 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.pull.notification/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml
index 7687af14ec2..658b51a8ceb 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.fcm/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml
index 250d1b27559..0d107ecda81 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.http/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml
index 27e81b20862..ba38443cd27 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml
index ac1d9433dbb..7f4e6d7386d 100644
--- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml
+++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.xmpp/pom.xml
@@ -22,7 +22,7 @@
device-mgt-extensions
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt-extensions/pom.xml b/components/device-mgt-extensions/pom.xml
index 61cc4740967..5b2bf7774f8 100644
--- a/components/device-mgt-extensions/pom.xml
+++ b/components/device-mgt-extensions/pom.xml
@@ -22,7 +22,7 @@
carbon-devicemgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml
index 6173c124e8d..7ffc616573a 100644
--- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml
+++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/pom.xml
@@ -22,7 +22,7 @@
device-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java
index 4f13273e217..8aea316c557 100644
--- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java
+++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java
@@ -91,9 +91,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
if (properties == null || properties.isEmpty()) {
String msg = "Devices configuration retrieval criteria cannot be null or empty.";
log.error(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()
- ).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
ObjectMapper mapper = new ObjectMapper();
@@ -113,18 +111,15 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceNotFoundException e) {
log.warn(e.getMessage());
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (AmbiguousConfigurationException e) {
String msg = "Configurations are ambiguous. " + e.getMessage();
log.warn(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (JsonParseException | JsonMappingException e) {
String msg = "Malformed device property structure";
log.error(msg.concat(" ").concat(properties), e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (IOException e) {
String msg = "Error occurred while parsing query param JSON data.";
log.error(msg.concat(" ").concat(properties), e);
@@ -150,8 +145,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
if (devicesTransferred.isEmpty()) {
String msg = "Devices are not enrolled to super tenant";
log.warn(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} else {
return Response.status(Response.Status.OK).entity(devicesTransferred).build();
}
@@ -163,8 +157,7 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceNotFoundException e) {
log.error(e.getMessage(), e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
index d232be71b83..fd55008151f 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/pom.xml
@@ -22,7 +22,7 @@
device-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
@@ -425,5 +425,35 @@
io.entgra.application.mgt.core
provided
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.apimgt.keymgt.extension
+ provided
+
+
+ org.wso2.carbon.analytics-common
+ org.wso2.carbon.event.stream.core
+ provided
+
+
+ org.wso2.carbon.analytics-common
+ org.wso2.carbon.event.receiver.core
+ provided
+
+
+ org.wso2.carbon.analytics-common
+ org.wso2.carbon.event.publisher.core
+ provided
+
+
+ org.wso2.carbon.analytics-common
+ org.wso2.carbon.event.output.adapter.rdbms
+ provided
+
+
+ org.wso2.carbon.devicemgt
+ io.entgra.device.mgt.core.apimgt.analytics.extension
+ provided
+
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java
new file mode 100644
index 00000000000..158153fd918
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceConfig.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.wso2.carbon.device.mgt.jaxrs.beans;
+
+import io.swagger.annotations.ApiModel;
+import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
+
+import java.util.List;
+
+@ApiModel(value = "DeviceConfig", description = "Device config")
+public class DeviceConfig {
+ private String clientId;
+ private String clientSecret;
+ private String deviceId;
+ private String type;
+ private String accessToken;
+ private String refreshToken;
+ private String mqttGateway;
+ private String httpsGateway;
+ private String httpGateway;
+ private PlatformConfiguration platformConfiguration;
+ public String getClientId() {
+ return clientId;
+ }
+
+ public void setClientId(String clientId) {
+ this.clientId = clientId;
+ }
+
+ public String getClientSecret() {
+ return clientSecret;
+ }
+
+ public void setClientSecret(String clientSecret) {
+ this.clientSecret = clientSecret;
+ }
+
+ public String getDeviceId() {
+ return deviceId;
+ }
+
+ public void setDeviceId(String deviceId) {
+ this.deviceId = deviceId;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
+ }
+
+ public String getRefreshToken() {
+ return refreshToken;
+ }
+
+ public void setRefreshToken(String refreshToken) {
+ this.refreshToken = refreshToken;
+ }
+
+ public String getMqttGateway() {
+ return mqttGateway;
+ }
+
+ public void setMqttGateway(String mqttGateway) {
+ this.mqttGateway = mqttGateway;
+ }
+
+ public String getHttpsGateway() {
+ return httpsGateway;
+ }
+
+ public void setHttpsGateway(String httpsGateway) {
+ this.httpsGateway = httpsGateway;
+ }
+
+ public String getHttpGateway() {
+ return httpGateway;
+ }
+
+ public void setHttpGateway(String httpGateway) {
+ this.httpGateway = httpGateway;
+ }
+
+ public PlatformConfiguration getPlatformConfiguration() {
+ return platformConfiguration;
+ }
+
+ public void setPlatformConfiguration(PlatformConfiguration platformConfiguration) {
+ this.platformConfiguration = platformConfiguration;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java
index 8c6c4945c4c..9f0d32127eb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/DeviceList.java
@@ -35,8 +35,11 @@ public class DeviceList extends BasePaginatedResult {
@ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false)
private String message;
- @ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false)
- private boolean billedDateIsValid;
+ @ApiModelProperty(name = "deviceCount", value = "Total count of all devices per tenant", required = false)
+ private double deviceCount;
+
+ @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
+ private String billPeriod;
@ApiModelProperty(value = "List of devices returned")
@JsonProperty("devices")
@@ -48,12 +51,20 @@ public class DeviceList extends BasePaginatedResult {
this.devices = devices;
}
- public boolean isBilledDateIsValid() {
- return billedDateIsValid;
+ public String getBillPeriod() {
+ return billPeriod;
+ }
+
+ public void setBillPeriod(String billPeriod) {
+ this.billPeriod = billPeriod;
+ }
+
+ public double getDeviceCount() {
+ return deviceCount;
}
- public void setBilledDateIsValid(boolean billedDateIsValid) {
- this.billedDateIsValid = billedDateIsValid;
+ public void setDeviceCount(double deviceCount) {
+ this.deviceCount = deviceCount;
}
public String getMessage() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java
index b8e07df6d54..b5a715135e0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/beans/analytics/DeviceTypeEvent.java
@@ -20,14 +20,18 @@ package org.wso2.carbon.device.mgt.jaxrs.beans.analytics;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
+import java.util.List;
+
/**
* This hold stats data record
*/
public class DeviceTypeEvent {
+ private String eventName;
private EventAttributeList eventAttributes;
private TransportType transport;
+ private String eventTopicStructure;
@ApiModelProperty(value = "Attributes related to device type event")
@JsonProperty("eventAttributes")
public EventAttributeList getEventAttributeList() {
@@ -48,5 +52,25 @@ public class DeviceTypeEvent {
public void setTransportType(TransportType transport) {
this.transport = transport;
}
+
+ @ApiModelProperty(value = "event topic structure")
+ @JsonProperty("eventTopicStructure")
+ public String getEventTopicStructure() {
+ return eventTopicStructure;
+ }
+
+ public void setEventTopicStructure(String eventTopicStructure) {
+ this.eventTopicStructure = eventTopicStructure;
+ }
+
+ @ApiModelProperty(value = "event topic name")
+ @JsonProperty("eventName")
+ public String getEventName() {
+ return eventName;
+ }
+
+ public void setEventName(String eventName) {
+ this.eventName = eventName;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java
index 82e0cdb8975..83503248fcd 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceEventManagementService.java
@@ -29,6 +29,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;
@SwaggerDefinition(
info = @Info(
@@ -69,64 +70,64 @@ import javax.ws.rs.core.Response;
@Consumes(MediaType.APPLICATION_JSON)
public interface DeviceEventManagementService {
-// @POST
-// @Path("/{type}")
-// @ApiOperation(
-// produces = MediaType.APPLICATION_JSON,
-// httpMethod = "POST",
-// value = "Adding the Event Type Definition",
-// notes = "Add the event definition for a 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 = "The device type, such as android, ios, and windows.")
-// @PathParam("type")String deviceType,
-// @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
-// @QueryParam("skipPersist") boolean skipPersist,
-// @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
-// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
-// @ApiParam(name = "deviceTypeEvent", value = "Add the data to complete the DeviceTypeEvent object.",
-// required = true)
-// @Valid DeviceTypeEvent deviceTypeEvent);
+ @POST
+ @Path("/{type}")
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "POST",
+ value = "Adding the Event Type Definition",
+ notes = "Add the event definition for a 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 = "The device type, such as android, ios, and windows.")
+ @PathParam("type")String deviceType,
+ @ApiParam(name = "skipPersist", value = "Is it required to persist the data or not")
+ @QueryParam("skipPersist") boolean skipPersist,
+ @ApiParam(name = "isSharedWithAllTenants", value = "Should artifacts be available to all tenants")
+ @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
+ @ApiParam(name = "deviceTypeEvents", value = "Add the data to complete the DeviceTypeEvent object.",
+ required = true)
+ @Valid List deviceTypeEvent);
@DELETE
@Path("/{type}")
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java
index 469091d21ea..a080208de25 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/DeviceManagementService.java
@@ -188,6 +188,13 @@ import java.util.List;
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/devices/owning-device/add"}
),
+ @Scope(
+ name = "Viewing Enrollment Guide",
+ description = "Show enrollment guide to users",
+ key = "perm:devices:enrollment-guide:view",
+ roles = {"Internal/devicemgt-user"},
+ permissions = {"/device-mgt/devices/enrollment-guide/view"}
+ ),
}
)
@Path("/devices")
@@ -344,179 +351,6 @@ public interface DeviceManagementService {
@QueryParam("limit")
int limit);
-
- @GET
- @Path("/billing")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "Getting Cost details of devices in a tenant",
- notes = "Provides individual cost and total cost of all devices per tenant.",
- tags = "Device Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
- })
- }
- )
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
- response = DeviceList.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 = 400,
- message = "The incoming request has more than one selection criteria defined via the query parameters.",
- response = ErrorResponse.class),
- @ApiResponse(
- code = 404,
- message = "The search criteria did not match any device registered with the server.",
- 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 getDevicesBilling(
- @ApiParam(
- name = "tenantDomain",
- value = "The tenant domain.",
- required = false)
- @QueryParam("tenantDomain")
- String tenantDomain,
- @ApiParam(
- name = "startDate",
- value = "The start date.",
- required = false)
- @QueryParam("startDate")
- Timestamp startDate,
- @ApiParam(
- name = "endDate",
- value = "The end date.",
- required = false)
- @QueryParam("endDate")
- Timestamp endDate,
- @ApiParam(
- name = "generateBill",
- value = "The generate bill boolean.",
- required = false)
- @QueryParam("generateBill")
- boolean generateBill,
- @ApiParam(
- name = "offset",
- value = "The starting pagination index for the complete list of qualified items.",
- required = false,
- defaultValue = "0")
- @QueryParam("offset")
- int offset,
- @ApiParam(
- name = "limit",
- value = "Provide how many device details you require from the starting pagination index/offset.",
- required = false,
- defaultValue = "10")
- @QueryParam("limit")
- int limit);
-
-
- @GET
- @Path("/billing/file")
- @Produces(MediaType.APPLICATION_JSON)
- @ApiOperation(
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "Getting Cost details of devices in a tenant",
- notes = "Provides individual cost and total cost of all devices per tenant.",
- tags = "Device Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
- })
- }
- )
- @ApiResponses(value = {
- @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
- response = DeviceList.class,
- responseHeaders = {
- @ResponseHeader(
- name = "Content-Type",
- description = "The content type of the body"),
- @ResponseHeader(
- name = "Content-Disposition",
- description = "The content disposition 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 = 400,
- message = "The incoming request has more than one selection criteria defined via the query parameters.",
- response = ErrorResponse.class),
- @ApiResponse(
- code = 404,
- message = "The search criteria did not match any device registered with the server.",
- 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 exportBilling(
- @ApiParam(
- name = "tenantDomain",
- value = "The tenant domain.",
- required = false)
- @QueryParam("tenantDomain")
- String tenantDomain,
- @ApiParam(
- name = "startDate",
- value = "The start date.",
- required = false)
- @QueryParam("startDate")
- Timestamp startDate,
- @ApiParam(
- name = "endDate",
- value = "The end date.",
- required = false)
- @QueryParam("endDate")
- Timestamp endDate,
- @ApiParam(
- name = "generateBill",
- value = "The generate bill boolean.",
- required = false)
- @QueryParam("generateBill")
- boolean generateBill);
-
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
@@ -726,12 +560,12 @@ public interface DeviceManagementService {
required = false,
defaultValue = "0")
@QueryParam("offset") int offset,
- @ApiParam(
- name = "limit",
- value = "Provide how many device details you require from the starting pagination index/offset.",
- required = false,
- defaultValue = "100")
- @QueryParam("limit") int limit
+ @ApiParam(
+ name = "limit",
+ value = "Provide how many device details you require from the starting pagination index/offset.",
+ required = false,
+ defaultValue = "100")
+ @QueryParam("limit") int limit
);
@GET
@@ -975,6 +809,59 @@ public interface DeviceManagementService {
@QueryParam("requireDeviceInfo")
boolean requireDeviceInfo);
+ @POST
+ @Produces(MediaType.APPLICATION_JSON)
+ @Consumes(MediaType.MULTIPART_FORM_DATA)
+ @Path("/enrollment/guide")
+ @ApiOperation(
+ consumes = MediaType.MULTIPART_FORM_DATA,
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "POST",
+ value = "Sending Enrollment Mode chosen by customer",
+ notes = "Enrollment mode selected and path is sent as parameters",
+ tags = "Device Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:enrollment-guide:view")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully mailed the Enrollment Guide of customer.",
+ response = Device.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 Invalid request or validation error.",
+ response = ErrorResponse.class),
+ @ApiResponse(
+ code = 500,
+ message = "Internal Server Error. \n " +
+ "Server error occurred while sending mail of the Enrollment Guide.",
+ response = ErrorResponse.class)
+ })
+ Response sendEnrollmentGuide(
+ @ApiParam(
+ name = "enrolmentGuide",
+ value = "The details of the enrolment path suggested.",
+ required = true)
+ String enrolmentGuide);
+
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/type/any/list")
@@ -1232,6 +1119,82 @@ public interface DeviceManagementService {
@HeaderParam("If-Modified-Since")
String ifModifiedSince);
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{type}/{id}/config")
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "GET",
+ value = "Getting the Configuration of a Device",
+ notes = "Get the configuration of a device by specifying the device type and device identifier.",
+ tags = "Device Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:details")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully fetched the configuration of the device.",
+ response = DeviceInfo.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. 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 Location data for the specified device 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 getDeviceConfiguration(
+ @ApiParam(
+ name = "type",
+ value = "The device type name, such as ios, android, windows, or fire-alarm.",
+ required = true)
+ @PathParam("type")
+ @Size(max = 45)
+ String type,
+ @ApiParam(
+ name = "id",
+ value = "The device identifier of the device you want ot get details.",
+ required = true)
+ @PathParam("id")
+ @Size(max = 45)
+ String id,
+ @ApiParam(
+ name = "If-Modified-Since",
+ value = "Checks if the requested variant was modified, since the specified date-time. \n" +
+ "Provide the value in the following 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);
+
//device rename request would looks like follows
//POST devices/type/virtual_firealarm/id/us06ww93auzp/rename
@POST
@@ -1382,7 +1345,7 @@ public interface DeviceManagementService {
@GET
@Produces(MediaType.APPLICATION_JSON)
- @Path("/{type}/{id}/features")
+ @Path("/device-type/{type}/features")
@ApiOperation(
produces = MediaType.APPLICATION_JSON,
httpMethod = "GET",
@@ -1453,14 +1416,6 @@ public interface DeviceManagementService {
@PathParam("type")
@Size(max = 45)
String type,
- @ApiParam(
- name = "id",
- value = "The device identifier of the device.\n" +
- "INFO: Make sure to add the ID of a device that is already registered with WSO2 IoTS.",
- required = true)
- @PathParam("id")
- @Size(max = 45)
- String id,
@ApiParam(
name = "If-Modified-Since",
value = "Checks if the requested variant was modified, since the specified date-time. \n" +
@@ -1580,15 +1535,15 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
- "Used by caches, or in conditional requests."),
+ "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.")}),
+ "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"),
+ "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.",
@@ -1606,7 +1561,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
- "Server error occurred while getting the device details.",
+ "Server error occurred while getting the device details.",
response = ErrorResponse.class)
})
Response queryDevicesByProperties(
@@ -1628,7 +1583,7 @@ public interface DeviceManagementService {
name = "device property map",
value = "properties by which devices need filtered",
required = true)
- PropertyMap map);
+ PropertyMap map);
@GET
@Produces(MediaType.APPLICATION_JSON)
@@ -2054,140 +2009,141 @@ public interface DeviceManagementService {
@Size(max = 45)
String id);
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- @Path("/{type}/{id}/getstatushistory")
- @ApiOperation(
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "Get Device status history",
- notes = "Get a list of status history associated with the device type and id",
- tags = "Device Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully fetched the status history of matching devices.",
- response = List.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. 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 device with the specified device type and id 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)
- })
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{type}/{id}/status-history")
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "GET",
+ value = "Get Device status history",
+ notes = "Get a list of status history associated with the device type and id",
+ tags = "Device Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully fetched the status history of matching devices.",
+ response = List.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. 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 device with the specified device type and id 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 getDeviceStatusHistory(
- @ApiParam(
- name = "type",
- value = "The device type, such as ios, android, or windows.",
- required = true)
- @PathParam("type")
- @Size(max = 45)
- String type,
- @ApiParam(
- name = "id",
- value = "Device ID.",
- required = true)
- @PathParam("id")
- @Size(max = 45)
- String id);
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- @Path("/{type}/{id}/getenrolmentstatushistory")
- @ApiOperation(
- produces = MediaType.APPLICATION_JSON,
- httpMethod = "GET",
- value = "Get Device Current Enrolment status history",
- notes = "Get a list of status history associated with the device type and id for the current enrolment",
- tags = "Device Management",
- extensions = {
- @Extension(properties = {
- @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
- })
- }
- )
- @ApiResponses(
- value = {
- @ApiResponse(
- code = 200,
- message = "OK. \n Successfully fetched the status history of matching devices.",
- response = List.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. 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 device with the specified device type and id 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)
- })
+ @ApiParam(
+ name = "type",
+ value = "The device type, such as ios, android, or windows.",
+ required = true)
+ @PathParam("type")
+ @Size(max = 45)
+ String type,
+ @ApiParam(
+ name = "id",
+ value = "Device ID.",
+ required = true)
+ @PathParam("id")
+ @Size(max = 45)
+ String id);
+
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("/{type}/{id}/enrolment-status-history")
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "GET",
+ value = "Get Device Current Enrolment status history",
+ notes = "Get a list of status history associated with the device type and id for the current enrolment",
+ tags = "Device Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:devices:view")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully fetched the status history of matching devices.",
+ response = List.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. 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 device with the specified device type and id 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 getCurrentEnrolmentDeviceStatusHistory(
- @ApiParam(
- name = "type",
- value = "The device type, such as ios, android, or windows.",
- required = true)
- @PathParam("type")
- @Size(max = 45)
- String type,
- @ApiParam(
- name = "id",
- value = "Device ID.",
- required = true)
- @PathParam("id")
- @Size(max = 45)
- String id);
+ @ApiParam(
+ name = "type",
+ value = "The device type, such as ios, android, or windows.",
+ required = true)
+ @PathParam("type")
+ @Size(max = 45)
+ String type,
+ @ApiParam(
+ name = "id",
+ value = "Device ID.",
+ required = true)
+ @PathParam("id")
+ @Size(max = 45)
+ String id);
@PUT
@Produces(MediaType.APPLICATION_JSON)
@@ -2352,16 +2308,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
- "Used by caches, or in conditional requests."),
+ "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."),
+ "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"),
+ " of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@@ -2373,7 +2329,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
- "Server error occurred while retrieving the device details.",
+ "Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceCountByStatus(
@@ -2421,16 +2377,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
- "Used by caches, or in conditional requests."),
+ "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."),
+ "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"),
+ " of the requested resource.\n"),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@@ -2442,7 +2398,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
- "Server error occurred while retrieving the device details.",
+ "Server error occurred while retrieving the device details.",
response = ErrorResponse.class)
})
Response getDeviceIdentifiersByStatus(
@@ -2491,16 +2447,16 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
- "Used by caches, or in conditional requests."),
+ "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."),
+ "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."),
+ "version of the requested resource."),
@ApiResponse(
code = 400,
message = "Bad Request. \n Invalid request or validation error.",
@@ -2512,7 +2468,7 @@ public interface DeviceManagementService {
@ApiResponse(
code = 500,
message = "Internal Server Error. \n " +
- "Server error occurred while retrieving information requested device.",
+ "Server error occurred while retrieving information requested device.",
response = ErrorResponse.class)
})
Response bulkUpdateDeviceStatus(
@@ -2823,11 +2779,11 @@ public interface DeviceManagementService {
@ResponseHeader(
name = "ETag",
description = "Entity Tag of the response resource.\n" +
- "Used by caches, or in conditional requests."),
+ "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."),
+ "Used by caches, or in conditional requests."),
}),
@ApiResponse(
code = 500,
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java
index 1162c55f45c..96b3188f70d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java
@@ -192,6 +192,13 @@ import java.util.List;
key = "perm:groups:device",
roles = {"Internal/devicemgt-user"},
permissions = {"/device-mgt/groups/devices/view"}
+ ),
+ @Scope(
+ name = "View whether the groups has relevant device types",
+ description = "View whether the groups has relevant device types",
+ key = "perm:groups:devices-types",
+ roles = {"Internal/devicemgt-user"},
+ permissions = {"/device-mgt/groups/devices/types"}
)
}
)
@@ -1185,4 +1192,58 @@ public interface GroupManagementService {
@QueryParam("requireGroupProps")
boolean requireGroupProps);
+ @Path("/device-types")
+ @POST
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = HTTPConstants.HEADER_GET,
+ value = "Getting Details whether the groups has relevant device type or not",
+ notes = "Getting Details whether the groups has relevant device type or not.",
+ tags = "Device Group Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:groups:devices-types")
+ })
+ },
+ nickname = "getGroupByGroupNameFilter"
+ )
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK. \n Successfully fetched the device types of groups.",
+ response = DeviceGroup.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. \n Empty body because the client has already the latest version of " +
+ "the requested resource."),
+ @ApiResponse(
+ code = 404,
+ message = "Error occurred",
+ 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 group details.",
+ response = ErrorResponse.class)
+ })
+ Response getGroupHasDeviceTypes(
+ @ApiParam(
+ name = "identifiers",
+ value = "GET list of identifiers.",
+ required = true)
+ List identifiers);
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/MetadataService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/MetadataService.java
index 446944729ba..55aeafeec01 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/MetadataService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/MetadataService.java
@@ -33,6 +33,7 @@ import org.apache.axis2.transport.http.HTTPConstants;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/WhiteLabelService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/WhiteLabelService.java
new file mode 100644
index 00000000000..85be91bdd8f
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/WhiteLabelService.java
@@ -0,0 +1,324 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.service.api;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+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 io.swagger.annotations.ApiParam;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.wso2.carbon.apimgt.annotations.api.Scope;
+import org.wso2.carbon.apimgt.annotations.api.Scopes;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
+import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
+import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+/**
+ * Metadata related REST-API implementation.
+ */
+@SwaggerDefinition(
+ info = @Info(
+ version = "1.0.0",
+ title = "Whitelabel Service",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = "name", value = "WhiteLabelManagement"),
+ @ExtensionProperty(name = "context", value = "/api/device-mgt/v1.0/whitelabel"),
+ })
+ }
+ ),
+ tags = {
+ @Tag(name = "device_management")
+ }
+)
+@Scopes(
+ scopes = {
+ @Scope(
+ name = "View Whitelabel",
+ description = "View whitelabel details",
+ key = "perm:whitelabel:view",
+ roles = {"Internal/devicemgt-user"},
+ permissions = {"/device-mgt/whitelabel/view"}
+ ),
+ @Scope(
+ name = "Update Whitelabel",
+ description = "Updating whitelabel",
+ key = "perm:whitelabel:update",
+ roles = {"Internal/devicemgt-user"},
+ permissions = {"/device-mgt/whitelabel/update"}
+ ),
+ }
+)
+@Api(value = "Whitelabel Management")
+@Path("/whitelabel")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public interface WhiteLabelService {
+
+ @GET
+ @Path("/{tenantDomain}/favicon")
+ @ApiOperation(
+ httpMethod = HTTPConstants.HEADER_GET,
+ value = "Get whitelabel favicon",
+ notes = "Get whitelabel favicon for the tenant of the logged in user",
+ tags = "Tenant Metadata Management"
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully retrieved white label favicon.",
+ 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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while getting white label artifact.",
+ response = ErrorResponse.class)
+ })
+ Response getWhiteLabelFavicon( @ApiParam(
+ name = "tenantDomain",
+ value = "The tenant domain.",
+ required = true) @PathParam("tenantDomain") String tenantDomain);
+
+ @GET
+ @Path("/{tenantDomain}/logo")
+ @ApiOperation(
+ httpMethod = HTTPConstants.HEADER_GET,
+ value = "Get whitelabel logo",
+ notes = "Get whitelabel logo for the tenant of the logged in user",
+ tags = "Tenant Metadata Management"
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully retrieved white label logo.",
+ response = Metadata.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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while getting white label artifact.",
+ response = ErrorResponse.class)
+ })
+ Response getWhiteLabelLogo(
+ @ApiParam(
+ name = "tenantDomain",
+ value = "The tenant domain.",
+ required = true)
+ @PathParam("tenantDomain") String tenantDomain);
+
+ @GET
+ @Path("/{tenantDomain}/icon")
+ @ApiOperation(
+ httpMethod = HTTPConstants.HEADER_GET,
+ value = "Get whitelabel logo icon",
+ notes = "Get whitelabel logo icon for the tenant of the logged in user",
+ tags = "Tenant Metadata Management"
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully retrieved white label logo.",
+ response = Metadata.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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while getting white label artifact.",
+ response = ErrorResponse.class)
+ })
+ Response getWhiteLabelLogoIcon( @ApiParam(
+ name = "tenantDomain",
+ value = "The tenant domain.",
+ required = true) @PathParam("tenantDomain") String tenantDomain);
+
+ @PUT
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = HTTPConstants.HEADER_POST,
+ value = "Create whitelabel for tenant",
+ notes = "Create whitelabel for the tenant of the logged in user",
+ tags = "Tenant Metadata Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully created white label theme.",
+ response = Metadata.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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while creating white label theme.",
+ response = ErrorResponse.class)
+ })
+ Response updateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest);
+
+ @GET
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = HTTPConstants.HEADER_POST,
+ value = "Get whitelabel for tenant",
+ notes = "Get whitelabel for the tenant of the logged in user",
+ tags = "Tenant Metadata Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:view")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully fetched white label theme.",
+ response = Metadata.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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while fetching white label theme.",
+ response = ErrorResponse.class)
+ })
+ Response getWhiteLabelTheme();
+
+ @PUT
+ @Path("/reset")
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = HTTPConstants.HEADER_POST,
+ value = "Reset whitelabel for tenant",
+ notes = "Reset whitelabel to default for the tenant of the logged in user",
+ tags = "Tenant Metadata Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:whitelabel:update")
+ })
+ }
+ )
+ @ApiResponses(
+ value = {
+ @ApiResponse(
+ code = 200,
+ message = "OK. \n Successfully fetched white label theme.",
+ response = Metadata.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 = 500,
+ message = "Internal Server Error. " +
+ "\n Server error occurred while deleting white label theme.",
+ response = ErrorResponse.class)
+ })
+ Response resetWhiteLabel();
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java
index 3079dd4ad3f..b0c850de950 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/DeviceManagementAdminService.java
@@ -65,6 +65,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.sql.Timestamp;
import java.util.List;
@SwaggerDefinition(
@@ -110,7 +111,14 @@ import java.util.List;
key = "perm:devices:permanent-delete",
roles = {"Internal/devicemgt-admin"},
permissions = {"/device-mgt/admin/devices/permanent-delete"}
- )
+ ),
+ @Scope(
+ name = "Get Usage of Devices",
+ description = "Get Usage of Devices",
+ key = "perm:admin:usage:view",
+ roles = {"Internal/devicemgt-admin"},
+ permissions = {"/device-mgt/admin/devices/usage/view"}
+ ),
}
)
public interface DeviceManagementAdminService {
@@ -423,4 +431,78 @@ public interface DeviceManagementAdminService {
List actions
);
+ @GET
+ @Path("/billing")
+ @Produces(MediaType.APPLICATION_JSON)
+ @ApiOperation(
+ produces = MediaType.APPLICATION_JSON,
+ httpMethod = "GET",
+ value = "Getting Cost details of devices in a tenant",
+ notes = "Provides individual cost and total cost of all devices per tenant.",
+ tags = "Device Management",
+ extensions = {
+ @Extension(properties = {
+ @ExtensionProperty(name = Constants.SCOPE, value = "perm:admin:usage:view")
+ })
+ }
+ )
+ @ApiResponses(value = {
+ @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of devices.",
+ response = DeviceList.class,
+ responseHeaders = {
+ @ResponseHeader(
+ name = "Content-Type",
+ description = "The content type of the body"),
+ @ResponseHeader(
+ name = "Content-Disposition",
+ description = "The content disposition 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 = 400,
+ message = "The incoming request has more than one selection criteria defined via the query parameters.",
+ response = ErrorResponse.class),
+ @ApiResponse(
+ code = 404,
+ message = "The search criteria did not match any device registered with the server.",
+ 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 getBilling(
+ @ApiParam(
+ name = "tenantDomain",
+ value = "The tenant domain.",
+ required = false)
+ @QueryParam("tenantDomain")
+ String tenantDomain,
+ @ApiParam(
+ name = "startDate",
+ value = "The start date.",
+ required = false)
+ @QueryParam("startDate")
+ Timestamp startDate,
+ @ApiParam(
+ name = "endDate",
+ value = "The end date.",
+ required = false)
+ @QueryParam("endDate")
+ Timestamp endDate);
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
index 9c253c4fa6e..d0539f7b8b5 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/ActivityProviderServiceImpl.java
@@ -74,9 +74,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
activity = dmService.getOperationByActivityId(id);
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();
+ String msg = "No activity can be " +
+ "found upon the provided activity id '" + id + "'";
+ return Response.status(404).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
@@ -98,10 +98,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
List idList;
idList = activityIdList.getIdList();
if (idList == null || idList.isEmpty()) {
- String msg = "Activity Ids shouldn't be empty";
+ String msg = "Activities should not be empty";
log.error(msg);
- return Response.status(400).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(400).entity(msg).build();
}
Response validationFailedResponse = validateAdminPermission();
if (validationFailedResponse == null) {
@@ -125,8 +124,7 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
} else {
String msg = "No activity found with the given IDs.";
log.error(msg);
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(404).entity(msg).build();
}
} catch (OperationManagementException e) {
String msg = "ErrorResponse occurred while fetching the activity list for the supplied ids.";
@@ -162,9 +160,9 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
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();
+ String msg = "No activity can be " +
+ "found upon the provided activity id '" + id + "'";
+ return Response.status(404).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(activity).build();
} catch (OperationManagementException e) {
@@ -247,9 +245,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
- return Response.status(400).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "Invalid date string is provided in 'If-Modified-Since' header").build()).build();
+ String msg = "Invalid date string is provided in [If-Modified-Since] header.";
+ return Response.status(400).entity(msg).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
timestamp = ifModifiedSinceTimestamp / 1000;
@@ -259,9 +256,8 @@ public class ActivityProviderServiceImpl implements ActivityInfoProviderService
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
- return Response.status(400).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "Invalid date string is provided in 'since' filter").build()).build();
+ String msg = "Invalid date string is provided in [since] filter.";
+ return Response.status(400).entity(msg).build();
}
sinceTimestamp = sinceDate.getTime();
timestamp = sinceTimestamp / 1000;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java
index 4cba178f128..23be4d88ebb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceEventManagementServiceImpl.java
@@ -1,11 +1,19 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.AnalyticsArtifactsDeployer;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.dto.*;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventReceiverDeployerException;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventPublisherDeployerException;
+import io.entgra.device.mgt.core.apimgt.analytics.extension.exception.EventStreamDeployerException;
import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Stub;
+import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.databridge.commons.StreamDefinition;
+import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.Attribute;
import org.wso2.carbon.device.mgt.jaxrs.beans.analytics.AttributeType;
@@ -15,26 +23,40 @@ 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.input.adapter.core.InputEventAdapterConfiguration;
+import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
+import org.wso2.carbon.event.publisher.core.EventPublisherService;
+import org.wso2.carbon.event.publisher.core.config.EventPublisherConfiguration;
+import org.wso2.carbon.event.publisher.core.config.mapping.JSONOutputMapping;
+import org.wso2.carbon.event.publisher.core.config.mapping.MapOutputMapping;
+import org.wso2.carbon.event.publisher.core.exception.EventPublisherConfigurationException;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceCallbackHandler;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
+import org.wso2.carbon.event.receiver.core.EventReceiverService;
+import org.wso2.carbon.event.receiver.core.config.EventReceiverConfiguration;
+import org.wso2.carbon.event.receiver.core.config.mapping.JSONInputMapping;
+import org.wso2.carbon.event.receiver.core.config.mapping.WSO2EventInputMapping;
+import org.wso2.carbon.event.receiver.core.exception.EventReceiverConfigurationException;
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.core.EventStreamService;
+import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
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.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
+import javax.validation.Valid;
+import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.rmi.RemoteException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
/**
@@ -173,65 +195,129 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
/**
* Deploy Event Stream, Receiver, Publisher and Store Configuration.
*/
-// @POST
-// @Path("/{type}")
-// @Override
-// public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
-// @QueryParam("skipPersist") boolean skipPersist,
-// @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
-// @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, isSharedWithAllTenants, deviceType);
-// if (!skipPersist) {
-// 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, isSharedWithAllTenants, 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();
-// }
-// }
+ @POST
+ @Path("/{type}")
+ @Override
+ public Response deployDeviceTypeEventDefinition(@PathParam("type") String deviceType,
+ @QueryParam("skipPersist") boolean skipPersist,
+ @QueryParam("isSharedWithAllTenants") boolean isSharedWithAllTenants,
+ @Valid List deviceTypeEvents) {
+
+
+ String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+ try {
+ for (DeviceTypeEvent deviceTypeEvent : deviceTypeEvents) {
+ TransportType transportType = deviceTypeEvent.getTransportType();
+ EventAttributeList eventAttributes = deviceTypeEvent.getEventAttributeList();
+ String eventName = deviceTypeEvent.getEventName();
+
+
+ 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();
+ }
+ // event stream
+ String streamName = DeviceMgtAPIUtils.getStreamDefinition(deviceType, tenantDomain, eventName);
+ AnalyticsArtifactsDeployer artifactsDeployer = new AnalyticsArtifactsDeployer();
+ List props = new ArrayList<>();
+ for (Attribute attribute : eventAttributes.getList()) {
+ props.add(new Property(attribute.getName(), attribute.getType().name()));
+ }
+ EventStreamData eventStreamData = new EventStreamData();
+ eventStreamData.setName(streamName);
+ eventStreamData.setVersion(Constants.DEFAULT_STREAM_VERSION);
+ eventStreamData.setMetaData(new MetaData(DEFAULT_DEVICE_ID_ATTRIBUTE, "STRING"));
+ eventStreamData.setPayloadData(props);
+ artifactsDeployer.deployEventStream(eventStreamData, tenantId);
+
+ // event receiver
+ String receiverName = getReceiverName(deviceType, tenantDomain, transportType, eventName);
+ EventReceiverData receiverData = new EventReceiverData();
+ receiverData.setName(receiverName);
+ receiverData.setStreamName(streamName);
+ receiverData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
+ List propertyList = new ArrayList<>();
+ if (transportType == TransportType.MQTT) {
+ receiverData.setEventAdapterType(OAUTH_MQTT_ADAPTER_TYPE);
+ propertyList.add(new Property(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER));
+ propertyList.add(new Property(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR));
+ String topic;
+ if (!StringUtils.isEmpty(deviceTypeEvent.getEventTopicStructure())) {
+ if (isSharedWithAllTenants) {
+ topic = deviceTypeEvent.getEventTopicStructure().replace("${deviceId}", "+")
+ .replace("${deviceType}", deviceType)
+ .replace("${tenantDomain}", "+");
+ } else {
+ topic = deviceTypeEvent.getEventTopicStructure().replace("${deviceId}", "+")
+ .replace("${deviceType}", deviceType)
+ .replace("${tenantDomain}", tenantDomain);
+ }
+ } else {
+ if (isSharedWithAllTenants) {
+ topic = "+/" + deviceType + "/+/events";
+ } else {
+ topic = tenantDomain + "/" + deviceType + "/+/events";
+ }
+ }
+ propertyList.add(new Property("topic", topic));
+ receiverData.setCustomMappingType("json");
+
+ } else {
+ receiverData.setEventAdapterType(THRIFT_ADAPTER_TYPE);
+ propertyList.add(new Property("events.duplicated.in.cluster", "false"));
+ receiverData.setCustomMappingType("wso2event");
+ }
+ receiverData.setPropertyList(propertyList);
+ artifactsDeployer.deployEventReceiver(receiverData, tenantId);
+
+ if (!skipPersist) {
+ // rdbms event publisher
+ String rdbmsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_rdbms_publisher";
+
+ EventPublisherData eventPublisherData = new EventPublisherData();
+ eventPublisherData.setName(rdbmsPublisherName);
+ eventPublisherData.setStreamName(streamName);
+ eventPublisherData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
+ eventPublisherData.setEventAdaptorType("rdbms");
+ eventPublisherData.setCustomMappingType("map");
+ List publisherProps = new ArrayList<>();
+ publisherProps.add(new Property("datasource.name", "EVENT_DB"));
+ publisherProps.add(new Property("table.name", "table_" + rdbmsPublisherName.replace(".", "")));
+ publisherProps.add(new Property("execution.mode", "insert"));
+ eventPublisherData.setPropertyList(publisherProps);
+ artifactsDeployer.deployEventPublisher(eventPublisherData, tenantId);
+ }
+
+ // web socket event publisher
+ String wsPublisherName = getPublisherName(deviceType, tenantDomain, eventName) + "_ws_publisher";
+ EventPublisherData wsEventPublisherData = new EventPublisherData();
+ wsEventPublisherData.setName(wsPublisherName);
+ wsEventPublisherData.setStreamName(streamName);
+ wsEventPublisherData.setStreamVersion(Constants.DEFAULT_STREAM_VERSION);
+ wsEventPublisherData.setEventAdaptorType("websocket-local");
+ wsEventPublisherData.setCustomMappingType("json");
+ artifactsDeployer.deployEventPublisher(wsEventPublisherData, tenantId);
+
+ }
+ return Response.ok().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 (EventStreamDeployerException e) {
+ log.error("Failed while deploying event stream definition, tenantDomain: " + tenantDomain, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ } catch (EventPublisherDeployerException e) {
+ log.error("Failed while deploying event publisher, tenantDomain: " + tenantDomain, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ } catch (EventReceiverDeployerException e) {
+ log.error("Failed while deploying event receiver, tenantDomain: " + tenantDomain, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
+ }
+ }
/**
* Delete device type specific artifacts from DAS.
@@ -498,160 +584,174 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
// return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
// }
// }
-
-
- private void publishEventReceivers(String streamNameWithVersion, TransportType transportType
- , String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType)
- throws RemoteException, UserStoreException, JWTClientException {
- EventReceiverAdminServiceStub receiverAdminServiceStub = DeviceMgtAPIUtils.getEventReceiverAdminServiceStub();
+ private void publishEventReceivers(String streamName, String version, TransportType transportType
+ , String requestedTenantDomain, boolean isSharedWithAllTenants, String deviceType,
+ String eventTopicStructure, String receiverName) throws EventReceiverConfigurationException {
+ EventReceiverService eventReceiverService = DeviceMgtAPIUtils.getEventReceiverService();
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);
+// TransportType transportTypeToBeRemoved = TransportType.HTTP;
+// if (transportType == TransportType.HTTP) {
+// transportTypeToBeRemoved = TransportType.MQTT;
+// }
+// String eventRecieverNameTobeRemoved = getReceiverName(deviceType, requestedTenantDomain, transportTypeToBeRemoved);
+ EventReceiverConfiguration eventReceiverConfiguration =
+ eventReceiverService.getActiveEventReceiverConfiguration(receiverName);
+ if (eventReceiverConfiguration != null) {
+ eventReceiverService.undeployActiveEventReceiverConfiguration(receiverName);
}
- String adapterType = OAUTH_MQTT_ADAPTER_TYPE;
- BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[];
+ InputEventAdapterConfiguration inputEventAdapterConfiguration = new InputEventAdapterConfiguration();
+ Map propertyMap = new HashMap<>();
if (transportType == TransportType.MQTT) {
- basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[3];
+ inputEventAdapterConfiguration.setType(OAUTH_MQTT_ADAPTER_TYPE);
String topic;
- if (isSharedWithAllTenants) {
- topic = "+/" + deviceType + "/+/events";
+ if (!StringUtils.isEmpty(eventTopicStructure)) {
+ if (isSharedWithAllTenants) {
+ topic = eventTopicStructure.replace("${deviceId}", "+")
+ .replace("${deviceType}", deviceType)
+ .replace("${tenantDomain}", "+");
+ } else {
+ topic = eventTopicStructure.replace("${deviceId}", "+")
+ .replace("${deviceType}", deviceType)
+ .replace("${tenantDomain}", requestedTenantDomain);
+ }
} else {
- topic = requestedTenantDomain + "/" + deviceType + "/+/events";
+ if (isSharedWithAllTenants) {
+ topic = "+/" + deviceType + "/+/events";
+ } else {
+ topic = requestedTenantDomain + "/" + deviceType + "/+/events";
+ }
}
- basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("topic", topic);
- basicInputAdapterPropertyDtos[1] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_TRANSFORMER_TYPE
- , MQTT_CONTENT_TRANSFORMER);
- basicInputAdapterPropertyDtos[2] = getBasicInputAdapterPropertyDto(MQTT_CONTENT_VALIDATOR_TYPE
- , MQTT_CONTENT_VALIDATOR);
+ propertyMap.put("topic", topic);
+ propertyMap.put(MQTT_CONTENT_TRANSFORMER_TYPE, MQTT_CONTENT_TRANSFORMER);
+ propertyMap.put(MQTT_CONTENT_VALIDATOR_TYPE, MQTT_CONTENT_VALIDATOR);
} else {
- adapterType = THRIFT_ADAPTER_TYPE;
- basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1];
- basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("events.duplicated.in.cluster", "false");
+ inputEventAdapterConfiguration.setType(THRIFT_ADAPTER_TYPE);
+ propertyMap.put("events.duplicated.in.cluster", "false");
}
- String eventRecieverName = getReceiverName(deviceType, requestedTenantDomain, transportType);
- if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
+ inputEventAdapterConfiguration.setProperties(propertyMap);
+
+ if (eventReceiverService.getActiveEventReceiverConfiguration(receiverName) == null) {
+ EventReceiverConfiguration configuration = new EventReceiverConfiguration();
+ configuration.setEventReceiverName(receiverName);
+ configuration.setToStreamName(streamName);
+ configuration.setToStreamVersion(version);
+ configuration.setFromAdapterConfiguration(inputEventAdapterConfiguration);
if (transportType == TransportType.MQTT) {
- receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion
- , adapterType, null, basicInputAdapterPropertyDtos, false);
+ JSONInputMapping jsonInputMapping = new JSONInputMapping();
+ jsonInputMapping.setCustomMappingEnabled(false);
+ configuration.setInputMapping(jsonInputMapping);
+ eventReceiverService.deployEventReceiverConfiguration(configuration);
} else {
- receiverAdminServiceStub.deployWso2EventReceiverConfiguration(eventRecieverName, streamNameWithVersion
- , adapterType, null, null, null, basicInputAdapterPropertyDtos, false, null);
+ WSO2EventInputMapping wso2EventInputMapping = new WSO2EventInputMapping();
+ wso2EventInputMapping.setCustomMappingEnabled(false);
+ configuration.setInputMapping(wso2EventInputMapping);
+ eventReceiverService.deployEventReceiverConfiguration(configuration);
}
}
- } finally {
- cleanup(receiverAdminServiceStub);
+ } catch (EventReceiverConfigurationException e) {
+ log.error("Error while publishing event receiver" , e);
+ throw new EventReceiverConfigurationException(e);
}
+
}
- private void publishStreamDefinitons(String streamName, String version, String deviceType
- , EventAttributeList eventAttributes)
- throws RemoteException, UserStoreException, JWTClientException {
- EventStreamAdminServiceStub eventStreamAdminServiceStub = DeviceMgtAPIUtils.getEventStreamAdminServiceStub();
+ private void publishStreamDefinitons(String streamName, String version, EventAttributeList eventAttributes)
+ throws MalformedStreamDefinitionException, EventStreamConfigurationException {
+ EventStreamService eventStreamService = DeviceMgtAPIUtils.getEventStreamService();
+
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;
+ StreamDefinition streamDefinition = new StreamDefinition(streamName, version);
+
+ List payloadDataAttributes = new ArrayList<>();
for (Attribute attribute : eventAttributes.getList()) {
- EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
- eventStreamAttributeDto.setAttributeName(attribute.getName());
- eventStreamAttributeDto.setAttributeType(attribute.getType().toString());
- eventStreamAttributeDtos[i] = eventStreamAttributeDto;
- i++;
+ payloadDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(attribute.getName(),
+ org.wso2.carbon.databridge.commons.AttributeType.valueOf(attribute.getType().name())));
}
+ streamDefinition.setPayloadData(payloadDataAttributes);
+
+ List metaDataAttributes = new ArrayList<>();
+ metaDataAttributes.add(new org.wso2.carbon.databridge.commons.Attribute(DEFAULT_DEVICE_ID_ATTRIBUTE,
+ org.wso2.carbon.databridge.commons.AttributeType.STRING));
+ streamDefinition.setMetaData(metaDataAttributes);
- 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);
+ if (eventStreamService.getStreamDefinition(streamDefinition.getStreamId()) != null) {
+ eventStreamService.removeEventStreamDefinition(streamName, version);
+ eventStreamService.addEventStreamDefinition(streamDefinition);
} else {
- eventStreamAdminServiceStub.addEventStreamDefinitionAsDto(eventStreamDefinitionDto);
+ eventStreamService.addEventStreamDefinition(streamDefinition);
}
- } finally {
- cleanup(eventStreamAdminServiceStub);
+
+ } catch (MalformedStreamDefinitionException e) {
+ log.error("Error while initializing stream definition " , e);
+ throw new MalformedStreamDefinitionException(e);
+ } catch (EventStreamConfigurationException e) {
+ log.error("Error while configuring stream definition " , e);
+ throw new EventStreamConfigurationException(e);
}
}
+ /*
-// 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 publishEventStore(String streamName, String version, String publisherName)
+ throws EventPublisherConfigurationException {
+
+ EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
- 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);
+ if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
+ EventPublisherConfiguration configuration = new EventPublisherConfiguration();
+ configuration.setEventPublisherName(publisherName);
+ configuration.setFromStreamName(streamName);
+ configuration.setFromStreamVersion(version);
+ MapOutputMapping mapOutputMapping = new MapOutputMapping();
+ mapOutputMapping.setCustomMappingEnabled(false);
+ configuration.setOutputMapping(mapOutputMapping);
+ OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
+ outputEventAdapterConfiguration.setType("rdbms");
+ Map staticProperties = new HashMap<>();
+ staticProperties.put("datasource.name", "EVENT_DB");
+ staticProperties.put("execution.mode", "insert");
+ staticProperties.put("table.name", "table_" + publisherName.replace(".", ""));
+ outputEventAdapterConfiguration.setStaticProperties(staticProperties);
+ configuration.setProcessEnabled(true);
+ configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
+ eventPublisherService.deployEventPublisherConfiguration(configuration);
}
- } finally {
- cleanup(eventPublisherAdminServiceStub);
+
+ } catch (EventPublisherConfigurationException e) {
+ log.error("Error while publishing to rdbms store" , e);
+ throw new EventPublisherConfigurationException(e);
}
}
+ private void publishWebsocketPublisherDefinition(String streamName, String version, String publisherName)
+ throws EventPublisherConfigurationException {
+ EventPublisherService eventPublisherService = DeviceMgtAPIUtils.getEventPublisherService();
+
+ try {
+ if (eventPublisherService.getActiveEventPublisherConfiguration(publisherName) == null) {
+ EventPublisherConfiguration configuration = new EventPublisherConfiguration();
+ configuration.setEventPublisherName(publisherName);
+ configuration.setFromStreamName(streamName);
+ configuration.setFromStreamVersion(version);
+ JSONOutputMapping jsonOutputMapping = new JSONOutputMapping();
+ jsonOutputMapping.setCustomMappingEnabled(false);
+ configuration.setOutputMapping(jsonOutputMapping);
+ OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
+ outputEventAdapterConfiguration.setType("websocket-local");
+ configuration.setToAdapterConfiguration(outputEventAdapterConfiguration);
+ eventPublisherService.deployEventPublisherConfiguration(configuration);
+ }
+ } catch (EventPublisherConfigurationException e) {
+ log.error("Error while publishing to websocket-local" , e);
+ throw new EventPublisherConfigurationException(e);
+ }
+
+ }
+
private BasicInputAdapterPropertyDto getBasicInputAdapterPropertyDto(String key, String value) {
BasicInputAdapterPropertyDto basicInputAdapterPropertyDto = new BasicInputAdapterPropertyDto();
basicInputAdapterPropertyDto.setKey(key);
@@ -667,6 +767,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-" + transportType.toString() + "-receiver";
}
+ private String getReceiverName(String deviceType, String tenantDomain, TransportType transportType, String eventName) {
+ return eventName + "-" + getReceiverName(deviceType, tenantDomain, transportType);
+ }
+
+ private String getPublisherName(String tenantDomain, String deviceType, String eventName) {
+ return eventName + "_" + tenantDomain.replace(".", "_") + "_" + deviceType;
+ }
private void cleanup(Stub stub) {
if (stub != null) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java
index b8c626cb415..1e9d741aa95 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImpl.java
@@ -37,33 +37,26 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
import com.google.gson.Gson;
+import io.entgra.application.mgt.common.ApplicationInstallResponse;
+import io.entgra.application.mgt.common.SubscriptionType;
+import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
import io.entgra.application.mgt.common.services.ApplicationManager;
+import io.entgra.application.mgt.common.services.SubscriptionManager;
+import io.entgra.application.mgt.core.util.HelperUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.json.JSONException;
import org.json.JSONObject;
+import org.wso2.carbon.apimgt.keymgt.extension.DCRResponse;
+import org.wso2.carbon.apimgt.keymgt.extension.TokenRequest;
+import org.wso2.carbon.apimgt.keymgt.extension.TokenResponse;
+import org.wso2.carbon.apimgt.keymgt.extension.exception.KeyMgtException;
+import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtService;
+import org.wso2.carbon.apimgt.keymgt.extension.service.KeyMgtServiceImpl;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
-import io.entgra.application.mgt.common.ApplicationInstallResponse;
-import io.entgra.application.mgt.common.SubscriptionType;
-import io.entgra.application.mgt.common.exception.SubscriptionManagementException;
-import io.entgra.application.mgt.common.services.SubscriptionManager;
-import io.entgra.application.mgt.core.util.HelperUtil;
-import org.wso2.carbon.device.mgt.common.DeviceFilters;
-import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
-import org.wso2.carbon.device.mgt.common.OperationLogFilters;
-import org.wso2.carbon.device.mgt.common.MDMAppConstants;
-import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
-import org.wso2.carbon.device.mgt.common.Feature;
-import org.wso2.carbon.device.mgt.common.FeatureManager;
-import org.wso2.carbon.device.mgt.common.Device;
-import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
-import org.wso2.carbon.device.mgt.common.PaginationRequest;
-import org.wso2.carbon.device.mgt.common.PaginationResult;
-import org.wso2.carbon.device.mgt.common.TrackerDeviceInfo;
-import org.wso2.carbon.device.mgt.common.TrackerPermissionInfo;
+import org.wso2.carbon.device.mgt.common.*;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
@@ -72,12 +65,8 @@ import org.wso2.carbon.device.mgt.common.device.details.DeviceData;
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocationHistorySnapshotWrapper;
-import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
-import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
-import org.wso2.carbon.device.mgt.common.exceptions.InvalidConfigurationException;
-import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.exceptions.BadRequestException;
-import org.wso2.carbon.device.mgt.common.exceptions.UnAuthorizedException;
+import org.wso2.carbon.device.mgt.common.exceptions.*;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.Activity;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
@@ -91,6 +80,8 @@ import org.wso2.carbon.device.mgt.common.search.PropertyMap;
import org.wso2.carbon.device.mgt.common.search.SearchContext;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceStatus;
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.TrackerManagementDAOException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
@@ -103,19 +94,10 @@ import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.core.traccar.api.service.DeviceAPIClientService;
-import org.wso2.carbon.device.mgt.core.traccar.api.service.impl.DeviceAPIClientServiceImpl;
import org.wso2.carbon.device.mgt.core.traccar.common.TraccarHandlerConstants;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
-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.DeviceCompliance;
-import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationList;
-import org.wso2.carbon.device.mgt.jaxrs.beans.OperationStatusBean;
-import org.wso2.carbon.device.mgt.jaxrs.beans.ComplianceDeviceList;
-import org.wso2.carbon.device.mgt.jaxrs.beans.OperationRequest;
-import org.wso2.carbon.device.mgt.jaxrs.beans.OperationList;
-import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationUninstallation;
+import org.wso2.carbon.device.mgt.jaxrs.beans.*;
import org.wso2.carbon.device.mgt.jaxrs.service.api.DeviceManagementService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@@ -128,29 +110,17 @@ import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerSer
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.user.api.UserStoreException;
-import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.validation.Valid;
-import javax.ws.rs.Consumes;
import javax.validation.constraints.Size;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-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.PathParam;
-import javax.ws.rs.QueryParam;
+import javax.ws.rs.*;
import javax.ws.rs.core.Response;
-import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
-import java.util.*;
+import java.util.ArrayList;
import java.util.Date;
import java.util.List;
-import java.util.ArrayList;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
@@ -199,10 +169,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
@QueryParam("limit") int limit) {
try {
if (!StringUtils.isEmpty(name) && !StringUtils.isEmpty(role)) {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Request contains both name and role " +
- "parameters. Only one is allowed " +
- "at once.").build()).build();
+ String msg = "Request contains both name and role parameters. Only one is allowed at once.";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
// RequestValidationUtil.validateSelectionCriteria(type, user, roleName, ownership, status);
RequestValidationUtil.validatePaginationParameters(offset, limit);
@@ -291,9 +259,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
- "string is provided in 'If-Modified-Since' header").build()).build();
+ String msg = "Invalid date string is provided in [If-Modified-Since] header";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
request.setSince(sinceDate);
if (requireDeviceInfo) {
@@ -312,9 +279,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
- "string is provided in 'since' filter").build()).build();
+ String msg = "Invalid date string is provided in [since] filter";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
request.setSince(sinceDate);
if (requireDeviceInfo) {
@@ -355,105 +321,6 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
}
- @GET
- @Override
- @Path("/billing")
- public Response getDevicesBilling(
- @QueryParam("tenantDomain") String tenantDomain,
- @QueryParam("startDate") Timestamp startDate,
- @QueryParam("endDate") Timestamp endDate,
- @QueryParam("generateBill") boolean generateBill,
- @QueryParam("offset") int offset,
- @DefaultValue("10")
- @QueryParam("limit") int limit) {
- try {
- RequestValidationUtil.validatePaginationParameters(offset, limit);
- DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
- PaginationRequest request = new PaginationRequest(offset, limit);
- PaginationResult result;
- DeviceList devices = new DeviceList();
- int tenantId = 0;
- RealmService realmService = DeviceMgtAPIUtils.getRealmService();
-
- if (!tenantDomain.isEmpty()) {
- tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
- } else {
- tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- }
-
- try {
- result = dms.getAllDevicesBillings(request, tenantId, tenantDomain, startDate, endDate, generateBill);
- } catch (Exception exception) {
- String msg = "Error occurred when trying to retrieve billing data";
- log.error(msg, exception);
- return Response.serverError().entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
- }
-
- int resultCount = result.getRecordsTotal();
- if (resultCount == 0) {
- Response.status(Response.Status.OK).entity(devices).build();
- }
-
- devices.setList((List) result.getData());
- devices.setBilledDateIsValid(result.isBilledDateIsValid());
- devices.setMessage(result.getMessage());
- devices.setCount(result.getRecordsTotal());
- devices.setTotalCost(result.getTotalCost());
- return Response.status(Response.Status.OK).entity(devices).build();
- } catch (Exception e) {
- String msg = "Error occurred while retrieving billing data";
- log.error(msg, e);
- return Response.serverError().entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
- }
- }
-
- @GET
- @Override
- @Path("/billing/file")
- public Response exportBilling(
- @QueryParam("tenantDomain") String tenantDomain,
- @QueryParam("startDate") Timestamp startDate,
- @QueryParam("endDate") Timestamp endDate,
- @QueryParam("generateBill") boolean generateBill) {
-
- try {
- DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
- PaginationResult result;
- int tenantId = 0;
- RealmService realmService = DeviceMgtAPIUtils.getRealmService();
- DeviceList devices = new DeviceList();
-
- if (!tenantDomain.isEmpty()) {
- tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
- } else {
- tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
- }
-
- try {
- result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate, generateBill);
-
- } catch (Exception exception) {
- String msg = "Error occurred when trying to retrieve billing data without pagination";
- log.error(msg, exception);
- return null;
- }
-
- devices.setList((List) result.getData());
- devices.setBilledDateIsValid(result.isBilledDateIsValid());
- devices.setMessage(result.getMessage());
- devices.setCount(result.getRecordsTotal());
- devices.setTotalCost(result.getTotalCost());
- return Response.status(Response.Status.OK).entity(devices).build();
- } catch (Exception e) {
- String msg = "Error occurred while retrieving billing data without pagination";
- log.error(msg, e);
- return null;
- }
-
- }
-
@GET
@Override
@Path("/user-devices")
@@ -646,6 +513,10 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String msg = "Error occurred while retrieving role list of user '" + authorizedUser + "'";
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }catch (BadRequestException e){
+ String msg = "Error occurred while validating the device group.";
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
PaginationResult result = dms.getAllDevices(request, false);
@@ -662,7 +533,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(devices).build();
} catch (BadRequestException e) {
- String msg = "Invalid type, use either 'path' or 'full'";
+ String msg = "Invalid type, use either [path] or [full]";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnAuthorizedException e) {
@@ -696,12 +567,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
boolean response = deviceManagementProviderService.disenrollDevice(deviceIdentifier);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
- String msg = "Error encountered while deleting device of type : " + deviceType + " and " +
- "ID : " + deviceId;
+ String msg = "Error encountered while deleting requested device of type : " + deviceType ;
log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()
- ).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -715,15 +583,17 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
Device persistedDevice = deviceManagementProviderService.getDevice(new DeviceIdentifier
(deviceId, deviceType), true);
persistedDevice.setName(device.getName());
- boolean response = deviceManagementProviderService.modifyEnrollment(persistedDevice);
- return Response.status(Response.Status.CREATED).entity(response).build();
+ System.out.println("This is rename device");
+ boolean responseOfmodifyEnrollment = deviceManagementProviderService.modifyEnrollment(persistedDevice);
+ boolean responseOfDeviceNameChanged = deviceManagementProviderService.sendDeviceNameChangedNotification(
+ persistedDevice);
+ boolean response = responseOfmodifyEnrollment && responseOfDeviceNameChanged;
+ return Response.status(Response.Status.CREATED).entity(response).build();
} catch (DeviceManagementException e) {
- log.error("Error encountered while updating device of type : " + deviceType + " and " +
- "ID : " + deviceId);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Error while updating " +
- "device of type " + deviceType + " and ID : " + deviceId).build()).build();
+ String msg = "Error encountered while updating requested device of type : " + deviceType ;
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -764,10 +634,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
sinceDate = format.parse(ifModifiedSince);
deviceData.setLastModifiedDate(sinceDate);
} catch (ParseException e) {
- String msg = "Invalid date string is provided in 'If-Modified-Since' header";
+ String msg = "Invalid date string is provided in [If-Modified-Since] header";
log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -794,9 +663,8 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
"after the timestamp provided in 'If-Modified-Since' header").build();
}
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_NOT_FOUND).setMessage("Requested device of type '" +
- type + "', which carries id '" + id + "' does not exist").build()).build();
+ String msg = "Requested device of type " + type + " does not exist";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(device).build();
}
@@ -817,7 +685,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
dms);
return Response.status(Response.Status.OK).entity(snapshotWrapper).build();
} catch (BadRequestException e) {
- String msg = "Invalid type, use either 'path' or 'full'";
+ String msg = "Invalid type, use either [path] or [full]";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (UnAuthorizedException e) {
@@ -863,12 +731,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
try {
sinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
- String message = "Error occurred while parse the since date.Invalid date string is provided in " +
- "'If-Modified-Since' header";
+ String message = "Invalid date string is provided in [If-Modified-Since] header";
log.error(message, e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Invalid date " +
- "string is provided in 'If-Modified-Since' header").build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
}
}
if (sinceDate != null) {
@@ -877,16 +742,15 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
String message = "No device is modified after the timestamp provided in 'If-Modified-Since' header";
log.error(message);
return Response.status(Response.Status.NOT_MODIFIED).entity("No device is modified " +
- "after the timestamp provided in 'If-Modified-Since' header").build();
+ "after the timestamp provided in [If-Modified-Since] header").build();
}
} else {
device = dms.getDevice(id, requireDeviceInfo);
}
if (device == null) {
- String message = "Device does not exist with id '" + id + "'";
+ String message = "Device does not exist";
log.error(message);
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setCode(404l).setMessage(message).build()).build();
+ return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(id, device.getType());
// check whether the user is authorized
@@ -911,6 +775,32 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.status(Response.Status.OK).entity(device).build();
}
+ @POST
+ @Path("/enrollment/guide")
+ @Override
+ public Response sendEnrollmentGuide(String enrolmentGuide) {
+ if (log.isDebugEnabled()) {
+ log.debug("Sending enrollment invitation mail to existing user.");
+ }
+ DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
+ if (!config.getEnrollmentGuideConfiguration().isEnabled()) {
+ String msg = "Sending enrollment guide config is not enabled.";
+ log.error(msg);
+ return Response.status(Response.Status.FORBIDDEN).entity(msg).build();
+ }
+ DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
+ try {
+ dms.sendEnrolmentGuide(enrolmentGuide);
+ return Response.status(Response.Status.OK).entity("Invitation mails have been sent.").build();
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred sending mail to group in enrollment guide";
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
+ }
+
+
@POST
@Path("/type/any/list")
@Override
@@ -918,7 +808,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceManagementProviderService deviceManagementProviderService =
DeviceMgtAPIUtils.getDeviceManagementService();
if (deviceIds == null || deviceIds.isEmpty()) {
- String msg = "Required values of device identifiers are not set..";
+ String msg = "Required values of device identifiers are not set.";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).build();
}
@@ -982,34 +872,131 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
return Response.status(Response.Status.OK).entity(deviceInfo).build();
+ }
+ @GET
+ @Path("/{type}/{id}/config")
+ @Override
+ public Response getDeviceConfiguration(
+ @PathParam("type") @Size(max = 45) String type,
+ @PathParam("id") @Size(max = 45) String id,
+ @HeaderParam("If-Modified-Since") String ifModifiedSince) {
+
+ DeviceConfig deviceConfig = new DeviceConfig();
+ deviceConfig.setDeviceId(id);
+ deviceConfig.setType(type);
+
+ // find token validity time
+ DeviceManagementProviderService deviceManagementProviderService =
+ DeviceMgtAPIUtils.getDeviceManagementService();
+ int validityTime = 3600;
+ // add scopes for event topics
+ List mqttEventTopicStructure = new ArrayList<>();
+ try {
+ DeviceType deviceType = deviceManagementProviderService.getDeviceType(type);
+ if (deviceType != null) {
+ if (deviceType.getDeviceTypeMetaDefinition().isLongLivedToken()) {
+ validityTime = Integer.MAX_VALUE;
+ }
+ mqttEventTopicStructure = deviceType.getDeviceTypeMetaDefinition().getMqttEventTopicStructures();
+ } else {
+ String msg = "Device not found, device id : " + id + ", device type : " + type;
+ log.error(msg);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while retrieving device, device id : " + id + ", device type : " + type;
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
+
+ String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
+ String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
+ String applicationName = type.replace(" ", "").replace("_", "")
+ + "_" + tenantDomain;
+
+ KeyMgtService keyMgtService = new KeyMgtServiceImpl();
+ try {
+ DCRResponse dcrResponse = keyMgtService.dynamicClientRegistration(applicationName, username,
+ "client_credentials", null, new String[] {"device_management"}, false, validityTime);
+ deviceConfig.setClientId(dcrResponse.getClientId());
+ deviceConfig.setClientSecret(dcrResponse.getClientSecret());
+
+ StringBuilder scopes = new StringBuilder("device_" + type.replace(" ", "")
+ .replace("_", "") + "_" + id);
+ for (String topic : mqttEventTopicStructure) {
+ if (topic.contains("${deviceId}")) {
+ topic = topic.replace("${deviceId}", id);
+ }
+ topic = topic.replace("/",":");
+// scopes.append(" perm:topic:sub:".concat(topic));
+ scopes.append(" perm:topic:pub:".concat(topic));
+ }
+
+ // add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/#
+ scopes.append(" perm:topic:sub:" + tenantDomain + ":" + type + ":" + id + ":operation");
+
+ // add scopes for update operation /tenantDomain/deviceType/deviceId/update/operation
+ scopes.append(" perm:topic:pub:" + tenantDomain + ":" + type + ":" + id + ":update:operation");
+
+ TokenRequest tokenRequest = new TokenRequest(dcrResponse.getClientId(), dcrResponse.getClientSecret(),
+ null, scopes.toString(), "client_credentials", null,
+ null, null, null, validityTime);
+ TokenResponse tokenResponse = keyMgtService.generateAccessToken(tokenRequest);
+ deviceConfig.setAccessToken(tokenResponse.getAccessToken());
+ deviceConfig.setRefreshToken(tokenResponse.getRefreshToken());
+
+ try {
+ deviceConfig.setPlatformConfiguration(deviceManagementProviderService.getConfiguration(type));
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while reading platform configurations token, device id : " + id + ", device type : " + type;
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
+
+ deviceConfig.setMqttGateway("tcp://" + System.getProperty("mqtt.broker.host") + ":" + System.getProperty("mqtt.broker.port"));
+ deviceConfig.setHttpGateway("http://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.http.port"));
+ deviceConfig.setHttpsGateway("https://" + System.getProperty("iot.gateway.host") + ":" + System.getProperty("iot.gateway.https.port"));
+
+ } catch (KeyMgtException e) {
+ String msg = "Error occurred while creating oauth application, device id : " + id + ", device type : " + type;
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ } catch (org.wso2.carbon.apimgt.keymgt.extension.exception.BadRequestException e) {
+ String msg = "Error occurred while generating token, device id : " + id + ", device type : " + type;
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
+ return Response.status(Response.Status.OK).entity(deviceConfig).build();
+
}
@GET
- @Path("/{type}/{id}/features")
+ @Path("/device-type/{type}/features")
@Override
public Response getFeaturesOfDevice(
@PathParam("type") @Size(max = 45) String type,
- @PathParam("id") @Size(max = 45) String id,
@HeaderParam("If-Modified-Since") String ifModifiedSince) {
List features = new ArrayList<>();
DeviceManagementProviderService dms;
try {
- RequestValidationUtil.validateDeviceIdentifier(type, id);
dms = DeviceMgtAPIUtils.getDeviceManagementService();
FeatureManager fm;
try {
fm = dms.getFeatureManager(type);
} catch (DeviceTypeNotFoundException e) {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder()
- .setMessage("No device type found with name '" + type + "'").build()).build();
+ String msg = "No device type found with name : " + type ;
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
if (fm != null) {
features = fm.getFeatures();
}
} catch (DeviceManagementException e) {
- String msg = "Error occurred while retrieving the list of features of '" + type + "' device, which " +
- "carries the id '" + id + "'";
+ String msg = "Error occurred while retrieving the list of features of '" + type + "'";
log.error(msg, e);
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
@@ -1224,8 +1211,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (InputValidationException e) {
- String msg = "Error occurred while fetching the operations for the '" + type + "' device, which " +
- "carries the id '" + id + "'";
+ String msg = "Error occurred while fetching the operations for the type : " + type + " device";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceManagementException e) {
@@ -1234,7 +1220,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceTypeNotFoundException e) {
- String msg = "No device type found with name '" + type + "'";
+ String msg = "No device type found with name : " + type ;
log.error(msg, e);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
@@ -1344,11 +1330,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
boolean response = deviceManagementProviderService.changeDeviceStatus(deviceIdentifier, newsStatus);
return Response.status(Response.Status.OK).entity(response).build();
} catch (DeviceManagementException e) {
- String msg = "Error occurred while changing device status of type : " + type + " and " +
- "device id : " + id;
+ String msg = "Error occurred while changing device status of device type : " + type ;
log.error(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -1360,7 +1344,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object
*/
@GET
- @Path("/{type}/{id}/getstatushistory")
+ @Path("/{type}/{id}/status-history")
public Response getDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this
@@ -1376,11 +1360,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List deviceStatusHistory = deviceManagementProviderService.getDeviceStatusHistory(persistedDevice);
return Response.status(Response.Status.OK).entity(deviceStatusHistory).build();
} catch (DeviceManagementException e) {
- String msg = "Error occurred while retreiving device status history for device of type : " + type + " and " +
- "device id : " + id;
+ String msg = "Error occurred while retrieving device status history for device of type : " + type ;
log.error(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -1392,7 +1374,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
* @return {@link Response} object
*/
@GET
- @Path("/{type}/{id}/getenrolmentstatushistory")
+ @Path("/{type}/{id}/enrolment-status-history")
public Response getCurrentEnrolmentDeviceStatusHistory(@PathParam("type") @Size(max = 45) String type,
@PathParam("id") @Size(max = 45) String id) {
//TODO check authorization for this or current enrolment should be based on for the enrolment associated with the user
@@ -1408,11 +1390,9 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
List deviceStatusHistory = deviceManagementProviderService.getDeviceCurrentEnrolmentStatusHistory(persistedDevice);
return Response.status(Response.Status.OK).entity(deviceStatusHistory).build();
} catch (DeviceManagementException e) {
- String msg = "Error occurred while retreiving device status history for device of type : " + type + " and " +
- "device id : " + id;
+ String msg = "Error occurred while retrieving device status history for device of type : " + type;
log.error(msg);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -1489,7 +1469,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
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";
+ String errorMessage = "Issue in retrieving device management service instance";
log.error(errorMessage, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(errorMessage).build()).build();
@@ -1689,7 +1669,7 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
DeviceType deviceTypeObj = DeviceManagerUtil.getDeviceType(
deviceType, tenantId);
if (deviceTypeObj == null) {
- String msg = "Error, device of type: " + deviceType + " does not exist";
+ String msg = "Device of type: " + deviceType + " does not exist";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java
index 393fd31ff59..b8d7aeb97ac 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceTypeManagementServiceImpl.java
@@ -141,16 +141,15 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
DeviceManagementProviderService dms;
try {
if (StringUtils.isEmpty(type)) {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Type cannot be empty.").build()).build();
+ String msg = "Type cannot be empty.";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
dms = DeviceMgtAPIUtils.getDeviceManagementService();
FeatureManager fm = dms.getFeatureManager(type);
if (fm == null) {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("No feature manager is " +
- "registered with the given type '" + type + "'").build()).build();
+ String msg = "No feature manager is registered with the given type : " + type ;
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
if (StringUtils.isEmpty(hidden)) {
@@ -165,11 +164,9 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
return Response.serverError().entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
} catch (DeviceTypeNotFoundException e) {
- String msg = "No device type found with name '" + type + "'";
+ String msg = "No device type found with name : " + type ;
log.error(msg, e);
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder()
- .setMessage(msg).build()).build();
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity(features).build();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
index 2207957a2ac..b2063f8985c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GeoLocationBasedServiceImpl.java
@@ -63,6 +63,7 @@ import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
import org.wso2.carbon.device.mgt.jaxrs.beans.EventAction;
import org.wso2.carbon.device.mgt.jaxrs.beans.GeofenceWrapper;
+import org.wso2.carbon.device.mgt.jaxrs.exception.BadRequestException;
import org.wso2.carbon.device.mgt.jaxrs.service.api.GeoLocationBasedService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.InputValidationException;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
@@ -107,8 +108,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@QueryParam("from") long from, @QueryParam("to") long to) {
try {
if (!DeviceManagerUtil.isPublishLocationResponseEnabled()) {
+ String msg = "Unable to retrieve Geo Device stats. Geo Data publishing does not enabled.";
return Response.status(Response.Status.BAD_REQUEST.getStatusCode())
- .entity("Unable to retrive Geo Device stats. Geo Data publishing does not enabled.").build();
+ .entity(msg).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(e.getMessage()).build();
@@ -277,7 +279,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
- return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
+ String msg = "Device not found.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@@ -288,12 +291,11 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
- String error = "A geo alert with this name already exists.";
+ String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
} catch (DeviceManagementException e) {
- String error = "Error occurred while retrieving the device enrollment info of " +
- deviceType + " with id: " + deviceId;
+ String error = "Error occurred while retrieving the device enrollment info of requested "+ deviceType + " device.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -314,7 +316,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
- String error = "A geo alert with this name already exists.";
+ String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -344,23 +346,23 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
- return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
+ String msg = "Device not found.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
geoService.updateGeoAlert(alert, identifier, alertType, device.getEnrolmentInfo().getOwner());
return Response.ok().build();
} catch (DeviceAccessAuthorizationException | GeoLocationBasedServiceException e) {
- String error = "Error occurred while creating the geo alert for " + deviceType + " with id: " + deviceId;
+ String error = "Error occurred while updating the geo alert for " + deviceType + " with id: " + deviceId;
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
- String error = "A geo alert with this name already exists.";
+ String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
} catch (DeviceManagementException e) {
- String error = "Error occurred while retrieving the device enrollment info of " +
- deviceType + " with id: " + deviceId;
+ String error = "Error occurred while retrieving the device enrollment info of requested " + deviceType + " device.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -380,7 +382,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (AlertAlreadyExistException e) {
- String error = "A geo alert with this name already exists.";
+ String error = "A geo alert with this name already exists. Try with another name.";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -410,7 +412,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
- return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
+ String msg = "Device not found.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@@ -421,8 +424,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (DeviceManagementException e) {
- String error = "Error occurred while retrieving the device enrollment info of " +
- deviceType + " with id: " + deviceId;
+ String error = "Error occurred while retrieving the device enrollment info of requested " +deviceType + " device";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -467,7 +469,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
if (log.isDebugEnabled()) {
log.debug("Device not found: " + identifier.toString());
}
- return Response.status(Response.Status.NOT_FOUND.getStatusCode()).build();
+ String msg = "Device not found.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
@@ -497,8 +500,7 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
log.error(error, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build();
} catch (DeviceManagementException e) {
- String error = "Error occurred while retrieving the device enrollment info of " +
- deviceType + " with id: " + deviceId;
+ String error = "Error occurred while retrieving the device enrollment info of requested " + deviceType + " device";
log.error(error, e);
return Response.status(Response.Status.BAD_REQUEST).entity(error).build();
}
@@ -687,9 +689,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
@Consumes("application/json")
@Produces("application/json")
public Response createGeofence(GeofenceWrapper geofenceWrapper) {
- RequestValidationUtil.validateGeofenceData(geofenceWrapper);
- RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
try {
+ RequestValidationUtil.validateGeofenceData(geofenceWrapper);
+ RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
GeofenceData geofenceData = mapRequestGeofenceData(geofenceWrapper);
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (!geoService.createGeofence(geofenceData)) {
@@ -699,6 +701,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
}
return Response.status(Response.Status.CREATED).entity("Geo Fence record created successfully").build();
+ } catch (BadRequestException e){
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to create geofence";
log.error(msg, e);
@@ -895,9 +899,9 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
public Response updateGeofence(GeofenceWrapper geofenceWrapper,
@PathParam("fenceId") int fenceId,
@QueryParam("eventIds") int[] eventIds) {
- RequestValidationUtil.validateGeofenceData(geofenceWrapper);
- RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
try {
+ RequestValidationUtil.validateGeofenceData(geofenceWrapper);
+ RequestValidationUtil.validateEventConfigurationData(geofenceWrapper.getEventConfig());
GeofenceData geofenceData = mapRequestGeofenceData(geofenceWrapper);
GeoLocationProviderService geoService = DeviceMgtAPIUtils.getGeoService();
if (!geoService.updateGeofence(geofenceData, fenceId)) {
@@ -912,6 +916,8 @@ public class GeoLocationBasedServiceImpl implements GeoLocationBasedService {
geoService.updateGeoEventConfigurations(geofenceData, eventsToRemove,
geofenceData.getGroupIds(), fenceId);
return Response.status(Response.Status.CREATED).entity("Geo Fence update successfully").build();
+ } catch (BadRequestException e){
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
} catch (GeoLocationBasedServiceException e) {
String msg = "Failed to update geofence";
log.error(msg, e);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java
index 8927ea533d6..514685507df 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java
@@ -48,6 +48,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@@ -66,6 +67,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
+import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@@ -165,7 +167,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupAlreadyExistException e) {
- String msg = "Group already exists with name " + group.getName() + ".";
+ String msg = "Group already exists with name : " + group.getName() + ".";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
@@ -179,7 +181,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else {
- return Response.status(Response.Status.NOT_FOUND).build();
+ return Response.status(Response.Status.NOT_FOUND).entity("Group not found.").build();
}
} catch (GroupManagementException e) {
String error = "Error occurred while getting the group.";
@@ -196,7 +198,7 @@ public class GroupManagementServiceImpl implements GroupManagementService {
if (deviceGroup != null) {
return Response.status(Response.Status.OK).entity(deviceGroup).build();
} else {
- return Response.status(Response.Status.NOT_FOUND).build();
+ return Response.status(Response.Status.NOT_FOUND).entity("Group not found.").build();
}
} catch (GroupManagementException e) {
String error = "Error occurred while getting the group.";
@@ -218,11 +220,11 @@ public class GroupManagementServiceImpl implements GroupManagementService {
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupNotExistException e) {
- String msg = "Group doesn't exist with ID '" + deviceGroup.getGroupId() + "'.";
+ String msg = "Group does not exist.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
} catch (GroupAlreadyExistException e) {
- String msg = "Group already exists with name '" + deviceGroup.getName() + "'.";
+ String msg = "Group already exists with name : '" + deviceGroup.getName() + "'.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
@@ -429,4 +431,20 @@ public class GroupManagementServiceImpl implements GroupManagementService {
}
}
+ @POST
+ @Path("/device-types")
+ @Override
+ public Response getGroupHasDeviceTypes(List identifiers) {
+ try {
+ DeviceTypesOfGroups deviceTypesOfGroups = DeviceMgtAPIUtils.getGroupManagementProviderService()
+ .getDeviceTypesOfGroups(identifiers);
+
+ return Response.status(Response.Status.OK).entity(deviceTypesOfGroups).build();
+ } catch (GroupManagementException e) {
+ String msg = "Only numbers can exists in a group ID or Invalid Group ID provided.";
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ }
+ }
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/MetadataServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/MetadataServiceImpl.java
index 5a484bfa0c3..559ecc41ec0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/MetadataServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/MetadataServiceImpl.java
@@ -18,20 +18,27 @@
package org.wso2.carbon.device.mgt.jaxrs.service.impl;
+import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException;
+import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelTheme;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.jaxrs.beans.MetadataList;
import org.wso2.carbon.device.mgt.jaxrs.service.api.MetadataService;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.util.List;
import javax.ws.rs.Consumes;
@@ -147,4 +154,20 @@ public class MetadataServiceImpl implements MetadataService {
}
}
+ /**
+ * Useful to send files as application/octet-stream responses
+ */
+ private Response sendFileStream(byte[] content) throws IOException {
+ try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(content)) {
+ Response.ResponseBuilder response = Response
+ .ok(binaryDuplicate, MediaType.APPLICATION_OCTET_STREAM);
+ response.status(Response.Status.OK);
+ response.header("Content-Length", content.length);
+ return response.build();
+ } catch (IOException e) {
+ String msg = "Error occurred while creating input stream from buffer array. ";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java
index 6a2dbe68a3c..7405a73e722 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/PolicyManagementServiceImpl.java
@@ -40,6 +40,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@@ -83,8 +84,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
.validatePolicyDetails(policyWrapper);
// validation failure results;
if (!features.isEmpty()) {
- log.error("Policy feature/s validation failed.");
- return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
+ String msg = "Policy feature/s validation failed." ;
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " + features).build();
}
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
@@ -212,9 +214,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
policy = policyAdministratorPoint.getPolicy(id);
if (policy == null) {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "No policy found with the id '" + id + "'").build()).build();
+ String msg = "Policy not found.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving policy corresponding to the id '" + id + "'";
@@ -233,8 +234,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
.validatePolicyDetails(policyWrapper);
// validation failure results;
if (!features.isEmpty()) {
- log.error("Policy feature/s validation failed.");
- return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
+ String msg = "Policy feature/s validation failed." ;
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " + features).build();
}
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
try {
@@ -296,10 +298,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
//TODO:Check of this logic is correct
String modifiedInvalidPolicyIds =
invalidPolicyIds.substring(0, invalidPolicyIds.length() - 1);
- return Response.status(Response.Status.BAD_REQUEST).
- entity(new ErrorResponse.ErrorResponseBuilder().
- setMessage("Policies with the policy ID " + modifiedInvalidPolicyIds +
- " doesn't exist").build()).build();
+ String msg = "Policies does not exist.";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -329,9 +329,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully activated")
.build();
} else {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " +
- "not been activated").build()).build();
+ String msg = "Selected policies have not been activated.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@@ -361,9 +360,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
return Response.status(Response.Status.OK).entity("Selected policies have been successfully " +
"deactivated").build();
} else {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Selected policies have " +
- "not been deactivated").build()).build();
+ String msg = "Selected policies have not been activated.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@@ -412,9 +410,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
+ "updated.").build();
} else {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage("Policy priorities did "
- + "not update. Bad Request.").build()).build();
+ String msg = "Policy priorities did not update. Bad Request.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
}
@@ -440,9 +437,8 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
}
policy = policyManagementService.getAppliedPolicyToDevice(device);
if (policy == null) {
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "No policy found for device ID '" + deviceId + "'"+ deviceId).build()).build();
+ String msg = "Policy not found for the requested device.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving policy corresponding to the id '" + deviceType + "'"+ deviceId;
@@ -491,8 +487,9 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
= RequestValidationUtil.validateProfileFeatures(profileFeaturesList);
// validation failure results;
if (!features.isEmpty()) {
- log.error("Policy feature/s validation failed.");
- return Response.status(Response.Status.BAD_REQUEST).entity(features).build();
+ String msg = "Policy feature/s validation failed." ;
+ log.error(msg);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg + " Features : " +features).build();
}
return Response.status(Response.Status.OK).entity("Valid request").build();
@@ -508,18 +505,13 @@ public class PolicyManagementServiceImpl implements PolicyManagementService {
RequestValidationUtil.validatePaginationParameters(offset, limit);
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
List policies;
- List filteredPolicies;
PolicyList targetPolicies = new PolicyList();
+ PaginationRequest request = new PaginationRequest(offset, limit);
try {
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
- policies = policyAdministratorPoint.getPolicyList();
- targetPolicies.setCount(policies.size());
- if (offset == 0 && limit == 0) {
- targetPolicies.setList(policies);
- } else {
- filteredPolicies = FilteringUtil.getFilteredList(policies, offset, limit);
- targetPolicies.setList(filteredPolicies);
- }
+ policies = policyAdministratorPoint.getPolicyList(request);
+ targetPolicies.setCount(policyAdministratorPoint.getPolicyCount());
+ targetPolicies.setList(policies);
} catch (PolicyManagementException e) {
String msg = "Error occurred while retrieving all available policies";
log.error(msg, e);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java
index af05da7991f..0894b2f2cd6 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/RoleManagementServiceImpl.java
@@ -169,8 +169,9 @@ public class RoleManagementServiceImpl implements RoleManagementService {
try {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
if (!userRealm.getUserStoreManager().isExistingRole(roleName)) {
- return Response.status(404).entity(new ErrorResponse.ErrorResponseBuilder().setMessage(
- "No role exists with the name '" + roleName + "'").build()).build();
+
+ String msg = "No role exists with the name : " + roleName ;
+ return Response.status(404).entity(msg).build();
}
final UIPermissionNode rolePermissions = this.getUIPermissionNode(roleName, userRealm);
@@ -249,9 +250,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
if (!userStoreManager.isExistingRole(roleName)) {
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
- roleName + "'").build()).build();
+ String msg = "No role exists with the name : " + roleName ;
+ return Response.status(404).entity(msg).build();
}
roleInfo.setRoleName(roleName);
roleInfo.setUsers(userStoreManager.getUserListOfRole(roleName));
@@ -325,7 +325,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
}
if (ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(errorCode)) {
String roleName = roleInfo.getRoleName().split("/")[1];
- String msg = "Role already exists with name " + roleName + ".";
+ String msg = "Role already exists with name : " + roleName + ". Try with another role name.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
} else {
@@ -354,10 +354,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
roleName = userStoreName + "/" + roleName;
}
if (roles.size() < 2) {
- return Response.status(400).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("Combining Roles requires at least two roles.")
- .build()
- ).build();
+ String msg = "Combining Roles requires at least two roles.";
+ return Response.status(400).entity(msg).build();
}
for (String role : roles) {
RequestValidationUtil.validateRoleName(role);
@@ -374,9 +372,7 @@ public class RoleManagementServiceImpl implements RoleManagementService {
mergePermissions(new UIPermissionNode[]{getRolePermissions(role)}, permsSet);
}
} catch (IllegalArgumentException e) {
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(e.getMessage()).build()
- ).build();
+ return Response.status(404).entity(e.getMessage()).build();
}
Permission[] permissions = permsSet.toArray(new Permission[permsSet.size()]);
@@ -424,9 +420,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
- roleName + "'").build()).build();
+ String msg = "No role exists with the name : " + roleName ;
+ return Response.status(404).entity(msg).build();
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();
@@ -481,10 +476,23 @@ public class RoleManagementServiceImpl implements RoleManagementService {
return Response.status(Response.Status.OK).entity("Role '" + roleInfo.getRoleName() + "' has " +
"successfully been updated").build();
} catch (UserStoreException e) {
- String msg = "Error occurred while updating role '" + roleName + "'";
- log.error(msg, e);
- return Response.serverError().entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ String errorCode = "";
+ String errorMessage = e.getMessage();
+ if (errorMessage != null && !errorMessage.isEmpty() &&
+ errorMessage.contains(ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode())) {
+ errorCode = e.getMessage().split("-")[0].trim();
+ }
+ if (ErrorMessages.ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(errorCode)) {
+ String role = roleInfo.getRoleName().split("/")[1];
+ String msg = "Role already exists with name : " + role + ". Try with another role name.";
+ log.warn(msg);
+ return Response.status(Response.Status.CONFLICT).entity(msg).build();
+ }else{
+ String msg = "Error occurred while updating role '" + roleName + "'";
+ log.error(msg, e);
+ return Response.serverError().entity(
+ new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ }
} catch (UserAdminException e) {
String msg = "Error occurred while updating permissions of the role '" + roleName + "'";
log.error(msg, e);
@@ -559,9 +567,8 @@ public class RoleManagementServiceImpl implements RoleManagementService {
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
final UserStoreManager userStoreManager = userRealm.getUserStoreManager();
if (!userStoreManager.isExistingRole(roleName)) {
- return Response.status(404).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("No role exists with the name '" +
- roleName + "'").build()).build();
+ String msg = "No role exists with the name : " + roleName ;
+ return Response.status(404).entity(msg).build();
}
final AuthorizationManager authorizationManager = userRealm.getAuthorizationManager();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java
index 1fbb402dcd0..c6f6d882e05 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/UserManagementServiceImpl.java
@@ -157,10 +157,8 @@ public class UserManagementServiceImpl implements UserManagementService {
" already exists. Therefore, request made to add user was refused.");
}
// returning response with bad request state
- return Response.status(Response.Status.CONFLICT).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
- userInfo.getUsername() + " already exists. Therefore, request made to add user " +
- "was refused.").build()).build();
+ String msg = "User by username: " + userInfo.getUsername() + " already exists. Try with another username." ;
+ return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
String initialUserPassword;
@@ -290,9 +288,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist.");
}
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "User doesn't exist.").build()).build();
+ String msg = "User by username: " + username + " does not exist.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
BasicUserInfo user = this.getBasicUserInfo(username);
@@ -318,9 +315,8 @@ public class UserManagementServiceImpl implements UserManagementService {
log.debug("User by username: " + username +
" doesn't exists. Therefore, request made to update user was refused.");
}
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " +
- username + " doesn't exist.").build()).build();
+ String msg = "User by username: " + username + " does not exist.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
Map defaultUserClaims =
@@ -396,9 +392,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for removal.");
}
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("User '" +
- username + "' does not exist for removal.").build()).build();
+ String msg = "User by username: " + username + " does not exist for removal.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
// Un-enroll all devices for the user
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
@@ -430,9 +425,8 @@ public class UserManagementServiceImpl implements UserManagementService {
if (log.isDebugEnabled()) {
log.debug("User by username: " + username + " does not exist for role retrieval.");
}
- return Response.status(Response.Status.NOT_FOUND).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage("User by username: " + username +
- " does not exist for role retrieval.").build()).build();
+ String msg = "User by username: " + username + " does not exist for role retrieval.";
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
RoleList result = new RoleList();
@@ -867,8 +861,8 @@ public class UserManagementServiceImpl implements UserManagementService {
try {
ifSinceDate = format.parse(ifModifiedSince);
} catch (ParseException e) {
- return Response.status(400).entity(new ErrorResponse.ErrorResponseBuilder()
- .setMessage("Invalid date string is provided in 'If-Modified-Since' header").build()).build();
+ String msg = "Invalid date string is provided in [If-Modified-Since] header";
+ return Response.status(400).entity(msg).build();
}
ifModifiedSinceTimestamp = ifSinceDate.getTime();
isIfModifiedSinceSet = true;
@@ -879,8 +873,8 @@ public class UserManagementServiceImpl implements UserManagementService {
try {
sinceDate = format.parse(since);
} catch (ParseException e) {
- return Response.status(400).entity(new ErrorResponse.ErrorResponseBuilder()
- .setMessage("Invalid date string is provided in 'since' filter").build()).build();
+ String msg = "Invalid date string is provided in [since] filter";
+ return Response.status(400).entity(msg).build();
}
sinceTimestamp = sinceDate.getTime();
timestamp = sinceTimestamp / 1000;
@@ -1094,8 +1088,7 @@ public class UserManagementServiceImpl implements UserManagementService {
if (!userStoreManager.isExistingUser(username)) {
String message = "User by username: " + username + " does not exist for permission retrieval.";
log.error(message);
- return Response.status(Response.Status.NOT_FOUND)
- .entity(new ErrorResponse.ErrorResponseBuilder().setMessage(message).build()).build();
+ return Response.status(Response.Status.NOT_FOUND).entity(message).build();
}
// Get a list of roles which the user assigned to
List roles = getFilteredRoles(userStoreManager, username);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/WhiteLabelServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/WhiteLabelServiceImpl.java
new file mode 100644
index 00000000000..97621667dcd
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/WhiteLabelServiceImpl.java
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.jaxrs.service.impl;
+
+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.FileResponse;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelTheme;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
+import org.wso2.carbon.device.mgt.jaxrs.service.api.WhiteLabelService;
+import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
+import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+/**
+ * This is the service class for metadata management.
+ */
+@Path("/whitelabel")
+@Produces(MediaType.APPLICATION_JSON)
+@Consumes(MediaType.APPLICATION_JSON)
+public class WhiteLabelServiceImpl implements WhiteLabelService {
+
+ private static final Log log = LogFactory.getLog(WhiteLabelServiceImpl.class);
+
+ @GET
+ @Override
+ @Path("/{tenantDomain}/favicon")
+ public Response getWhiteLabelFavicon(@PathParam("tenantDomain") String tenantDomain) {
+ try {
+ FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelFavicon(tenantDomain);
+ return sendFileStream(fileResponse);
+ } catch (NotFoundException e) {
+ String msg = "Favicon white label image cannot be found in the system. Uploading the favicon white label image again might help solve the issue.";
+ log.error(msg, e);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while getting favicon";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ @GET
+ @Override
+ @Path("/{tenantDomain}/logo")
+ public Response getWhiteLabelLogo(@PathParam("tenantDomain") String tenantDomain) {
+ try {
+ FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelLogo(tenantDomain);
+ return sendFileStream(fileResponse);
+ } catch (NotFoundException e) {
+ String msg = "Logo white label image cannot be found in the system. Uploading the logo white label image again might help solve the issue.";
+ log.error(msg, e);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while getting logo";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ @GET
+ @Override
+ @Path("/{tenantDomain}/icon")
+ public Response getWhiteLabelLogoIcon(@PathParam("tenantDomain") String tenantDomain) {
+ try {
+ FileResponse fileResponse = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelLogoIcon(tenantDomain);
+ return sendFileStream(fileResponse);
+ } catch (NotFoundException e) {
+ String msg = "Icon white label image cannot be found in the system. Uploading the icon white label image again might help solve the issue.";
+ log.error(msg, e);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while getting logo";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ @PUT
+ @Override
+ public Response updateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest) {
+ RequestValidationUtil.validateWhiteLabelTheme(whiteLabelThemeCreateRequest);
+ try {
+ WhiteLabelTheme createdWhiteLabelTheme = DeviceMgtAPIUtils.getWhiteLabelManagementService().updateWhiteLabelTheme(whiteLabelThemeCreateRequest);
+ return Response.status(Response.Status.CREATED).entity(createdWhiteLabelTheme).build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while creating whitelabel for tenant";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ @GET
+ @Override
+ public Response getWhiteLabelTheme() {
+ try {
+ String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
+ WhiteLabelTheme whiteLabelTheme = DeviceMgtAPIUtils.getWhiteLabelManagementService().getWhiteLabelTheme(tenantDomain);
+ return Response.status(Response.Status.CREATED).entity(whiteLabelTheme).build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while deleting whitelabel for tenant";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ } catch (NotFoundException e) {
+ String msg = "Not white label theme configured for this tenant";
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while retrieving tenant details of whitelabel";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ @PUT
+ @Override
+ @Path("/reset")
+ public Response resetWhiteLabel() {
+ try {
+ DeviceMgtAPIUtils.getWhiteLabelManagementService().resetToDefaultWhiteLabelTheme();
+ return Response.status(Response.Status.CREATED).entity("White label theme deleted successfully.").build();
+ } catch (MetadataManagementException e) {
+ String msg = "Error occurred while resetting whitelabel for tenant";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+ /**
+ * Useful to send file responses
+ */
+ private Response sendFileStream(FileResponse fileResponse) {
+ try (ByteArrayInputStream binaryDuplicate = new ByteArrayInputStream(fileResponse.getFileContent())) {
+ Response.ResponseBuilder response = Response
+ .ok(binaryDuplicate, fileResponse.getMimeType());
+ response.status(Response.Status.OK);
+ response.header("Content-Length", fileResponse.getFileContent().length);
+ return response.build();
+ } catch (IOException e) {
+ String msg = "Error occurred while creating input stream from buffer array. ";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java
index d942c77e7b0..55c8c2ff1d0 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/ApplicationManagementAdminServiceImpl.java
@@ -81,9 +81,8 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
applicationWrapper.getDeviceIdentifiers().size() > 0) {
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
} else {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "No application installation criteria i.e. user/role/device is given").build()).build();
+ String msg = "No application installation criteria i.e. user/role/device is given";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
return Response.status(Response.Status.ACCEPTED).entity(activity).build();
@@ -131,9 +130,8 @@ public class ApplicationManagementAdminServiceImpl implements ApplicationManagem
applicationWrapper.getDeviceIdentifiers().size() > 0) {
activity = appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
} else {
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(
- "No application un-installation criteria i.e. user/role/device is given").build()).build();
+ String msg = "No application un-installation criteria i.e. user/role/device is given";
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
return Response.status(Response.Status.ACCEPTED).entity(activity).build();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java
index e8314e3b00d..1137beceed6 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/DeviceManagementAdminServiceImpl.java
@@ -52,12 +52,15 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.exceptions.UserNotFoundException;
+import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
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;
import org.wso2.carbon.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
+import org.wso2.carbon.user.api.UserStoreException;
+import org.wso2.carbon.user.core.service.RealmService;
import javax.validation.constraints.Size;
import javax.ws.rs.Consumes;
@@ -71,6 +74,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.sql.Timestamp;
import java.util.List;
@Path("/admin/devices")
@@ -147,7 +151,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
@Path("/device-owner")
public Response updateEnrollOwner(
@QueryParam("owner") String owner,
- List deviceIdentifiers){
+ List deviceIdentifiers) {
try {
if (DeviceMgtAPIUtils.getDeviceManagementService().updateEnrollment(owner, true, deviceIdentifiers)) {
String msg = "Device owner is updated successfully.";
@@ -165,7 +169,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (UserNotFoundException e) {
- String msg = "Couldn't found the owner in user store to update the owner of devices.";
+ String msg = "Could not found the owner in user store to update the owner of devices.";
log.error(msg, e);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
@@ -190,12 +194,10 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
- }
- catch (InvalidDeviceException e) {
+ } catch (InvalidDeviceException e) {
String msg = "Found Invalid devices";
log.error(msg, e);
- return Response.status(Response.Status.BAD_REQUEST).entity(
- new ErrorResponse.ErrorResponseBuilder().setMessage(msg).build()).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
}
}
@@ -205,7 +207,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
public Response triggerCorrectiveActions(
@PathParam("deviceId") String deviceIdentifier,
@PathParam("featureCode") String featureCode,
- List actions){
+ List actions) {
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
PlatformConfigurationManagementService platformConfigurationManagementService = DeviceMgtAPIUtils
.getPlatformConfigurationManagementService();
@@ -219,7 +221,7 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (BadRequestException e) {
- String msg = "Bad request, can't proceed. Hence verify the request and re-try";
+ String msg = "Bad request, cannot proceed. Hence verify the request and re-try";
log.error(msg);
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
} catch (DeviceManagementException e) {
@@ -227,10 +229,57 @@ public class DeviceManagementAdminServiceImpl implements DeviceManagementAdminSe
log.error(msg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (DeviceNotFoundException e) {
- String msg = "Couldn't find an device for device identifier: " + deviceIdentifier;
+ String msg = "Could not find an device";
log.error(msg);
return Response.status(Response.Status.NOT_FOUND).entity(msg).build();
}
return Response.status(Response.Status.OK).entity("Triggered action successfully").build();
}
+
+ @GET
+ @Override
+ @Path("/billing")
+ public Response getBilling(
+ @QueryParam("tenantDomain") String tenantDomain,
+ @QueryParam("startDate") Timestamp startDate,
+ @QueryParam("endDate") Timestamp endDate) {
+ try {
+ PaginationResult result;
+ int tenantId = 0;
+ RealmService realmService = DeviceMgtAPIUtils.getRealmService();
+
+ int tenantIdContext = CarbonContext.getThreadLocalCarbonContext().getTenantId();
+
+ if (!tenantDomain.isEmpty()) {
+ tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
+ }
+ if (tenantIdContext != MultitenantConstants.SUPER_TENANT_ID && tenantIdContext != tenantId) {
+ String msg = "Current logged in user is not authorized to access billing details of other tenants";
+ log.error(msg);
+ return Response.status(Response.Status.UNAUTHORIZED).entity(msg).build();
+ } else {
+ DeviceList devices = new DeviceList();
+ DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
+ result = dms.createBillingFile(tenantId, tenantDomain, startDate, endDate);
+ devices.setList((List) result.getData());
+ devices.setDeviceCount(result.getTotalDeviceCount());
+ devices.setMessage(result.getMessage());
+ devices.setTotalCost(result.getTotalCost());
+ devices.setBillPeriod(startDate.toString() + " - " + endDate.toString());
+ return Response.status(Response.Status.OK).entity(devices).build();
+ }
+ } catch (BadRequestException e) {
+ String msg = "Bad request, can't proceed. Hence verify the request and re-try";
+ log.error(msg, e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(msg).build();
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while retrieving billing data";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ } catch (UserStoreException e) {
+ String msg = "Error occurred while processing tenant configuration.";
+ log.error(msg, e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
+ }
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java
index a461b71b500..9dd67617e81 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java
@@ -156,7 +156,7 @@ public class GroupManagementAdminServiceImpl implements GroupManagementAdminServ
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
} catch (GroupAlreadyExistException e) {
- String msg = "Group already exists with name " + group.getName() + ".";
+ String msg = "Group already exists with name : " + group.getName() + ". Try with another group name.";
log.warn(msg);
return Response.status(Response.Status.CONFLICT).entity(msg).build();
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java
index f9a27bee4ca..bb15685f2cc 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/util/RequestValidationUtil.java
@@ -18,10 +18,13 @@
*/
package org.wso2.carbon.device.mgt.jaxrs.service.impl.util;
+import com.google.gson.Gson;
+import com.google.gson.JsonSyntaxException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpStatus;
+import org.wso2.carbon.device.mgt.common.Base64File;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
@@ -31,8 +34,11 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceTypeNotFoundException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelImageRequestPayload;
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
+import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ErrorResponse;
@@ -43,6 +49,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
import org.wso2.carbon.device.mgt.jaxrs.beans.ProfileFeature;
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleInfo;
import org.wso2.carbon.device.mgt.jaxrs.beans.Scope;
+import org.wso2.carbon.device.mgt.jaxrs.exception.BadRequestException;
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils;
import org.wso2.carbon.policy.mgt.common.PolicyPayloadValidator;
@@ -670,6 +677,122 @@ public class RequestValidationUtil {
}
}
+ /**
+ * Check if whitelabel theme create request contains valid payload and all required payload
+ *
+ * @param whiteLabelThemeCreateRequest {@link WhiteLabelThemeCreateRequest}
+ */
+ public static void validateWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest) {
+ if (whiteLabelThemeCreateRequest.getFavicon() == null) {
+ String msg = "Favicon is required to whitelabel";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ if (whiteLabelThemeCreateRequest.getLogo() == null) {
+ String msg = "Logo is required to whitelabel";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ if (whiteLabelThemeCreateRequest.getLogoIcon() == null) {
+ String msg = "Logo Icon is required to whitelabel";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ if (whiteLabelThemeCreateRequest.getFooterText() == null) {
+ String msg = "Footer text is required to whitelabel";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ if (whiteLabelThemeCreateRequest.getAppTitle() == null) {
+ String msg = "App title is required to whitelabel";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ try {
+ validateWhiteLabelImage(whiteLabelThemeCreateRequest.getFavicon());
+ validateWhiteLabelImage(whiteLabelThemeCreateRequest.getLogo());
+ validateWhiteLabelImage(whiteLabelThemeCreateRequest.getLogoIcon());
+ } catch (InputValidationException e) {
+ String msg = "Payload contains invalid base64 files";
+ log.error(msg, e);
+ throw e;
+ }
+ }
+
+ /**
+ * Validate if {@link WhiteLabelImageRequestPayload} contains mandatory fields.
+ */
+ private static void validateWhiteLabelImage(WhiteLabelImageRequestPayload whiteLabelImage) {
+ if (whiteLabelImage.getImageType() == null) {
+ String msg = "Invalid payload found with the request. White label imageType cannot be null.";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ if (whiteLabelImage.getImageType() == WhiteLabelImageRequestPayload.ImageType.BASE64) {
+ try {
+ Base64File image = new Gson().fromJson(whiteLabelImage.getImage(), Base64File.class);
+ validateBase64File(image);
+ } catch (JsonSyntaxException e) {
+ String msg = "Invalid image payload found with the request. Image object does not represent a Base64 File. " +
+ "Hence verify the request payload object.";
+ log.error(msg, e);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ }
+ else if (whiteLabelImage.getImageType() == WhiteLabelImageRequestPayload.ImageType.URL) {
+ try {
+ String imageUrl = new Gson().fromJson(whiteLabelImage.getImage(), String.class);
+ if (!HttpUtil.isHttpUrlValid(imageUrl)) {
+ String msg = "Invalid image url provided for white label image.";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ } catch (JsonSyntaxException e) {
+ String msg = "Invalid payload found with the request. Hence verify the request payload object.";
+ log.error(msg, e);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ } else {
+ String msg = "Invalid payload found with the request. Unknown white label imageType " + whiteLabelImage.getImageType();
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ }
+
+ /**
+ * Validate if {@link Base64File} contains mandatory fields.
+ */
+ private static void validateBase64File(Base64File base64File) {
+ if (base64File.getBase64String() == null || base64File.getName() == null) {
+ String msg = "Base64File doesn't contain required properties. name and base64String properties " +
+ "are required fields for base64file type";
+ log.error(msg);
+ throw new InputValidationException(
+ new ErrorResponse.ErrorResponseBuilder()
+ .setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ }
+ }
+
/**
* Validate if the metaData and metaKey values are non empty & in proper format.
*
@@ -727,8 +850,7 @@ public class RequestValidationUtil {
if (geofenceWrapper.getFenceName() == null || geofenceWrapper.getFenceName().trim().isEmpty()) {
String msg = "Geofence name should not be null or empty";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
if (geofenceWrapper.getGeoJson() != null && !geofenceWrapper.getGeoJson().trim().isEmpty()) {
isGeoJsonExists = true;
@@ -736,26 +858,22 @@ public class RequestValidationUtil {
if ((geofenceWrapper.getLatitude() < -90 || geofenceWrapper.getLatitude() > 90) && !isGeoJsonExists) {
String msg = "Latitude should be a value between -90 and 90";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
if ((geofenceWrapper.getLongitude() < -180 || geofenceWrapper.getLongitude() > 180) && !isGeoJsonExists) {
String msg = "Longitude should be a value between -180 and 180";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
if (geofenceWrapper.getRadius() < 1 && !isGeoJsonExists) {
String msg = "Minimum radius of the fence should be 1m";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
if (geofenceWrapper.getFenceShape().trim().isEmpty()) {
String msg = "Fence shape should not be empty";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
}
@@ -767,23 +885,20 @@ public class RequestValidationUtil {
if (eventConfig == null ||eventConfig.isEmpty()) {
String msg = "Event configuration is mandatory, since should not be null or empty";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
for (EventConfig config : eventConfig) {
if (config.getActions() == null || config.getActions().isEmpty()) {
String msg = "Event actions are mandatory, since should not be null or empty";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
if (config.getEventLogic() == null || config.getEventLogic().trim().isEmpty()) {
String msg = "Event logic is mandatory, since should not be null or empty";
log.error(msg);
- throw new InputValidationException(
- new ErrorResponse.ErrorResponseBuilder().setCode(HttpStatus.SC_BAD_REQUEST).setMessage(msg).build());
+ throw new BadRequestException(msg);
}
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java
index 92bc2790d49..e2100f03eb1 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/util/DeviceMgtAPIUtils.java
@@ -50,15 +50,12 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.stream.persistence.stub.EventStreamPersistenceAdminServiceStub;
+import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.base.ServerConfiguration;
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.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.MonitoringOperation;
-import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
+import org.wso2.carbon.device.mgt.common.*;
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.configuration.mgt.ConfigurationEntry;
@@ -74,11 +71,13 @@ import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.report.mgt.ReportManagementService;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
+import org.wso2.carbon.device.mgt.common.spi.TraccarManagementService;
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.dto.DeviceTypeVersion;
@@ -95,8 +94,11 @@ 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.device.mgt.jaxrs.service.impl.util.RequestValidationUtil;
import org.wso2.carbon.event.processor.stub.EventProcessorAdminServiceStub;
+import org.wso2.carbon.event.publisher.core.EventPublisherService;
import org.wso2.carbon.event.publisher.stub.EventPublisherAdminServiceStub;
+import org.wso2.carbon.event.receiver.core.EventReceiverService;
import org.wso2.carbon.event.receiver.stub.EventReceiverAdminServiceStub;
+import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.stub.EventStreamAdminServiceStub;
import org.wso2.carbon.identity.claim.metadata.mgt.dto.ClaimPropertyDTO;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
@@ -111,11 +113,7 @@ import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
import org.wso2.carbon.registry.core.service.RegistryService;
-import org.wso2.carbon.user.api.AuthorizationManager;
-import org.wso2.carbon.user.api.RealmConfiguration;
-import org.wso2.carbon.user.api.UserRealm;
-import org.wso2.carbon.user.api.UserStoreException;
-import org.wso2.carbon.user.api.UserStoreManager;
+import org.wso2.carbon.user.api.*;
import org.wso2.carbon.user.core.jdbc.JDBCUserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
@@ -128,11 +126,7 @@ import javax.net.ssl.TrustManagerFactory;
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.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.LinkedList;
@@ -172,8 +166,9 @@ public class DeviceMgtAPIUtils {
private static KeyStore trustStore;
private static char[] keyStorePassword;
-// private static IntegrationClientService integrationClientService;
+ // private static IntegrationClientService integrationClientService;
private static MetadataManagementService metadataManagementService;
+ private static WhiteLabelManagementService whiteLabelManagementService;
private static OTPManagementService otpManagementService;
private static volatile SubscriptionManager subscriptionManager;
@@ -511,6 +506,28 @@ public class DeviceMgtAPIUtils {
return notificationManagementService;
}
+ /**
+ * Initializing and accessing method for WhiteLabelManagementService.
+ *
+ * @return WhiteLabelManagementService instance
+ * @throws IllegalStateException if whiteLabelManagementService cannot be initialized
+ */
+ public static WhiteLabelManagementService getWhiteLabelManagementService() {
+ if (whiteLabelManagementService == null) {
+ synchronized (DeviceMgtAPIUtils.class) {
+ if (whiteLabelManagementService == null) {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ whiteLabelManagementService = (WhiteLabelManagementService) ctx.getOSGiService(
+ WhiteLabelManagementService.class, null);
+ if (whiteLabelManagementService == null) {
+ throw new IllegalStateException("Whitelabel Management service not initialized.");
+ }
+ }
+ }
+ }
+ return whiteLabelManagementService;
+ }
+
/**
* Initializing and accessing method for MetadataManagementService.
*
@@ -581,6 +598,36 @@ public class DeviceMgtAPIUtils {
return geoService;
}
+ public static EventStreamService getEventStreamService() {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ EventStreamService
+ eventStreamService = (EventStreamService) ctx.getOSGiService(EventStreamService.class, null);
+ if (eventStreamService == null) {
+ throw new IllegalStateException("Event Stream Service has not been initialized.");
+ }
+ return eventStreamService;
+ }
+
+ public static EventReceiverService getEventReceiverService() {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ EventReceiverService
+ eventReceiverService = (EventReceiverService) ctx.getOSGiService(EventReceiverService.class, null);
+ if (eventReceiverService == null) {
+ throw new IllegalStateException("Event Receiver Service has not been initialized.");
+ }
+ return eventReceiverService;
+ }
+
+ public static EventPublisherService getEventPublisherService() {
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ EventPublisherService
+ eventPublisherService = (EventPublisherService) ctx.getOSGiService(EventPublisherService.class, null);
+ if (eventPublisherService == null) {
+ throw new IllegalStateException("Event Receiver Service has not been initialized.");
+ }
+ return eventPublisherService;
+ }
+
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
@@ -642,10 +689,13 @@ public class DeviceMgtAPIUtils {
// return eventsPublisherService;
// }
+ public static String getStreamDefinition(String deviceType, String tenantDomain, String eventName) {
+ return getStreamDefinition(deviceType, tenantDomain) + "." + eventName;
+ }
+
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(
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
index efce569c420..9db350e2677 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml
@@ -49,6 +49,7 @@
+
@@ -99,6 +100,7 @@
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml
index fffbfbdb24e..00c784efc5a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/web.xml
@@ -48,7 +48,10 @@
nonSecuredEndPoints
- /api/device-mgt/v1.0/users/validate
+ /api/device-mgt/v1.0/users/validate,
+ /api/device-mgt/v1.0/whitelabel/.*/favicon,
+ /api/device-mgt/v1.0/whitelabel/.*/logo,
+ /api/device-mgt/v1.0/whitelabel/.*/icon,
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java
index 7b995660ad7..db085319f0c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/test/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/DeviceManagementServiceImplTest.java
@@ -590,7 +590,7 @@ public class DeviceManagementServiceImplTest {
PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
.toReturn(this.deviceManagementProviderService);
Response response = this.deviceManagementService
- .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
+ .getFeaturesOfDevice(TEST_DEVICE_TYPE, null);
Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
@@ -601,7 +601,7 @@ public class DeviceManagementServiceImplTest {
Mockito.when(this.deviceManagementProviderService.getFeatureManager(Mockito.anyString()))
.thenThrow(new DeviceTypeNotFoundException());
Response response = this.deviceManagementService
- .getFeaturesOfDevice(TEST_DEVICE_TYPE, UUID.randomUUID().toString(), null);
+ .getFeaturesOfDevice(TEST_DEVICE_TYPE, null);
Assert.assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode());
Mockito.reset(this.deviceManagementProviderService);
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml
index bdc879561d3..b769df09061 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/pom.xml
@@ -21,7 +21,7 @@
device-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Base64File.java
similarity index 91%
rename from components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Base64File.java
index ef1f1d3204e..93303f4493f 100644
--- a/components/application-mgt/io.entgra.application.mgt.common/src/main/java/io/entgra/application/mgt/common/Base64File.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/Base64File.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ * Copyright (c) 2023, 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
@@ -16,7 +16,7 @@
* under the License.
*/
-package io.entgra.application.mgt.common;
+package org.wso2.carbon.device.mgt.common;
public class Base64File {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java
new file mode 100644
index 00000000000..ad7f9eaeb30
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/BillingResponse.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2022, 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;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+import java.io.Serializable;
+import java.util.List;
+
+@ApiModel(value = "BillingResponse", description = "This class carries all information related to a billing response.")
+public class BillingResponse implements Serializable {
+
+ private static final long serialVersionUID = 1998101711L;
+
+ @ApiModelProperty(name = "year", value = "Year of the billed period",
+ required = false)
+ private String year;
+
+ @ApiModelProperty(name = "totalCostPerYear", value = "Bill for a period of year", required = false)
+ private double totalCostPerYear;
+
+ @ApiModelProperty(name = "devices", value = "Billed list of devices per year", required = false)
+ private List device;
+
+ @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
+ private String billPeriod;
+
+ @ApiModelProperty(name = "startDate", value = "Start Date of period", required = false)
+ private String startDate;
+
+ @ApiModelProperty(name = "endDate", value = "End Date of period", required = false)
+ private String endDate;
+
+ @ApiModelProperty(name = "deviceCount", value = "Device count for a billing period",
+ required = false)
+ private int deviceCount;
+
+ public BillingResponse() {
+ }
+
+ public BillingResponse(String year, double totalCostPerYear, List device, String billPeriod, String startDate, String endDate, int deviceCount) {
+ this.year = year;
+ this.totalCostPerYear = totalCostPerYear;
+ this.device = device;
+ this.billPeriod = billPeriod;
+ this.startDate = startDate;
+ this.endDate = endDate;
+ this.deviceCount = deviceCount;
+ }
+
+ public String getStartDate() {
+ return startDate;
+ }
+
+ public void setStartDate(String startDate) {
+ this.startDate = startDate;
+ }
+
+ public String getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(String endDate) {
+ this.endDate = endDate;
+ }
+
+ public double getTotalCostPerYear() {
+ return totalCostPerYear;
+ }
+
+ public void setTotalCostPerYear(double totalCostPerYear) {
+ this.totalCostPerYear = totalCostPerYear;
+ }
+
+ public String getYear() {
+ return year;
+ }
+
+ public void setYear(String year) {
+ this.year = year;
+ }
+
+ public List getDevice() {
+ return device;
+ }
+
+ public void setDevice(List device) {
+ this.device = device;
+ }
+
+ public String getBillPeriod() {
+ return billPeriod;
+ }
+
+ public void setBillPeriod(String billPeriod) {
+ this.billPeriod = billPeriod;
+ }
+
+ public int getDeviceCount() {
+ return deviceCount;
+ }
+
+ public void setDeviceCount(int deviceCount) {
+ this.deviceCount = deviceCount;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/FileResponse.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/FileResponse.java
new file mode 100644
index 00000000000..e3e83cf3c2c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/FileResponse.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common;
+
+public class FileResponse {
+ private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
+ private byte[] fileContent;
+ private String mimeType;
+
+ private String name;
+
+ public byte[] getFileContent() {
+ return fileContent;
+ }
+
+ public void setFileContent(byte[] fileContent) {
+ this.fileContent = fileContent;
+ }
+
+ public String getMimeType() {
+ return mimeType;
+ }
+
+ public void setMimeType(String mimeType) {
+ this.mimeType = mimeType;
+ }
+
+ public enum ImageExtension {
+ SVG() {
+ @Override
+ public String mimeType() {
+ return "image/svg+xml";
+ }
+ },
+ PNG,
+ JPG,
+ JPEG,
+ GIF;
+
+ public String mimeType() {
+ return DEFAULT_MIME_TYPE;
+ }
+
+ public static String mimeTypeOf(String extension) {
+ if (extension.isEmpty()) {
+ return DEFAULT_MIME_TYPE;
+ }
+ ImageExtension imageExtension = ImageExtension.valueOf(extension.toUpperCase());
+ return imageExtension.mimeType();
+ }
+
+ @Override
+ public String toString() {
+ return this.name().toLowerCase();
+ }
+
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java
index 29bb7922e97..9a24b5c7f35 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationRequest.java
@@ -44,6 +44,7 @@ public class PaginationRequest {
private Map property = new HashMap<>();
private List statusList = new ArrayList<>();
private OperationLogFilters operationLogFilters = new OperationLogFilters();
+ private List sortColumn = new ArrayList<>();
public OperationLogFilters getOperationLogFilters() {
return operationLogFilters;
}
@@ -172,11 +173,38 @@ public class PaginationRequest {
this.filter = filter;
}
+ public void setSortColumn(List sortColumn) { this.sortColumn = sortColumn; }
+
+ public List getSortColumn() { return sortColumn; }
+
+ /**
+ * Convert SortColumns field parameter and splitting string into columnName and sortType
+ *
+ * @param sortColumns which is separated by a colon(:) and first will be the columnNane and the second will be type ASC or DESC,
+ * if there is no colon(:) detected, ASC will be default
+ * (Ex: sort=col1:ASC&sort=col2:DESC, sort=col1&sort=col2:DESC)
+ * @return sortColumnList as a list of sortColumn
+ */
+ public void setSortColumns(List sortColumns) {
+ List sortColumnList = new ArrayList<>();
+ SortColumn sortColumn;
+ String[] sorting;
+ for (String sortBy: sortColumns) {
+ sortColumn = new SortColumn();
+ sorting = sortBy.split(":");
+ sortColumn.setName(sorting[0]);
+ sortColumn.setType(sorting.length >= 2 && (sorting[1].equalsIgnoreCase("desc"))
+ ? SortColumn.types.DESC : SortColumn.types.ASC);
+ sortColumnList.add(sortColumn);
+ }
+ setSortColumn(sortColumnList);
+ }
+
@Override
public String toString() {
return "Device type '" + this.deviceType + "' Device Name '" + this.deviceName + "' row count: " + this.rowCount
+ " Owner role '" + this.ownerRole + "' owner pattern '" + this.ownerPattern + "' ownership "
+ this.ownership + "' Status '" + this.statusList + "' owner '" + this.owner + "' groupId: " + this.groupId
- + " start index: " + this.startIndex;
+ + " start index: " + this.startIndex + ", SortColumns: " + this.sortColumn;
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java
index 553618d80c5..b76f40471bf 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/PaginationResult.java
@@ -47,18 +47,29 @@ public class PaginationResult implements Serializable {
@ApiModelProperty(name = "totalCost", value = "Total cost of all devices per tenant", required = false)
private double totalCost;
- @ApiModelProperty(name = "billedDateIsValid", value = "Check if user entered date is valid", required = false)
- private boolean billedDateIsValid;
+ @ApiModelProperty(name = "totalDeviceCount", value = "Total count of all devices per tenant", required = false)
+ private double totalDeviceCount;
+
+ @ApiModelProperty(name = "billPeriod", value = "Billed period", required = false)
+ private String billPeriod;
@ApiModelProperty(name = "message", value = "Send information text to the billing UI", required = false)
private String message;
- public boolean isBilledDateIsValid() {
- return billedDateIsValid;
+ public String getBillPeriod() {
+ return billPeriod;
+ }
+
+ public void setBillPeriod(String billPeriod) {
+ this.billPeriod = billPeriod;
+ }
+
+ public double getTotalDeviceCount() {
+ return totalDeviceCount;
}
- public void setBilledDateIsValid(boolean billedDateIsValid) {
- this.billedDateIsValid = billedDateIsValid;
+ public void setTotalDeviceCount(double totalDeviceCount) {
+ this.totalDeviceCount = totalDeviceCount;
}
public String getMessage() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java
new file mode 100644
index 00000000000..8e6d4915ea1
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/SortColumn.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common;
+
+/**
+ * This class holds required parameters for a querying a sort by column in pagination.
+ *
+ */
+public class SortColumn {
+ String name;
+ SortColumn.types type;
+
+ public enum types {
+ ASC, DESC
+ }
+
+ /**
+ * ColumnName setter method
+ * @param name of the column
+ */
+ public void setName(String name) { this.name = name; }
+
+ /**
+ * get the name of the column
+ * @return name
+ */
+ public String getName() { return name; }
+
+ /**
+ * Column sort type
+ * @param type of sort as ASC or DESC
+ */
+ public void setType(SortColumn.types type) { this.type = type; }
+
+ /**
+ * get column sort type
+ * @return type of sort
+ */
+ public SortColumn.types getType() { return type; }
+
+ @Override
+ public String toString() {
+ return "Column Name - " + this.name + ", Type - " + this.type ;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/NotFoundException.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/NotFoundException.java
new file mode 100644
index 00000000000..15986e31dae
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/exceptions/NotFoundException.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.exceptions;
+
+/**
+ * This exception will be thrown when the requested application or platform not found.
+ */
+public class NotFoundException extends Exception {
+
+ public NotFoundException(String message, Throwable throwable) {
+ super(message, throwable);
+ }
+
+ public NotFoundException(String message) {
+ super(message);
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java
new file mode 100644
index 00000000000..66bde2dc830
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/group/mgt/DeviceTypesOfGroups.java
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2022, Entgra (pvt) Ltd. (https://entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.group.mgt;
+
+import io.swagger.annotations.ApiModel;
+import io.swagger.annotations.ApiModelProperty;
+
+import java.io.Serializable;
+
+@ApiModel(value = "DeviceTypesOfGroups", description = "This class carries whether the groups has device type or not.")
+public class DeviceTypesOfGroups implements Serializable {
+
+ private static final long serialVersionUID = 5562356373277828099L;
+ @ApiModelProperty(name = "hasAndroid", value = "groups has Android devices.")
+ private boolean hasAndroid;
+ @ApiModelProperty(name = "id", value = "groups has iOS devices.")
+ private boolean hasIos;
+ @ApiModelProperty(name = "hasAndroid", value = "groups has Windows devices.")
+ private boolean hasWindows;
+
+ public boolean isHasAndroid() {
+ return hasAndroid;
+ }
+
+ public void setHasAndroid(boolean hasAndroid) {
+ this.hasAndroid = hasAndroid;
+ }
+
+ public boolean isHasIos() {
+ return hasIos;
+ }
+
+ public void setHasIos(boolean hasIos) {
+ this.hasIos = hasIos;
+ }
+
+ public boolean isHasWindows() {
+ return hasWindows;
+ }
+
+ public void setHasWindows(boolean hasWindows) {
+ this.hasWindows = hasWindows;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/MetadataManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/MetadataManagementService.java
index 060492f6203..4765fc047d3 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/MetadataManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/MetadataManagementService.java
@@ -23,7 +23,6 @@ import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyAlreadyExistsException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataKeyNotFoundException;
import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
-
import java.util.List;
/**
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelArtifactPath.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelArtifactPath.java
new file mode 100644
index 00000000000..501e35a0744
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelArtifactPath.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+public class WhiteLabelArtifactPath {
+ private String faviconPath;
+ private String logoPath;
+ private String logoIconPath;
+
+ public WhiteLabelArtifactPath() {
+
+ }
+
+ public WhiteLabelArtifactPath(String faviconPath, String logoPath, String logoIconPath) {
+ this.faviconPath = faviconPath;
+ this.logoPath = logoPath;
+ this.logoIconPath = logoIconPath;
+ }
+
+ public String getFaviconPath() {
+ return faviconPath;
+ }
+
+ public void setFaviconPath(String faviconPath) {
+ this.faviconPath = faviconPath;
+ }
+
+ public String getLogoPath() {
+ return logoPath;
+ }
+
+ public void setLogoPath(String logoPath) {
+ this.logoPath = logoPath;
+ }
+
+ public String getLogoIconPath() {
+ return logoIconPath;
+ }
+
+ public void setLogoIconPath(String logoIconPath) {
+ this.logoIconPath = logoIconPath;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImage.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImage.java
new file mode 100644
index 00000000000..846aca5f761
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImage.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+public class WhiteLabelImage {
+ private ImageLocationType imageLocationType;
+ private String imageLocation;
+
+ public ImageLocationType getImageLocationType() {
+ return imageLocationType;
+ }
+
+ public void setImageLocationType(ImageLocationType imageLocationType) {
+ this.imageLocationType = imageLocationType;
+ }
+
+ public String getImageLocation() {
+ return imageLocation;
+ }
+
+ public void setImageLocation(String imageLocation) {
+ this.imageLocation = imageLocation;
+ }
+
+ public enum ImageName {
+ FAVICON,
+ LOGO,
+ LOGO_ICON;
+
+ @Override
+ public String toString() {
+ return name().toLowerCase();
+ }
+ }
+
+ public enum ImageLocationType {
+ URL,
+ CUSTOM_FILE,
+ DEFAULT_FILE
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImageRequestPayload.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImageRequestPayload.java
new file mode 100644
index 00000000000..0ccce87c930
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelImageRequestPayload.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+import com.google.gson.Gson;
+import com.google.gson.JsonElement;
+import org.wso2.carbon.device.mgt.common.Base64File;
+
+public class WhiteLabelImageRequestPayload {
+ private ImageType imageType;
+ private JsonElement image;
+
+ public ImageType getImageType() {
+ return imageType;
+ }
+
+ public void setImageType(ImageType imageType) {
+ this.imageType = imageType;
+ }
+
+ public JsonElement getImage() {
+ return image;
+ }
+
+ public Base64File getImageAsBase64File() {
+ if (imageType != ImageType.BASE64) {
+ throw new IllegalStateException("Cannot convert image with Image type of " + imageType + " to base64.");
+ }
+ return new Gson().fromJson(image, Base64File.class);
+ }
+
+ public String getImageAsUrl() {
+ if (imageType != ImageType.URL) {
+ throw new IllegalStateException("Cannot convert image with Image type of " + imageType + " to image url string.");
+ }
+ return new Gson().fromJson(image, String.class);
+ }
+
+ public void setImage(JsonElement image) {
+ this.image = image;
+ }
+
+ public enum ImageType {
+ URL,
+ BASE64;
+
+ public WhiteLabelImage.ImageLocationType getDTOImageLocationType() {
+ if (this == URL) {
+ return WhiteLabelImage.ImageLocationType.URL;
+ }
+ return WhiteLabelImage.ImageLocationType.CUSTOM_FILE;
+ }
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelManagementService.java
new file mode 100644
index 00000000000..6ccf82eab47
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelManagementService.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+import org.wso2.carbon.device.mgt.common.FileResponse;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
+
+/**
+ * Defines the contract of WhiteLabelManagementService.
+ */
+public interface WhiteLabelManagementService {
+
+ /**
+ * Use to get byte content of favicon whitelabel image
+ * @return byte content of favicon
+ * @throws MetadataManagementException if error occurred while retrieving favicon
+ * @throws NotFoundException if favicon is not found
+ */
+ FileResponse getWhiteLabelFavicon(String tenantDomain) throws
+ MetadataManagementException, NotFoundException;
+
+ /**
+ * Use to get byte content of logo whitelabel image
+ * @return byte content of logo
+ * @throws MetadataManagementException if error occurred while retrieving logo
+ * @throws NotFoundException if logo is not found
+ */
+ FileResponse getWhiteLabelLogo(String tenantDomain) throws
+ MetadataManagementException, NotFoundException;
+
+ /**
+ * Use to get byte content of logo icon whitelabel image
+ * @return byte content of logo icon
+ * @throws MetadataManagementException if error occurred while retrieving logo icon
+ * @throws NotFoundException if logo icon is not found
+ */
+ FileResponse getWhiteLabelLogoIcon(String tenantDomain) throws
+ MetadataManagementException, NotFoundException;
+
+ /**
+ * This method is useful to create & persist default white label theme for provided tenant if
+ * it doesn't exist already
+ * @throws MetadataManagementException if error while adding default white label theme
+ */
+ void addDefaultWhiteLabelThemeIfNotExist(int tenantId) throws MetadataManagementException;
+
+ /**
+ * This method is useful to reset existing white label to default whitelabel
+ * @throws MetadataManagementException if error while resetting default white label theme
+ */
+ void resetToDefaultWhiteLabelTheme() throws MetadataManagementException;
+
+ /**
+ * This method is useful to update existing white label theme
+ * @throws MetadataManagementException if error while updating existing white label theme
+ */
+ WhiteLabelTheme updateWhiteLabelTheme(WhiteLabelThemeCreateRequest createWhiteLabelTheme)
+ throws MetadataManagementException;
+
+ /**
+ * This method is useful to get existing white label theme
+ * @throws MetadataManagementException if error while getting existing white label theme
+ */
+ WhiteLabelTheme getWhiteLabelTheme(String tenantDomain) throws MetadataManagementException, NotFoundException, DeviceManagementException;
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelTheme.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelTheme.java
new file mode 100644
index 00000000000..2600eeef907
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelTheme.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+public class WhiteLabelTheme {
+ private WhiteLabelImage faviconImage;
+ private WhiteLabelImage logoImage;
+ private WhiteLabelImage logoIconImage;
+ private String footerText;
+ private String appTitle;
+
+ public String getFooterText() {
+ return footerText;
+ }
+
+ public void setFooterText(String footerText) {
+ this.footerText = footerText;
+ }
+
+ public WhiteLabelImage getFaviconImage() {
+ return faviconImage;
+ }
+
+ public void setFaviconImage(WhiteLabelImage faviconImage) {
+ this.faviconImage = faviconImage;
+ }
+
+ public WhiteLabelImage getLogoImage() {
+ return logoImage;
+ }
+
+ public void setLogoImage(WhiteLabelImage logoImage) {
+ this.logoImage = logoImage;
+ }
+
+ public String getAppTitle() {
+ return appTitle;
+ }
+
+ public void setAppTitle(String appTitle) {
+ this.appTitle = appTitle;
+ }
+
+ public WhiteLabelImage getLogoIconImage() {
+ return logoIconImage;
+ }
+
+ public void setLogoIconImage(WhiteLabelImage logoIconImage) {
+ this.logoIconImage = logoIconImage;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelThemeCreateRequest.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelThemeCreateRequest.java
new file mode 100644
index 00000000000..7939f3428a9
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/metadata/mgt/WhiteLabelThemeCreateRequest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.metadata.mgt;
+
+public class WhiteLabelThemeCreateRequest {
+ private WhiteLabelImageRequestPayload favicon;
+ private WhiteLabelImageRequestPayload logo;
+ private WhiteLabelImageRequestPayload logoIcon;
+ private String footerText;
+ private String appTitle;
+
+ public WhiteLabelImageRequestPayload getFavicon() {
+ return favicon;
+ }
+
+ public void setFavicon(WhiteLabelImageRequestPayload favicon) {
+ this.favicon = favicon;
+ }
+
+ public WhiteLabelImageRequestPayload getLogo() {
+ return logo;
+ }
+
+ public void setLogo(WhiteLabelImageRequestPayload logo) {
+ this.logo = logo;
+ }
+
+ public String getFooterText() {
+ return footerText;
+ }
+
+ public void setFooterText(String footerText) {
+ this.footerText = footerText;
+ }
+
+ public String getAppTitle() {
+ return appTitle;
+ }
+
+ public void setAppTitle(String appTitle) {
+ this.appTitle = appTitle;
+ }
+
+ public WhiteLabelImageRequestPayload getLogoIcon() {
+ return logoIcon;
+ }
+
+ public void setLogoIcon(WhiteLabelImageRequestPayload logoIcon) {
+ this.logoIcon = logoIcon;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/wrapper/DownloadURLDetails.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/wrapper/DownloadURLDetails.java
new file mode 100644
index 00000000000..e6a8557b66d
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/wrapper/DownloadURLDetails.java
@@ -0,0 +1,49 @@
+/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.common.otp.mgt.wrapper;
+
+public class DownloadURLDetails {
+
+ private String firstName;
+ private String URL;
+ private String email;
+
+ public String getURL() {
+ return URL;
+ }
+
+ public void setURL(String URL) {
+ this.URL = URL;
+ }
+
+ public String getFirstName() {
+ return firstName;
+ }
+
+ public void setFirstName(String firstName) {
+ this.firstName = firstName;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ this.email = email;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java
index 6349407dc1c..27e20328c5b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java
@@ -22,6 +22,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException;
import org.wso2.carbon.device.mgt.common.invitation.mgt.DeviceEnrollmentInvitation;
import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO;
+import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.DownloadURLDetails;
import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.OTPWrapper;
import java.util.Map;
@@ -62,4 +63,13 @@ public interface OTPManagementService {
*/
void sendDeviceEnrollmentInvitationMail(DeviceEnrollmentInvitation deviceEnrollmentInvitation)
throws OTPManagementException;
-}
+
+ /**
+ * Send an e-mail to the requesting e-mail address with a product download URL
+ * @param downloadURLDetails Contains the details to send product download e-mail
+ * @throws OTPManagementException if request payload doesn't contains required details to send the product
+ * download mail.
+ */
+ void shareProductDownloadUrl(DownloadURLDetails downloadURLDetails) throws OTPManagementException;
+
+ }
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/TraccarManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/TraccarManagementService.java
new file mode 100644
index 00000000000..0c3379eedfa
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/TraccarManagementService.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2023, 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.spi;
+
+import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
+
+public interface TraccarManagementService {
+
+ /**
+ * Add the provided device to Traccar.
+ * @param device The device to be added to Traccar.
+ */
+ void addDevice(Device device);
+
+ /**
+ * Removes the Traccar device with the specified device ID from the logged in user.
+ * @param deviceEnrollmentId The enrollment ID of the device to be removed from Traccar.
+ */
+ void unLinkTraccarDevice(int deviceEnrollmentId);
+
+ /**
+ * Update the provided device to Traccar.
+ * @param device The device to be updated on Traccar.
+ */
+ void updateDevice(Device device);
+
+ /**
+ * Removes the device with the specified enrollment ID from Traccar.
+ * @param deviceEnrollmentId The enrollment ID of the device to be removed from Traccar.
+ */
+ void removeDevice(int deviceEnrollmentId);
+
+ /**
+ * Updates the location of the provided device with the specified device location.
+ * @param device The device whose location is to be updated.
+ * @param deviceLocation The new location of the device.
+ */
+ void updateLocation(Device device, DeviceLocation deviceLocation);
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java
index dcc7ff47cdd..835f450bb78 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/type/mgt/DeviceTypeMetaDefinition.java
@@ -5,6 +5,7 @@ import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
+import java.util.ArrayList;
import java.util.List;
public class DeviceTypeMetaDefinition {
@@ -19,6 +20,10 @@ public class DeviceTypeMetaDefinition {
private String description;
private boolean isSharedWithAllTenants;
+ private List mqttEventTopicStructures;
+
+ private boolean longLivedToken = false;
+
public String getDescription() {
return description;
}
@@ -83,4 +88,20 @@ public class DeviceTypeMetaDefinition {
public void setSharedWithAllTenants(boolean sharedWithAllTenants) {
isSharedWithAllTenants = sharedWithAllTenants;
}
+
+ public List getMqttEventTopicStructures() {
+ return mqttEventTopicStructures;
+ }
+
+ public void setMqttEventTopicStructures(List mqttEventTopicStructures) {
+ this.mqttEventTopicStructures = mqttEventTopicStructures;
+ }
+
+ public boolean isLongLivedToken() {
+ return longLivedToken;
+ }
+
+ public void setLongLivedToken(boolean longLivedToken) {
+ this.longLivedToken = longLivedToken;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
index 6176c74ff5a..07d7cdc4a7d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
device-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
@@ -103,6 +103,7 @@
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.ntask.core.*,
org.wso2.carbon.ntask.common,
+ io.entgra.task.mgt.common.*,
org.apache.commons.collections;version="${commons-collections.version.range}",
org.wso2.carbon.email.sender.*,
io.swagger.annotations.*;resolution:=optional,
@@ -112,7 +113,9 @@
org.wso2.carbon.event.processor.stub,
org.wso2.carbon.identity.jwt.client.extension.service,
org.apache.commons.codec.binary,
- io.entgra.server.bootup.heartbeat.beacon
+ io.entgra.server.bootup.heartbeat.beacon,
+ io.entgra.device.mgt.extensions.logger.*,
+ io.entgra.notification.logger.*
!org.wso2.carbon.device.mgt.core.internal,
@@ -347,6 +350,14 @@
okhttp
compile
+
+ org.wso2.carbon.devicemgt
+ io.entgra.task.mgt.common
+
+
+ org.wso2.carbon.devicemgt
+ io.entgra.notification.logger
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java
index 8e03917f55f..0d45a2efc1d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/DeviceManagementConstants.java
@@ -44,6 +44,7 @@ public final class DeviceManagementConstants {
public static final String DEVICE_CACHE = "DEVICE_CACHE";
public static final String API_RESOURCE_PERMISSION_CACHE = "API_RESOURCE_CACHE_CACHE";
public static final String GEOFENCE_CACHE = "GEOFENCE_CACHE";
+ public static final String BILLING_CACHE = "BILLING_CACHE";
public static final String META_KEY = "PER_DEVICE_COST";
public static final String ACTIVE_STATUS = "ACTIVE";
public static final String ENROLLMENT_NOTIFICATION_API_ENDPOINT = "/api/device-mgt/enrollment-notification";
@@ -131,9 +132,11 @@ public final class DeviceManagementConstants {
public static final String USER_REGISTRATION_TEMPLATE = "user-registration";
public static final String USER_ENROLLMENT_TEMPLATE = "user-enrollment";
public static final String USER_VERIFY_TEMPLATE = "user-verify";
+ public static final String PRODUCT_DOWNLOAD_LINK_SHARING_TEMPLATE = "share-product-download-url";
public static final String POLICY_VIOLATE_TEMPLATE = "policy-violating-notifier";
public static final String USER_WELCOME_TEMPLATE = "user-welcome";
public static final String DEFAULT_ENROLLMENT_TEMPLATE = "default-enrollment-invitation";
+ public static final String ENROLLMENT_GUIDE_TEMPLATE = "enrollment-guide";
}
public static final class OperationAttributes {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
index cc82921cbc4..7dde5efb162 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/app/mgt/ApplicationManagerProviderServiceImpl.java
@@ -354,4 +354,4 @@ public class ApplicationManagerProviderServiceImpl implements ApplicationManagem
DeviceManagementDAOFactory.closeConnection();
}
}
-}
\ No newline at end of file
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java
new file mode 100644
index 00000000000..c805529849c
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheKey.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * you may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.cache;
+
+import java.sql.Timestamp;
+import java.util.Objects;
+
+public class BillingCacheKey {
+
+ private String tenantDomain;
+ private Timestamp startDate;
+ private Timestamp endDate;
+ private volatile int hashCode;
+
+ public String getTenantDomain() {
+ return tenantDomain;
+ }
+
+ public void setTenantDomain(String tenantDomain) {
+ this.tenantDomain = tenantDomain;
+ }
+
+ public Timestamp getStartDate() {
+ return startDate;
+ }
+
+ public void setStartDate(Timestamp startDate) {
+ this.startDate = startDate;
+ }
+
+ public Timestamp getEndDate() {
+ return endDate;
+ }
+
+ public void setEndDate(Timestamp endDate) {
+ this.endDate = endDate;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null) {
+ return false;
+ }
+ if (!BillingCacheKey.class.isAssignableFrom(obj.getClass())) {
+ return false;
+ }
+ final BillingCacheKey other = (BillingCacheKey) obj;
+ String thisId = this.tenantDomain + "_" + this.startDate + "_" + this.endDate;
+ String otherId = other.tenantDomain + "_" + other.startDate + "_" + this.endDate;
+ if (!thisId.equals(otherId)) {
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public int hashCode() {
+ if (hashCode == 0) {
+ hashCode = Objects.hash(tenantDomain, startDate, endDate);
+ }
+ return hashCode;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java
new file mode 100644
index 00000000000..18723dc2d84
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/BillingCacheManager.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * you may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.cache;
+
+import org.wso2.carbon.device.mgt.common.PaginationResult;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+
+import java.sql.Timestamp;
+import java.util.List;
+
+public interface BillingCacheManager {
+ /**
+ * Adds a given billing object to the billing-cache.
+ * @param startDate - startDate of the billing period.
+ * @param endDate - endDate of the billing period.
+ * @param paginationResult - PaginationResult object to be added.
+ * @param tenantDomain - Owning tenant of the billing.
+ *
+ */
+ void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
+
+ /**
+ * Removes a billing object from billing-cache.
+ * @param startDate - startDate of the billing period.
+ * @param endDate - endDate of the billing period.
+ * @param tenantDomain - Owning tenant of the billing.
+ *
+ */
+ void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
+
+ /**
+ * Removes a list of devices from billing-cache.
+ * @param billingList - List of Cache-Keys of the billing objects to be removed.
+ *
+ */
+ void removeBillingsFromCache(List billingList) throws DeviceManagementException;
+
+ /**
+ * Updates a given billing object in the billing-cache.
+ * @param startDate - startDate of the billing period.
+ * @param endDate - endDate of the billing period.
+ * @param paginationResult - PaginationResult object to be updated.
+ * @param tenantDomain - Owning tenant of the billing.
+ *
+ */
+ void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
+
+ /**
+ * Fetches a billing object from billing-cache.
+ * @param startDate - startDate of the billing period.
+ * @param endDate - endDate of the billing period.
+ * @param tenantDomain - Owning tenant of the billing.
+ * @return Device object
+ *
+ */
+ PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate);
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java
new file mode 100644
index 00000000000..e5b6cddaa10
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/cache/impl/BillingCacheManagerImpl.java
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.cache.impl;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.device.mgt.common.PaginationResult;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey;
+import org.wso2.carbon.device.mgt.core.cache.BillingCacheManager;
+import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
+
+import javax.cache.Cache;
+import java.sql.Timestamp;
+import java.util.List;
+
+/**
+ * Implementation of BillingCacheManager.
+ */
+public class BillingCacheManagerImpl implements BillingCacheManager {
+
+ private static final Log log = LogFactory.getLog(BillingCacheManagerImpl.class);
+
+ private static BillingCacheManagerImpl billingCacheManager;
+
+ private BillingCacheManagerImpl() {
+ }
+
+ public static BillingCacheManagerImpl getInstance() {
+ if (billingCacheManager == null) {
+ synchronized (BillingCacheManagerImpl.class) {
+ if (billingCacheManager == null) {
+ billingCacheManager = new BillingCacheManagerImpl();
+ }
+ }
+ }
+ return billingCacheManager;
+ }
+
+ @Override
+ public void addBillingToCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
+ Cache lCache = DeviceManagerUtil.getBillingCache();
+ if (lCache != null) {
+ BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
+ if (lCache.containsKey(cacheKey)) {
+ this.updateBillingInCache(paginationResult, tenantDomain, startDate, endDate);
+ } else {
+ lCache.put(cacheKey, paginationResult);
+ }
+ }
+ }
+
+ @Override
+ public void removeBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
+ Cache lCache = DeviceManagerUtil.getBillingCache();
+ if (lCache != null) {
+ BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
+ if (lCache.containsKey(cacheKey)) {
+ lCache.remove(cacheKey);
+ }
+ } else {
+ String msg = "Failed to remove selected billing from cache";
+ log.error(msg);
+ throw new DeviceManagementException(msg);
+ }
+ }
+
+ @Override
+ public void removeBillingsFromCache(List billingList) throws DeviceManagementException {
+ Cache lCache = DeviceManagerUtil.getBillingCache();
+ if (lCache != null) {
+ for (BillingCacheKey cacheKey : billingList) {
+ if (lCache.containsKey(cacheKey)) {
+ lCache.remove(cacheKey);
+ }
+ }
+ } else {
+ String msg = "Failed to remove billing from cache";
+ log.error(msg);
+ throw new DeviceManagementException(msg);
+ }
+ }
+
+ @Override
+ public void updateBillingInCache(PaginationResult paginationResult, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
+ Cache lCache = DeviceManagerUtil.getBillingCache();
+ if (lCache != null) {
+ BillingCacheKey cacheKey = getCacheKey(tenantDomain, startDate, endDate);
+ if (lCache.containsKey(cacheKey)) {
+ lCache.replace(cacheKey, paginationResult);
+ }
+ } else {
+ String msg = "Failed to update billing cache";
+ log.error(msg);
+ throw new DeviceManagementException(msg);
+ }
+ }
+
+ // TODO remove null check from here and do cache enable check in the methods calling this
+ @Override
+ public PaginationResult getBillingFromCache(String tenantDomain, Timestamp startDate, Timestamp endDate) {
+ Cache lCache = DeviceManagerUtil.getBillingCache();
+ if (lCache != null) {
+ return lCache.get(getCacheKey(tenantDomain, startDate, endDate));
+ }
+ return null;
+ }
+
+ /**
+ * This method generates the billing CacheKey and returns it.
+ */
+ private BillingCacheKey getCacheKey(String tenantDomain, Timestamp startDate, Timestamp endDate) {
+ BillingCacheKey billingCacheKey = new BillingCacheKey();
+ billingCacheKey.setTenantDomain(tenantDomain);
+ billingCacheKey.setStartDate(startDate);
+ billingCacheKey.setEndDate(endDate);
+ return billingCacheKey;
+ }
+}
\ No newline at end of file
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java
index 0db16ff4518..7d7c3ba8536 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/Constants.java
@@ -24,4 +24,6 @@ public class Constants {
public static final String URI_SEPARATOR = "/";
public static final String BASIC_AUTH_HEADER_PREFIX = "Basic ";
public static final String BEARER = "Bearer ";
+ public static final String SEND_USERNAME = "SEND_USERNAME";
+
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java
new file mode 100644
index 00000000000..38985716deb
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java
@@ -0,0 +1,32 @@
+/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.common.exception;
+
+/**
+ * Represents the exception thrown during storing and retrieving the artifacts.
+ */
+public class StorageManagementException extends Exception {
+ public StorageManagementException(String message, Throwable ex) {
+ super(message, ex);
+ }
+
+ public StorageManagementException(String message) {
+ super(message);
+ }
+}
+
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java
index 9626c8198f8..269e6b7957e 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/FileUtil.java
@@ -19,6 +19,8 @@
package org.wso2.carbon.device.mgt.core.common.util;
import org.apache.commons.io.FileUtils;
+import org.wso2.carbon.device.mgt.common.Base64File;
+
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -54,7 +56,7 @@ public class FileUtil {
}
/**
- * Useful to convert input stream to base64 string
+ * Useful to convert file to base64 string
*
* @param file stream to be converted
* @return base64 string of the provided input stream
@@ -64,6 +66,17 @@ public class FileUtil {
return Base64.getEncoder().encodeToString(fileContent);
}
+ /**
+ * Useful to convert {@link File} to {@link Base64File}
+ *
+ * @param file to be converted
+ * @return {@link Base64File} of the provided input stream
+ */
+ public static Base64File fileToBase64File(File file) throws IOException {
+ String base64String = fileToBase64String(file);
+ return new Base64File(file.getName(), base64String);
+ }
+
/**
* This generates file name with a suffix depending on the duplicate name count, useful when saving
* files with the same name
@@ -75,7 +88,7 @@ public class FileUtil {
String suffix = generateDuplicateFileNameSuffix(fileNameCount);
String fileNameWithoutExtension = extractFileNameWithoutExtension(fileName);
String fileNameWithSuffix = fileNameWithoutExtension + suffix;
- fileNameWithSuffix = fileNameWithSuffix + '.' + extractFileExtension(fileName);
+ fileNameWithSuffix = fileNameWithSuffix + '.' + extractFileExtensionFileName(fileName);
return fileNameWithSuffix;
}
@@ -98,13 +111,27 @@ public class FileUtil {
return suffix;
}
+ /**
+ * Use to extract file extension from file path
+ *
+ * @param filePath path of the file
+ * @return extension of the file
+ */
+ public static String extractFileExtensionFromFilePath(String filePath) {
+ File file = new File(filePath);
+ return extractFileExtensionFileName(file.getName());
+ }
+
/**
* Use to extract file extension from file name
*
* @param fileName name of the file
* @return extension of the file
*/
- private static String extractFileExtension(String fileName) {
+ public static String extractFileExtensionFileName(String fileName) {
+ if (!fileName.contains(".")) {
+ return "";
+ }
return fileName.substring(fileName.lastIndexOf('.') + 1);
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java
index afd8ad5f44c..84b895be37c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/HttpUtil.java
@@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.common.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
+import org.apache.commons.validator.routines.UrlValidator;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
@@ -234,4 +235,16 @@ public class HttpUtil {
ContentType contentType = ContentType.getOrDefault(response.getEntity());
return contentType.getMimeType();
}
+
+ /**
+ * Validate http url (For example make sure it uses http/https protocol)
+ *
+ * @param url url to be checked if valid
+ * @return if provided http url is valid
+ */
+ public static boolean isHttpUrlValid(String url) {
+ String[] schemes = {"http","https"};
+ UrlValidator urlValidator = new UrlValidator(schemes, UrlValidator.ALLOW_LOCAL_URLS);
+ return urlValidator.isValid(url);
+ }
}
diff --git a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/StorageManagementUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/StorageManagementUtil.java
similarity index 67%
rename from components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/StorageManagementUtil.java
rename to components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/StorageManagementUtil.java
index f0819dbd807..9766a7a3936 100644
--- a/components/application-mgt/io.entgra.application.mgt.core/src/main/java/io/entgra/application/mgt/core/util/StorageManagementUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/util/StorageManagementUtil.java
@@ -16,16 +16,12 @@
* under the License.
*/
-package io.entgra.application.mgt.core.util;
+package org.wso2.carbon.device.mgt.core.common.util;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import io.entgra.application.mgt.common.ImageArtifact;
-import io.entgra.application.mgt.common.exception.ApplicationStorageManagementException;
-import io.entgra.application.mgt.common.exception.ResourceManagementException;
+import org.wso2.carbon.device.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
import java.io.File;
import java.io.FileInputStream;
@@ -47,14 +43,13 @@ public class StorageManagementUtil {
* This method is responsible for creating artifact parent directories in the given path.
*
* @param artifactDirectoryPath Path for the artifact directory.
- * @throws ResourceManagementException Resource Management Exception.
*/
- public static void createArtifactDirectory(String artifactDirectoryPath) throws ResourceManagementException {
+ public static void createArtifactDirectory(String artifactDirectoryPath) throws StorageManagementException {
File artifactDirectory = new File(artifactDirectoryPath);
if (!artifactDirectory.exists() && !artifactDirectory.mkdirs()) {
- throw new ResourceManagementException(
- "Cannot create directories in the path to save the application related artifacts");
+ throw new StorageManagementException(
+ "Cannot create directories in the path: " + artifactDirectoryPath);
}
}
@@ -103,20 +98,13 @@ public class StorageManagementUtil {
}
/**
- * To create {@link ImageArtifact}.
+ * To save a bas64 string of a file in a given location.
*
- * @param imageFile Image File.
- * @param imageArtifactPath Path of the image artifact file.
- * @return Image Artifact.
- * @throws IOException IO Exception.
+ * @param base64File {@link Base64File} of the file.
*/
- public static ImageArtifact createImageArtifact(File imageFile, String imageArtifactPath) throws IOException {
- ImageArtifact imageArtifact = new ImageArtifact();
- imageArtifact.setName(imageFile.getName());
- imageArtifact.setType(Files.probeContentType(imageFile.toPath()));
- byte[] imageBytes = IOUtils.toByteArray(new FileInputStream(imageArtifactPath));
- imageArtifact.setEncodedImage(Base64.encodeBase64URLSafeString(imageBytes));
- return imageArtifact;
+ public static void saveFile(Base64File base64File, String path) throws IOException {
+ InputStream inputStream = FileUtil.base64ToInputStream(base64File.getBase64String());
+ saveFile(inputStream, path);
}
/***
@@ -138,16 +126,4 @@ public class StorageManagementUtil {
throw new IOException(msg, e);
}
}
-
- public static String getMD5(InputStream binaryFile) throws ApplicationStorageManagementException {
- String md5;
- try {
- md5 = DigestUtils.md5Hex(binaryFile);
- } catch (IOException e) {
- String msg = "IO Exception occurred while trying to get the md5sum value of application";
- log.error(msg, e);
- throw new ApplicationStorageManagementException(msg, e);
- }
- return md5;
- }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
index ebdfa35bfc3..891e2863399 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/DeviceManagementConfig.java
@@ -21,10 +21,13 @@ import org.wso2.carbon.device.mgt.common.enrollment.notification.EnrollmentNotif
import org.wso2.carbon.device.mgt.common.roles.config.DefaultRoles;
import org.wso2.carbon.device.mgt.core.config.analytics.OperationAnalyticsConfiguration;
import org.wso2.carbon.device.mgt.core.config.archival.ArchivalConfiguration;
+import org.wso2.carbon.device.mgt.core.config.cache.BillingCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.CertificateCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.DeviceCacheConfiguration;
import org.wso2.carbon.device.mgt.core.config.cache.GeoFenceCacheConfiguration;
+import org.wso2.carbon.device.mgt.core.config.enrollment.guide.EnrollmentGuideConfiguration;
import org.wso2.carbon.device.mgt.core.config.operation.timeout.OperationTimeoutConfiguration;
+import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration;
import org.wso2.carbon.device.mgt.core.event.config.EventOperationTaskConfiguration;
import org.wso2.carbon.device.mgt.core.config.geo.location.GeoLocationConfiguration;
import org.wso2.carbon.device.mgt.core.config.identity.IdentityConfigurations;
@@ -58,6 +61,7 @@ public final class DeviceManagementConfig {
private DeviceStatusTaskConfig deviceStatusTaskConfig;
private DeviceCacheConfiguration deviceCacheConfiguration;
private GeoFenceCacheConfiguration geoFenceCacheConfiguration;
+ private BillingCacheConfiguration billingCacheConfiguration;
private EventOperationTaskConfiguration eventOperationTaskConfiguration;
private CertificateCacheConfiguration certificateCacheConfiguration;
private OperationAnalyticsConfiguration operationAnalyticsConfiguration;
@@ -68,6 +72,8 @@ public final class DeviceManagementConfig {
private EnrollmentNotificationConfiguration enrollmentNotificationConfiguration;
private DefaultRoles defaultRoles;
private OperationTimeoutConfiguration operationTimeoutConfiguration;
+ private MetaDataConfiguration metaDataConfiguration;
+ private EnrollmentGuideConfiguration enrollmentGuideConfiguration;
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
@@ -169,6 +175,15 @@ public final class DeviceManagementConfig {
this.geoFenceCacheConfiguration = geoFenceCacheConfiguration;
}
+ @XmlElement(name = "BillingCacheConfiguration", required = true)
+ public BillingCacheConfiguration getBillingCacheConfiguration() {
+ return billingCacheConfiguration;
+ }
+
+ public void setBillingCacheConfiguration(BillingCacheConfiguration billingCacheConfiguration) {
+ this.billingCacheConfiguration = billingCacheConfiguration;
+ }
+
@XmlElement(name = "EventOperationTaskConfiguration", required = true)
public EventOperationTaskConfiguration getEventOperationTaskConfiguration() {
return eventOperationTaskConfiguration;
@@ -254,5 +269,23 @@ public final class DeviceManagementConfig {
public void setOperationTimeoutConfiguration(OperationTimeoutConfiguration operationTimeoutConfiguration) {
this.operationTimeoutConfiguration = operationTimeoutConfiguration;
}
+
+ @XmlElement(name = "MetaDataConfiguration", required = true)
+ public MetaDataConfiguration getMetaDataConfiguration() {
+ return metaDataConfiguration;
+ }
+
+ public void setMetaDataConfiguration(MetaDataConfiguration metaDataConfiguration) {
+ this.metaDataConfiguration = metaDataConfiguration;
+ }
+
+ @XmlElement(name = "EnrollmentGuideConfiguration", required = true)
+ public EnrollmentGuideConfiguration getEnrollmentGuideConfiguration() {
+ return enrollmentGuideConfiguration;
+ }
+
+ public void setEnrollmentGuideConfiguration(EnrollmentGuideConfiguration enrollmentGuideConfiguration) {
+ this.enrollmentGuideConfiguration = enrollmentGuideConfiguration;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java
new file mode 100644
index 00000000000..b34b9c2b6e0
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/cache/BillingCacheConfiguration.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2022, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * WSO2 Inc. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.cache;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "BillingCacheConfiguration")
+public class BillingCacheConfiguration {
+ private boolean isEnabled;
+ private int expiryTime;
+ private long capacity;
+
+ @XmlElement(name = "Enable", required = true)
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ isEnabled = enabled;
+ }
+
+ @XmlElement(name = "ExpiryTime", required = true)
+ public int getExpiryTime() {
+ return expiryTime;
+ }
+
+ public void setExpiryTime(int expiryTime) {
+ this.expiryTime = expiryTime;
+ }
+
+ @XmlElement(name = "Capacity", required = true)
+ public long getCapacity() {
+ return capacity;
+ }
+
+ public void setCapacity(long capacity) {
+ this.capacity = capacity;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java
new file mode 100644
index 00000000000..5f54cf79d41
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/enrollment/guide/EnrollmentGuideConfiguration.java
@@ -0,0 +1,30 @@
+package org.wso2.carbon.device.mgt.core.config.enrollment.guide;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "EnrollmentGuideConfiguration")
+public class EnrollmentGuideConfiguration {
+
+ private boolean isEnabled;
+ private String mail;
+
+ @XmlElement(name = "Enable", required = true)
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ isEnabled = enabled;
+ }
+
+ @XmlElement(name = "Mail", required = true)
+ public String getMail() {
+ return mail;
+ }
+
+ public void setMail(String mail) {
+ this.mail = mail;
+ }
+
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/MetaDataConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/MetaDataConfiguration.java
new file mode 100644
index 00000000000..848f206441d
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/MetaDataConfiguration.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.metadata.mgt;
+
+import org.wso2.carbon.device.mgt.core.config.metadata.mgt.whitelabel.WhiteLabelConfiguration;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "MetaDataConfiguration")
+public class MetaDataConfiguration {
+ private WhiteLabelConfiguration whiteLabelConfiguration;
+
+ @XmlElement(name = "WhiteLabelConfiguration", required = true)
+ public WhiteLabelConfiguration getWhiteLabelConfiguration() {
+ return whiteLabelConfiguration;
+ }
+
+ public void setWhiteLabelConfiguration(WhiteLabelConfiguration whiteLabelConfiguration) {
+ this.whiteLabelConfiguration = whiteLabelConfiguration;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelConfiguration.java
new file mode 100644
index 00000000000..436146f5b66
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelConfiguration.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.metadata.mgt.whitelabel;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "WhiteLabelConfiguration")
+public class WhiteLabelConfiguration {
+ private String footerText;
+ private String appTitle;
+ private WhiteLabelImages whiteLabelImages;
+
+ @XmlElement(name = "FooterText", required = true)
+ public String getFooterText() {
+ return footerText;
+ }
+
+ public void setFooterText(String footerText) {
+ this.footerText = footerText;
+ }
+
+ @XmlElement(name = "WhiteLabelImages", required = true)
+ public WhiteLabelImages getWhiteLabelImages() {
+ return whiteLabelImages;
+ }
+
+ public void setWhiteLabelImages(WhiteLabelImages whiteLabelImages) {
+ this.whiteLabelImages = whiteLabelImages;
+ }
+
+ @XmlElement(name = "AppTitle", required = true)
+ public String getAppTitle() {
+ return appTitle;
+ }
+
+ public void setAppTitle(String appTitle) {
+ this.appTitle = appTitle;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelImages.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelImages.java
new file mode 100644
index 00000000000..7a01bc2538e
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/metadata/mgt/whitelabel/WhiteLabelImages.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.metadata.mgt.whitelabel;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "WhiteLabelImages")
+public class WhiteLabelImages {
+
+ private String storagePath;
+ private String defaultImagesLocation;
+ private String defaultFaviconName;
+ private String defaultLogoName;
+ private String defaultLogoIconName;
+
+ @XmlElement(name = "StoragePath", required = true)
+ public String getStoragePath() {
+ return storagePath;
+ }
+
+ public void setStoragePath(String storagePath) {
+ this.storagePath = storagePath;
+ }
+
+ @XmlElement(name = "DefaultFaviconName", required = true)
+ public String getDefaultFaviconName() {
+ return defaultFaviconName;
+ }
+
+ public void setDefaultFaviconName(String defaultFaviconName) {
+ this.defaultFaviconName = defaultFaviconName;
+ }
+
+ @XmlElement(name = "DefaultLogoName", required = true)
+ public String getDefaultLogoName() {
+ return defaultLogoName;
+ }
+
+ public void setDefaultLogoName(String defaultLogoName) {
+ this.defaultLogoName = defaultLogoName;
+ }
+
+ @XmlElement(name = "DefaultImagesLocation", required = true)
+ public String getDefaultImagesLocation() {
+ return defaultImagesLocation;
+ }
+
+ @XmlElement(name = "DefaultLogoIconName", required = true)
+ public String getDefaultLogoIconName() {
+ return defaultLogoIconName;
+ }
+
+ public void setDefaultLogoIconName(String defaultLogoIconName) {
+ this.defaultLogoIconName = defaultLogoIconName;
+ }
+
+ public void setDefaultImagesLocation(String defaultImagesLocation) {
+ this.defaultImagesLocation = defaultImagesLocation;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java
new file mode 100644
index 00000000000..ec22d125a15
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/HubspotChat.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.config.ui;
+
+import javax.xml.bind.annotation.XmlElement;
+
+public class HubspotChat {
+ private boolean isEnableHubspot;
+ private String trackingUrl;
+ private String accessToken;
+ private String senderActorId;
+
+ @XmlElement(name = "EnableHubspot")
+ public boolean isEnableHubspot() {
+ return isEnableHubspot;
+ }
+
+ public void setEnableHubspot(boolean enableHubspot) {
+ isEnableHubspot = enableHubspot;
+ }
+
+ @XmlElement(name = "TrackingUrl")
+ public String getTrackingUrl() {
+ return trackingUrl;
+ }
+
+ public void setTrackingUrl(String trackingUrl) {
+ this.trackingUrl = trackingUrl;
+ }
+
+ @XmlElement(name = "AccessToken")
+ public String getAccessToken() {
+ return accessToken;
+ }
+
+ public void setAccessToken(String accessToken) {
+ this.accessToken = accessToken;
+ }
+ @XmlElement(name = "SenderActorId")
+ public String getSenderActorId() {
+ return senderActorId;
+ }
+
+ public void setSenderActorId(String senderActorId) {
+ this.senderActorId = senderActorId;
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java
index 551c1558ea3..dca4a76a6bb 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/config/ui/UIConfiguration.java
@@ -34,6 +34,7 @@ public class UIConfiguration {
private int sessionTimeOut;
private int loginCacheCapacity;
private Billing billing;
+ private HubspotChat hubspotChat;
@XmlElement(name = "AppRegistration", required=true)
public AppRegistration getAppRegistration() {
@@ -63,6 +64,14 @@ public class UIConfiguration {
isSsoEnable = ssoEnable;
}
+ @XmlElement(name = "HubspotChat", required = true)
+ public HubspotChat getHubspotChat() {
+ return hubspotChat;
+ }
+
+ public void setHubspotChat(HubspotChat hubspotChat) {
+ this.hubspotChat = hubspotChat;
+ }
@XmlElement(name = "Billing", required=true)
public Billing getBilling() {
return billing;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java
deleted file mode 100644
index dd0ddf4e286..00000000000
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/BillingDAO.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package org.wso2.carbon.device.mgt.core.dao;
-
-import org.wso2.carbon.device.mgt.common.Billing;
-
-import java.sql.Timestamp;
-import java.util.List;
-
-public interface BillingDAO {
-
- void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException;
-
- List getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException;
-}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java
index fcf414ff087..e9c4e1bf9e4 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java
@@ -293,6 +293,50 @@ public interface DeviceDAO {
*/
List getDevices(PaginationRequest request, int tenantId) throws DeviceManagementDAOException;
+ /**
+ * This method is used to retrieve the not removed device list in a year of a given tenant without pagination.
+ *
+ * @param tenantId tenant id.
+ * @param startDate start date of usage period.
+ * @param endDate end date of usage period.
+ * @return returns a list of not removed devices enrolled in that year.
+ * @throws DeviceManagementDAOException
+ */
+ List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
+
+ /**
+ * This method is used to retrieve the removed device list in a year of a given tenant without pagination.
+ *
+ * @param tenantId tenant id.
+ * @param startDate start date of usage period.
+ * @param endDate end date of usage period.
+ * @return returns a list of removed devices enrolled in that year.
+ * @throws DeviceManagementDAOException
+ */
+ List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
+
+ /**
+ * This method is used to retrieve the not removed device list in the prior year of a given tenant without pagination.
+ *
+ * @param tenantId tenant id.
+ * @param startDate start date of usage period.
+ * @param endDate end date of usage period.
+ * @return returns a list of not removed devices enrolled prior to that year.
+ * @throws DeviceManagementDAOException
+ */
+ List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
+
+ /**
+ * This method is used to retrieve the removed device list in the prior year of a given tenant without pagination.
+ *
+ * @param tenantId tenant id.
+ * @param startDate start date of usage period.
+ * @param endDate end date of usage period.
+ * @return returns a list of removed devices enrolled prior to that year.
+ * @throws DeviceManagementDAOException
+ */
+ List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate) throws DeviceManagementDAOException;
+
/**
* This method is used to retrieve the devices of a given tenant without pagination.
* @param tenantId tenant id.
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
index 230a958d198..cbd7c697f4a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceManagementDAOFactory.java
@@ -125,11 +125,6 @@ public class DeviceManagementDAOFactory {
return new EnrollmentDAOImpl();
}
- public static BillingDAO getBillingDAO() {
- return new BillingDAOImpl();
- }
-
-
public static TrackerDAO getTrackerDAO() {
if (databaseEngine != null) {
switch (databaseEngine) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java
index 825fa647979..612ebb76099 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/EnrollmentDAO.java
@@ -33,8 +33,6 @@ public interface EnrollmentDAO {
boolean updateEnrollmentStatus(List enrolmentInfos) throws DeviceManagementDAOException;
- boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfos, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException;
-
int removeEnrollment(int deviceId, String currentOwner, int tenantId) throws DeviceManagementDAOException;
@Deprecated
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java
deleted file mode 100644
index 4af343012b0..00000000000
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/BillingDAOImpl.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package org.wso2.carbon.device.mgt.core.dao.impl;
-
-import org.wso2.carbon.device.mgt.common.Billing;
-import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
-import org.wso2.carbon.device.mgt.core.dao.BillingDAO;
-import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
-import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
-import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
-
-import java.sql.*;
-import java.util.ArrayList;
-import java.util.List;
-
-public class BillingDAOImpl implements BillingDAO {
-
- @Override
- public void addBilling(int deviceId, int tenantId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException {
-
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- try {
- conn = this.getConnection();
- String sql = "INSERT INTO DM_BILLING(DEVICE_ID, TENANT_ID, BILLING_START, BILLING_END) VALUES(?, ?, ?, ?)";
- stmt = conn.prepareStatement(sql, new String[] {"invoice_id"});
- stmt.setInt(1, deviceId);
- stmt.setInt(2,tenantId);
- stmt.setTimestamp(3, billingStart);
- stmt.setTimestamp(4, billingEnd);
- stmt.execute();
- } catch (SQLException e) {
- e.printStackTrace();
- throw new DeviceManagementDAOException("Error occurred while adding billing period", e);
- } finally {
- DeviceManagementDAOUtil.cleanupResources(stmt, rs);
- }
- }
-
- @Override
- public List getBilling(int deviceId, Timestamp billingStart, Timestamp billingEnd) throws DeviceManagementDAOException {
- List billings = new ArrayList<>();
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- EnrolmentInfo.Status status = null;
- try {
- conn = this.getConnection();
- String sql;
-
- sql = "SELECT * FROM DM_BILLING WHERE DEVICE_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, deviceId);
- rs = stmt.executeQuery();
-
- while (rs.next()) {
- Billing bill = new Billing(rs.getInt("INVOICE_ID"), rs.getInt("DEVICE_ID"),rs.getInt("TENANT_ID"),
- (rs.getTimestamp("BILLING_START").getTime()), (rs.getTimestamp("BILLING_END").getTime()));
- billings.add(bill);
- }
- } catch (SQLException e) {
- throw new DeviceManagementDAOException("Error occurred getting billing periods", e);
- } finally {
- DeviceManagementDAOUtil.cleanupResources(stmt, null);
- }
- return billings;
- }
-
- private Connection getConnection() throws SQLException {
- return DeviceManagementDAOFactory.getConnection();
- }
-}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java
index c237d4ce22d..eb5373e2cf2 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/DeviceStatusDAOImpl.java
@@ -25,13 +25,7 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO {
conn = this.getConnection();
// either we list all status values for the device using the device id or only get status values for the given enrolment id
String idType = isDeviceId ? "DEVICE_ID" : "ENROLMENT_ID";
- String sql;
-
- if (billingStatus) {
- sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE STATUS IN ('ACTIVE','REMOVED') AND " + idType + " = ?";
- } else {
- sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?";
- }
+ String sql = "SELECT ENROLMENT_ID, DEVICE_ID, UPDATE_TIME, STATUS, CHANGED_BY FROM DM_DEVICE_STATUS WHERE " + idType + " = ?";
// filter the data based on a date range if specified
if (fromDate != null){
@@ -41,6 +35,10 @@ public class DeviceStatusDAOImpl implements DeviceStatusDAO {
sql += " AND UPDATE_TIME <= ?";
}
+ if (billingStatus) {
+ sql += " ORDER BY UPDATE_TIME DESC";
+ }
+
stmt = conn.prepareStatement(sql);
int i = 1;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java
index a8fbad8ff96..7b3e08cd509 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/EnrollmentDAOImpl.java
@@ -144,28 +144,6 @@ public class EnrollmentDAOImpl implements EnrollmentDAO {
return status;
}
- @Override
- public boolean updateEnrollmentLastBilledDate(EnrolmentInfo enrolmentInfo, Timestamp lastBilledDate, int tenantId) throws DeviceManagementDAOException {
- Connection conn;
- PreparedStatement stmt = null;
- ResultSet rs = null;
- try {
- conn = this.getConnection();
- String sql = "UPDATE DM_ENROLMENT SET LAST_BILLED_DATE = ? WHERE ID = ? AND TENANT_ID = ?";
- stmt = conn.prepareStatement(sql);
- stmt.setLong(1, lastBilledDate.getTime());
- stmt.setInt(2, enrolmentInfo.getId());
- stmt.setInt(3, tenantId);
- stmt.executeUpdate();
- return true;
- } catch (SQLException e) {
- throw new DeviceManagementDAOException("Error occurred while updating enrolment last billed date.", e);
- } finally {
- DeviceManagementDAOUtil.cleanupResources(stmt, rs);
- }
- }
-
-
@Override
public int removeEnrollment(int deviceId, String currentOwner,
int tenantId) throws DeviceManagementDAOException {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java
index 38fc88825d6..b40b5f5f209 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/GenericDeviceDAOImpl.java
@@ -84,7 +84,6 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
"e.IS_TRANSFERRED, " +
"e.DATE_OF_LAST_UPDATE, " +
"e.DATE_OF_ENROLMENT, " +
- "e.LAST_BILLED_DATE, " +
"e.ID AS ENROLMENT_ID " +
"FROM DM_ENROLMENT e, " +
"(SELECT d.ID, " +
@@ -188,6 +187,169 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
+ @Override
+ public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ List devices = new ArrayList<>();
+ try {
+ Connection conn = getConnection();
+ String sql = "SELECT d.ID AS DEVICE_ID, " +
+ "DEVICE_IDENTIFICATION, " +
+ "DESCRIPTION, " +
+ "NAME, " +
+ "DATE_OF_ENROLMENT, " +
+ "STATUS, " +
+ "DATE_OF_LAST_UPDATE, " +
+ "TIMESTAMPDIFF(DAY, ?, DATE_OF_ENROLMENT) as DAYS_SINCE_ENROLLED " +
+ "FROM DM_DEVICE d, DM_ENROLMENT e " +
+ "WHERE " +
+ "e.TENANT_ID=? AND " +
+ "d.ID=e.DEVICE_ID AND " +
+ "STATUS !='REMOVED' AND " +
+ "(" +
+ "DATE_OF_ENROLMENT BETWEEN ? AND ? " +
+ ")";
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setString(1, String.valueOf(endDate));
+ stmt.setInt(2, tenantId);
+ stmt.setString(3, String.valueOf(startDate));
+ stmt.setString(4, String.valueOf(endDate));
+ ResultSet rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
+ }
+ }
+ } catch (SQLException e) {
+ throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedYearly device billing ", e);
+ }
+ return devices;
+ }
+
+ @Override
+ public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ Connection conn;
+ List devices = new ArrayList<>();
+ try {
+ conn = this.getConnection();
+ String sql = "select d.ID AS DEVICE_ID, " +
+ "DEVICE_IDENTIFICATION, " +
+ "DESCRIPTION, " +
+ "NAME, " +
+ "DATE_OF_ENROLMENT, " +
+ "DATE_OF_LAST_UPDATE, " +
+ "STATUS, " +
+ "TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, DATE_OF_ENROLMENT) AS DAYS_USED " +
+ "from DM_DEVICE d, DM_ENROLMENT e " +
+ "where " +
+ "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " +
+ "STATUS ='REMOVED' and " +
+ "(" +
+ "DATE_OF_ENROLMENT between ? and ? " +
+ ") and " +
+ "(" +
+ "DATE_OF_LAST_UPDATE >= ? " +
+ ")";
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setInt(1, tenantId);
+ stmt.setString(2, String.valueOf(startDate));
+ stmt.setString(3, String.valueOf(endDate));
+ stmt.setString(4, String.valueOf(startDate));
+ ResultSet rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
+ }
+ }
+ } catch (SQLException e) {
+ throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedYearly device billing ", e);
+ }
+ return devices;
+ }
+
+ @Override
+ public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ Connection conn;
+ List devices = new ArrayList<>();
+ try {
+ conn = this.getConnection();
+ String sql = "select d.ID AS DEVICE_ID, " +
+ "DEVICE_IDENTIFICATION, " +
+ "DESCRIPTION, " +
+ "NAME, " +
+ "DATE_OF_ENROLMENT, " +
+ "STATUS, " +
+ "DATE_OF_LAST_UPDATE, " +
+ "TIMESTAMPDIFF(DAY, ?, ?) as DAYS_SINCE_ENROLLED " +
+ "from DM_DEVICE d, DM_ENROLMENT e " +
+ "where " +
+ "e.TENANT_ID=? and " +
+ "d.ID=e.DEVICE_ID and " +
+ "STATUS !='REMOVED' and " +
+ "(" +
+ "DATE_OF_ENROLMENT < ? " +
+ ")";
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setString(1, String.valueOf(endDate));
+ stmt.setString(2, String.valueOf(startDate));
+ stmt.setInt(3, tenantId);
+ stmt.setString(4, String.valueOf(startDate));
+ ResultSet rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
+ }
+ }
+ } catch (SQLException e) {
+ throw new DeviceManagementDAOException("Error occurred while fetching the list of NonRemovedPriorYears device billing ", e);
+ }
+ return devices;
+ }
+
+ @Override
+ public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ Connection conn;
+ List devices = new ArrayList<>();
+ try {
+ conn = this.getConnection();
+ String sql = "select d.ID AS DEVICE_ID, " +
+ "DEVICE_IDENTIFICATION, " +
+ "DESCRIPTION, " +
+ "NAME, " +
+ "DATE_OF_ENROLMENT, " +
+ "DATE_OF_LAST_UPDATE, " +
+ "STATUS, " +
+ "TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, ?) AS DAYS_USED " +
+ "from DM_DEVICE d, DM_ENROLMENT e " +
+ "where " +
+ "e.TENANT_ID=? and d.ID=e.DEVICE_ID and " +
+ "STATUS ='REMOVED' and " +
+ "(" +
+ "DATE_OF_ENROLMENT < ? " +
+ ") and " +
+ "(" +
+ "DATE_OF_LAST_UPDATE >= ? " +
+ ")";
+ try (PreparedStatement stmt = conn.prepareStatement(sql)) {
+ stmt.setString(1, String.valueOf(startDate));
+ stmt.setInt(2, tenantId);
+ stmt.setString(3, String.valueOf(startDate));
+ stmt.setString(4, String.valueOf(startDate));
+ ResultSet rs = stmt.executeQuery();
+
+ while (rs.next()) {
+ devices.add(DeviceManagementDAOUtil.loadDeviceBilling(rs));
+ }
+ }
+ } catch (SQLException e) {
+ throw new DeviceManagementDAOException("Error occurred while fetching the list of RemovedPriorYears device billing ", e);
+ }
+ return devices;
+ }
+
//Return only not removed id list
@Override
public List getDeviceListWithoutPagination(int tenantId)
@@ -197,10 +359,26 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
List devices = new ArrayList<>();
try {
conn = this.getConnection();
- String sql = "SELECT DM_DEVICE.ID AS DEVICE_ID, DEVICE_IDENTIFICATION, DESCRIPTION, DM_DEVICE.NAME AS DEVICE_NAME, DM_DEVICE_TYPE.NAME AS DEVICE_TYPE,\n" +
- "DM_ENROLMENT.ID AS ENROLMENT_ID, DATE_OF_ENROLMENT,OWNER, OWNERSHIP,IS_TRANSFERRED, STATUS, DATE_OF_LAST_UPDATE, LAST_BILLED_DATE,\n" +
- "TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED FROM DM_DEVICE JOIN DM_ENROLMENT\n" +
- "ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) WHERE DM_ENROLMENT.TENANT_ID=?";
+ String sql = "SELECT " +
+ "DM_DEVICE.ID AS DEVICE_ID, " +
+ "DEVICE_IDENTIFICATION, " +
+ "DESCRIPTION, " +
+ "DM_DEVICE.NAME AS DEVICE_NAME, " +
+ "DM_DEVICE_TYPE.NAME AS DEVICE_TYPE, " +
+ "DM_ENROLMENT.ID AS ENROLMENT_ID, " +
+ "DATE_OF_ENROLMENT, " +
+ "OWNER, " +
+ "OWNERSHIP, " +
+ "IS_TRANSFERRED, " +
+ "STATUS, " +
+ "DATE_OF_LAST_UPDATE, " +
+ "TIMESTAMPDIFF(DAY, DATE_OF_ENROLMENT, CURDATE()) as DAYS_SINCE_ENROLLED " +
+ "FROM " +
+ "DM_DEVICE " +
+ "JOIN DM_ENROLMENT ON (DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) " +
+ "JOIN DM_DEVICE_TYPE ON (DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID) " +
+ "WHERE " +
+ "DM_ENROLMENT.TENANT_ID = ? ";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, tenantId);
ResultSet rs = stmt.executeQuery();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java
index 08c5afd3118..c65e37d15a9 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/OracleDeviceDAOImpl.java
@@ -263,6 +263,34 @@ public class OracleDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
+// TODO - add Oracle support for below billing method
+ @Override
+ public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add Oracle support for below billing method
+ @Override
+ public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add Oracle support for below billing method
+ @Override
+ public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add Oracle support for below billing method
+ @Override
+ public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
@Override
public List getDeviceListWithoutPagination(int tenantId) throws DeviceManagementDAOException {
return null;
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java
index 7fdaaca4bd9..b23056de987 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/PostgreSQLDeviceDAOImpl.java
@@ -179,6 +179,35 @@ public class PostgreSQLDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
+ // TODO - add PostgreSQL support for below billing method
+ @Override
+ public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add PostgreSQL support for below billing method
+ @Override
+ public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add PostgreSQL support for below billing method
+ @Override
+ public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add PostgreSQL support for below billing method
+ @Override
+ public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+
//Return only not removed id list
@Override
public List getDevicesIds(PaginationRequest request, int tenantId)
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java
index baf3f92f618..e8f86c5c10a 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/impl/device/SQLServerDeviceDAOImpl.java
@@ -189,6 +189,35 @@ public class SQLServerDeviceDAOImpl extends AbstractDeviceDAOImpl {
}
}
+ // TODO - add SQL support for below billing method
+ @Override
+ public List getNonRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add SQL support for below billing method
+ @Override
+ public List getRemovedYearlyDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add SQL support for below billing method
+ @Override
+ public List getNonRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+ // TODO - add SQL support for below billing method
+ @Override
+ public List getRemovedPriorYearsDeviceList(int tenantId, Timestamp startDate, Timestamp endDate)
+ throws DeviceManagementDAOException {
+ return null;
+ }
+
+
//Return only not removed id list
@Override
public List getDevicesIds(PaginationRequest request, int tenantId)
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java
index 089bb4cf034..0fd111d76ed 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/util/DeviceManagementDAOUtil.java
@@ -144,14 +144,6 @@ public final class DeviceManagementDAOUtil {
public static EnrolmentInfo loadEnrolment(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
- String columnName = "LAST_BILLED_DATE";
- ResultSetMetaData rsmd = rs.getMetaData();
- int columns = rsmd.getColumnCount();
- for (int x = 1; x <= columns; x++) {
- if (columnName.equals(rsmd.getColumnName(x))) {
- enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
- }
- }
enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setOwner(rs.getString("OWNER"));
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.valueOf(rs.getString("OWNERSHIP")));
@@ -162,15 +154,12 @@ public final class DeviceManagementDAOUtil {
return enrolmentInfo;
}
+ /* This is used to set the enrollment data of the billing query */
public static EnrolmentInfo loadEnrolmentBilling(ResultSet rs) throws SQLException {
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
- enrolmentInfo.setId(rs.getInt("ENROLMENT_ID"));
enrolmentInfo.setDateOfEnrolment(rs.getTimestamp("DATE_OF_ENROLMENT").getTime());
- enrolmentInfo.setLastBilledDate(rs.getLong("LAST_BILLED_DATE"));
+ enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.valueOf(rs.getString("STATUS")));
- if (EnrolmentInfo.Status.valueOf(rs.getString("STATUS")).equals("REMOVED")) {
- enrolmentInfo.setDateOfLastUpdate(rs.getTimestamp("DATE_OF_LAST_UPDATE").getTime());
- }
return enrolmentInfo;
}
@@ -245,29 +234,23 @@ public final class DeviceManagementDAOUtil {
return device;
}
- public static Device loadDeviceIds(ResultSet rs) throws SQLException {
+ /* This is used to set the device data of the billing query */
+ public static Device loadDeviceBilling(ResultSet rs) throws SQLException {
Device device = new Device();
device.setId(rs.getInt("DEVICE_ID"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
- device.setEnrolmentInfo(loadEnrolmentStatus(rs));
+ device.setName(rs.getString("DESCRIPTION"));
+ device.setDescription(rs.getString("NAME"));
+ device.setEnrolmentInfo(loadEnrolmentBilling(rs));
return device;
}
- public static DeviceBilling loadDeviceBilling(ResultSet rs) throws SQLException {
- DeviceBilling device = new DeviceBilling();
- device.setId(rs.getInt("ID"));
- device.setName(rs.getString("DEVICE_NAME"));
- device.setDescription(rs.getString("DESCRIPTION"));
+ public static Device loadDeviceIds(ResultSet rs) throws SQLException {
+ Device device = new Device();
+ device.setId(rs.getInt("DEVICE_ID"));
device.setDeviceIdentifier(rs.getString("DEVICE_IDENTIFICATION"));
- device.setDaysUsed((int) rs.getLong("DAYS_SINCE_ENROLLED"));
- device.setEnrolmentInfo(loadEnrolmentBilling(rs));
+ device.setEnrolmentInfo(loadEnrolmentStatus(rs));
return device;
-// if (removedDevices) {
-// device.setDaysUsed((int) rs.getLong("DAYS_USED"));
-// } else {
-// device.setDaysSinceEnrolled((int) rs.getLong("DAYS_SINCE_ENROLLED"));
-// }
-
}
public static DeviceMonitoringData loadDevice(ResultSet rs, String deviceTypeName) throws SQLException {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
index 585074894df..f17719d228d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/device/details/mgt/impl/DeviceInformationManagerImpl.java
@@ -382,25 +382,11 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
deviceLocation.getBearing(),
deviceLocation.getDistance()
};
-// DeviceManagerUtil.getEventPublisherService().publishEvent(
-// LOCATION_EVENT_STREAM_DEFINITION, "1.0.0", metaData, new Object[0], payload
-// );
}
//Tracker update GPS Location
if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) {
- try {
- DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
- .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId());
- } catch (ExecutionException e) {
- log.error("ExecutionException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- } catch (InterruptedException e) {
- log.error("InterruptedException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- }
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateLocation(device, deviceLocation);
} else {
if(!HttpReportingUtil.isLocationPublishing()) {
if (log.isDebugEnabled()) {
@@ -409,12 +395,10 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
}
if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) {
- log.info("Traccar is disabled");
+ log.debug("Traccar is disabled");
}
}
}
- //Tracker update GPS Location
-
DeviceManagementDAOFactory.commitTransaction();
} catch (TransactionManagementException e) {
throw new DeviceDetailsMgtException("Transactional error occurred while adding the device location " +
@@ -453,18 +437,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
for (DeviceLocation deviceLocation: deviceLocations) {
//Tracker update GPS Location
if (HttpReportingUtil.isLocationPublishing() && HttpReportingUtil.isTrackerEnabled()) {
- try {
- DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
- .updateLocation(device, deviceLocation, CarbonContext.getThreadLocalCarbonContext().getTenantId());
- } catch (ExecutionException e) {
- log.error("ExecutionException : " + e);
- //throw new RuntimeException(e);
- // NOTE: Exception was not thrown due to being conflicted with non-traccar features
- } catch (InterruptedException e) {
- log.error("InterruptedException : " + e);
- //throw new RuntimeException(e);
- // NOTE: Exception was not thrown due to being conflicted with non-traccar features
- }
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateLocation(device, deviceLocation);
} else {
if(!HttpReportingUtil.isLocationPublishing()) {
if (log.isDebugEnabled()) {
@@ -473,7 +446,7 @@ public class DeviceInformationManagerImpl implements DeviceInformationManager {
}
if (!HttpReportingUtil.isTrackerEnabled()) {
if (log.isDebugEnabled()) {
- log.info("Traccar is disabled");
+ log.debug("Traccar is disabled");
}
}
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
index 6a69cb02ba5..08cfdff5911 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementDataHolder.java
@@ -19,6 +19,7 @@
package org.wso2.carbon.device.mgt.core.internal;
import io.entgra.server.bootup.heartbeat.beacon.service.HeartBeatManagementService;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
@@ -26,14 +27,18 @@ import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorization
import org.wso2.carbon.device.mgt.common.event.config.EventConfigurationProviderService;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManager;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
import org.wso2.carbon.device.mgt.common.spi.DeviceTypeGeneratorService;
+import org.wso2.carbon.device.mgt.common.spi.TraccarManagementService;
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
import org.wso2.carbon.device.mgt.core.dto.DeviceTypeServiceIdentifier;
import org.wso2.carbon.device.mgt.core.geo.task.GeoFenceEventOperationManager;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.operation.timeout.task.OperationTimeoutTaskManagerService;
import org.wso2.carbon.device.mgt.core.privacy.PrivacyComplianceProvider;
import org.wso2.carbon.device.mgt.core.push.notification.mgt.PushNotificationProviderRepository;
@@ -69,7 +74,7 @@ public class DeviceManagementDataHolder {
private AppManagementConfig appManagerConfig;
private OperationManager operationManager;
private ConfigurationContextService configurationContextService;
- private final HashMap requireDeviceAuthorization = new HashMap<>();
+ private final HashMap requireDeviceAuthorization = new HashMap<>();
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
private GroupManagementProviderService groupManagementProviderService;
private TaskService taskService;
@@ -85,17 +90,21 @@ public class DeviceManagementDataHolder {
private ExecutorService eventConfigExecutors;
private OperationTimeoutTaskManagerService operationTimeoutTaskManagerService;
private DeviceAPIClientService deviceAPIClientService;
+ private MetadataManagementService metadataManagementService;
+ private WhiteLabelManagementService whiteLabelManagementService;
+ private TraccarManagementService traccarManagementService;
private final Map deviceStatusTaskPluginConfigs = Collections.synchronizedMap(
new HashMap<>());
private final Map map = new HashMap<>();
- public Map getMap(){
+ public Map getMap() {
return this.map;
}
- private DeviceManagementDataHolder() {}
+ private DeviceManagementDataHolder() {
+ }
public static DeviceManagementDataHolder getInstance() {
return thisInstance;
@@ -204,7 +213,7 @@ public class DeviceManagementDataHolder {
}
public void setRequireDeviceAuthorization(String pluginType, boolean requireAuthentication) {
- requireDeviceAuthorization.put(pluginType,requireAuthentication);
+ requireDeviceAuthorization.put(pluginType, requireAuthentication);
}
public boolean requireDeviceAuthorization(String pluginType) {
@@ -359,4 +368,36 @@ public class DeviceManagementDataHolder {
public void setDeviceAPIClientService(DeviceAPIClientService deviceAPIClientService) {
this.deviceAPIClientService = deviceAPIClientService;
}
+
+ public MetadataManagementService getMetadataManagementService() {
+ return metadataManagementService;
+ }
+
+ public void setMetadataManagementService(MetadataManagementService metadataManagementService) {
+ this.metadataManagementService = metadataManagementService;
+ }
+
+ public WhiteLabelManagementService getWhiteLabelManagementService() {
+ return whiteLabelManagementService;
+ }
+
+ public void setWhiteLabelManagementService(WhiteLabelManagementService whiteLabelManagementService) {
+ this.whiteLabelManagementService = whiteLabelManagementService;
+ }
+
+ public TraccarManagementService getTraccarManagementService() {
+ TraccarManagementService traccarManagementService;
+ PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
+ traccarManagementService = (TraccarManagementService) ctx.getOSGiService(
+ TraccarManagementService.class, null);
+ if (traccarManagementService == null) {
+ String msg = "Traccar management service not initialized.";
+ throw new IllegalStateException(msg);
+ }
+ return traccarManagementService;
+ }
+
+ public void setTraccarManagementService(TraccarManagementService traccarManagementService) {
+ this.traccarManagementService = traccarManagementService;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
index a266a40499d..f36def494d7 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/internal/DeviceManagementServiceComponent.java
@@ -22,6 +22,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@@ -31,6 +32,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.geo.service.GeoLocationProviderService;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.metadata.mgt.MetadataManagementService;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelManagementService;
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementService;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
@@ -59,6 +61,7 @@ import org.wso2.carbon.device.mgt.core.device.details.mgt.impl.DeviceInformation
import org.wso2.carbon.device.mgt.core.event.config.EventConfigurationProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.geo.service.GeoLocationProviderServiceImpl;
import org.wso2.carbon.device.mgt.core.metadata.mgt.MetadataManagementServiceImpl;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.WhiteLabelManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.notification.mgt.NotificationManagementServiceImpl;
import org.wso2.carbon.device.mgt.core.notification.mgt.dao.NotificationManagementDAOFactory;
@@ -293,6 +296,8 @@ public class DeviceManagementServiceComponent {
if (log.isDebugEnabled()) {
log.debug("Registering OSGi service DeviceManagementProviderServiceImpl");
}
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+
/* Registering Tenants Observer */
BundleContext bundleContext = componentContext.getBundleContext();
TenantCreateObserver listener = new TenantCreateObserver();
@@ -358,8 +363,20 @@ public class DeviceManagementServiceComponent {
/* Registering Metadata Service */
MetadataManagementService metadataManagementService = new MetadataManagementServiceImpl();
+ DeviceManagementDataHolder.getInstance().setMetadataManagementService(metadataManagementService);
bundleContext.registerService(MetadataManagementService.class.getName(), metadataManagementService, null);
+ /* Registering Whitelabel Service */
+ WhiteLabelManagementService whiteLabelManagementService = new WhiteLabelManagementServiceImpl();
+ DeviceManagementDataHolder.getInstance().setWhiteLabelManagementService(whiteLabelManagementService);
+ try {
+ whiteLabelManagementService.addDefaultWhiteLabelThemeIfNotExist(tenantId);
+ } catch (Throwable e) {
+ log.error("Error occurred while adding default tenant white label theme", e);
+
+ }
+ bundleContext.registerService(WhiteLabelManagementService.class.getName(), whiteLabelManagementService, null);
+
/* Registering Event Configuration Service */
EventConfigurationProviderService eventConfigurationService = new EventConfigurationProviderServiceImpl();
DeviceManagementDataHolder.getInstance().setEventConfigurationProviderService(eventConfigurationService);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java
index 7d7fd1d7c01..5ba88883017 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/MetadataManagementServiceImpl.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.metadata.mgt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
@@ -33,7 +34,6 @@ import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
-
import java.sql.SQLException;
import java.util.List;
@@ -44,7 +44,7 @@ public class MetadataManagementServiceImpl implements MetadataManagementService
private static final Log log = LogFactory.getLog(MetadataManagementServiceImpl.class);
- private MetadataDAO metadataDAO;
+ private final MetadataDAO metadataDAO;
public MetadataManagementServiceImpl() {
this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
@@ -91,8 +91,14 @@ public class MetadataManagementServiceImpl implements MetadataManagementService
}
try {
MetadataManagementDAOFactory.openConnection();
- return metadataDAO.getMetadata(
- PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true), metaKey);
+ int tenantId;
+ if (metaKey.equals("EVALUATE_TENANTS")){
+ // for getting evaluate tenant list to provide the live chat feature
+ tenantId = MultitenantConstants.SUPER_TENANT_ID;
+ } else {
+ tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ }
+ return metadataDAO.getMetadata(tenantId, metaKey);
} catch (MetadataManagementDAOException e) {
String msg = "Error occurred while retrieving the metadata entry for metaKey:" + metaKey;
log.error(msg, e);
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java
new file mode 100644
index 00000000000..ec2bca767e0
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/WhiteLabelManagementServiceImpl.java
@@ -0,0 +1,458 @@
+/*
+ * Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.metadata.mgt;
+
+import com.google.gson.Gson;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.wso2.carbon.context.CarbonContext;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.Base64File;
+import org.wso2.carbon.device.mgt.common.FileResponse;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
+import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelImage;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelImageRequestPayload;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelManagementService;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelTheme;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelThemeCreateRequest;
+import org.wso2.carbon.device.mgt.core.common.util.HttpUtil;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration;
+import org.wso2.carbon.device.mgt.core.config.metadata.mgt.whitelabel.WhiteLabelConfiguration;
+import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.util.MetadataConstants;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.util.WhiteLabelStorageUtil;
+import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.SQLException;
+
+/**
+ * This class implements the MetadataManagementService.
+ */
+public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementService {
+
+ private static final Log log = LogFactory.getLog(WhiteLabelManagementServiceImpl.class);
+
+ private final MetadataDAO metadataDAO;
+
+ public WhiteLabelManagementServiceImpl() {
+ this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
+ }
+
+ @Override
+ public FileResponse getWhiteLabelFavicon(String tenantDomain) throws MetadataManagementException, NotFoundException {
+ try {
+ WhiteLabelTheme whiteLabelTheme = getWhiteLabelTheme(tenantDomain);
+ return getImageFileResponse(whiteLabelTheme.getFaviconImage(), WhiteLabelImage.ImageName.FAVICON, tenantDomain);
+ } catch (IOException e) {
+ String msg = "Error occurred while getting byte content of favicon";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while getting tenant details of favicon";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+ @Override
+ public FileResponse getWhiteLabelLogo(String tenantDomain) throws MetadataManagementException, NotFoundException {
+ try {
+ WhiteLabelTheme whiteLabelTheme = getWhiteLabelTheme(tenantDomain);
+ return getImageFileResponse(whiteLabelTheme.getLogoImage(), WhiteLabelImage.ImageName.LOGO, tenantDomain);
+ } catch (IOException e) {
+ String msg = "Error occurred while getting byte content of logo";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while getting tenant details of logo";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+ @Override
+ public FileResponse getWhiteLabelLogoIcon(String tenantDomain) throws MetadataManagementException, NotFoundException {
+ try {
+ WhiteLabelTheme whiteLabelTheme = getWhiteLabelTheme(tenantDomain);
+ return getImageFileResponse(whiteLabelTheme.getLogoIconImage(), WhiteLabelImage.ImageName.LOGO_ICON, tenantDomain);
+ } catch (IOException e) {
+ String msg = "Error occurred while getting byte content of logo";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while getting tenant details of icon";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+ /**
+ * Useful to get white label image file response for provided {@link WhiteLabelImage.ImageName}
+ */
+ private FileResponse getImageFileResponse(WhiteLabelImage image, WhiteLabelImage.ImageName imageName, String tenantDomain) throws
+ IOException, MetadataManagementException, NotFoundException, DeviceManagementException {
+ if (image.getImageLocationType() == WhiteLabelImage.ImageLocationType.URL) {
+ return getImageFileResponseFromUrl(image.getImageLocation());
+ }
+ return WhiteLabelStorageUtil.getWhiteLabelImageStream(image, imageName, tenantDomain);
+ }
+
+ /**
+ * Useful to get white label image file response from provided url
+ */
+ private FileResponse getImageFileResponseFromUrl(String url) throws IOException, NotFoundException {
+ FileResponse fileResponse = new FileResponse();
+ try(CloseableHttpClient client = HttpClients.createDefault()) {
+ HttpGet imageGetRequest = new HttpGet(url);
+ HttpResponse response = client.execute(imageGetRequest);
+ InputStream imageStream = response.getEntity().getContent();
+ if (imageStream == null) {
+ String msg = "Failed to retrieve the image from url: " + url;
+ log.error(msg);
+ throw new NotFoundException(msg);
+ }
+ byte[] fileContent = IOUtils.toByteArray(imageStream);
+ fileResponse.setFileContent(fileContent);
+ String mimeType = HttpUtil.getContentType(response);
+ fileResponse.setMimeType(mimeType);
+ return fileResponse;
+ }
+ }
+
+
+ @Override
+ public void addDefaultWhiteLabelThemeIfNotExist(int tenantId) throws MetadataManagementException {
+ try {
+ MetadataManagementDAOFactory.beginTransaction();
+ if (!metadataDAO.isExist(tenantId, MetadataConstants.WHITELABEL_META_KEY)) {
+ WhiteLabelTheme whiteLabelTheme = getDefaultWhiteLabelTheme();
+ Metadata metadata = constructWhiteLabelThemeMetadata(whiteLabelTheme);
+ metadataDAO.addMetadata(tenantId, metadata);
+ if (log.isDebugEnabled()) {
+ log.debug("White label metadata entry has inserted successfully");
+ }
+ }
+ MetadataManagementDAOFactory.commitTransaction();
+ } catch (MetadataManagementDAOException e) {
+ MetadataManagementDAOFactory.rollbackTransaction();
+ String msg = "Error occurred while inserting default whitelabel metadata entry.";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (TransactionManagementException e) {
+ String msg = "Error occurred while opening a connection to the data source";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } finally {
+ MetadataManagementDAOFactory.closeConnection();
+ }
+
+ }
+
+ @Override
+ public void resetToDefaultWhiteLabelTheme() throws MetadataManagementException {
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ WhiteLabelTheme whiteLabelTheme = getDefaultWhiteLabelTheme();
+ Metadata metadata = constructWhiteLabelThemeMetadata(whiteLabelTheme);
+ DeviceManagementDataHolder.getInstance().getMetadataManagementService().updateMetadata(metadata);
+ WhiteLabelStorageUtil.deleteWhiteLabelImageForTenantIfExists(tenantId);
+ }
+
+ /**
+ * Construct and return default whitelabel detail bean {@link WhiteLabelImage}
+ */
+ private WhiteLabelTheme getDefaultWhiteLabelTheme() {
+ String footerText = getDefaultFooterText();
+ String appTitle = getDefaultAppTitle();
+ WhiteLabelImage favicon = constructDefaultFaviconImage();
+ WhiteLabelImage logo = constructDefaultLogoImage();
+ WhiteLabelImage logoIcon = constructDefaultLogoIconImage();
+ WhiteLabelTheme defaultTheme = new WhiteLabelTheme();
+ defaultTheme.setFooterText(footerText);
+ defaultTheme.setAppTitle(appTitle);
+ defaultTheme.setLogoImage(logo);
+ defaultTheme.setLogoIconImage(logoIcon);
+ defaultTheme.setFaviconImage(favicon);
+ return defaultTheme;
+ }
+
+ /**
+ * Get default whitelabel label page title from config
+ */
+ private String getDefaultAppTitle() {
+ MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig().getMetaDataConfiguration();
+ WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
+ return whiteLabelConfiguration.getAppTitle();
+ }
+
+ /**
+ * Get default whitelabel label footer from config
+ */
+ private String getDefaultFooterText() {
+ MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig().getMetaDataConfiguration();
+ WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
+ return whiteLabelConfiguration.getFooterText();
+ }
+
+ /**
+ * This is useful to construct and get the default favicon whitelabel image
+ *
+ * @return {@link WhiteLabelImage}
+ */
+ private WhiteLabelImage constructDefaultFaviconImage() {
+ MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig().getMetaDataConfiguration();
+ WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
+ WhiteLabelImage favicon = new WhiteLabelImage();
+ favicon.setImageLocation(whiteLabelConfiguration.getWhiteLabelImages().getDefaultFaviconName());
+ setDefaultWhiteLabelImageCommonProperties(favicon);
+ return favicon;
+ }
+
+ /**
+ * This is useful to construct and get the default logo whitelabel image
+ *
+ * @return {@link WhiteLabelImage}
+ */
+ private WhiteLabelImage constructDefaultLogoImage() {
+ MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig().getMetaDataConfiguration();
+ WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
+ WhiteLabelImage logo = new WhiteLabelImage();
+ logo.setImageLocation(whiteLabelConfiguration.getWhiteLabelImages().getDefaultLogoName());
+ setDefaultWhiteLabelImageCommonProperties(logo);
+ return logo;
+ }
+
+ /**
+ * This is useful to construct and get the default logo whitelabel image
+ *
+ * @return {@link WhiteLabelImage}
+ */
+ private WhiteLabelImage constructDefaultLogoIconImage() {
+ MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
+ getDeviceManagementConfig().getMetaDataConfiguration();
+ WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
+ WhiteLabelImage logoIcon = new WhiteLabelImage();
+ logoIcon.setImageLocation(whiteLabelConfiguration.getWhiteLabelImages().getDefaultLogoIconName());
+ setDefaultWhiteLabelImageCommonProperties(logoIcon);
+ return logoIcon;
+ }
+
+ /**
+ * This is useful to set common properties such as DEFAULT_FILE type for {@link WhiteLabelImage.ImageLocationType}
+ * for default white label image bean{@link WhiteLabelImage}
+ */
+ private void setDefaultWhiteLabelImageCommonProperties(WhiteLabelImage image) {
+ image.setImageLocationType(WhiteLabelImage.ImageLocationType.DEFAULT_FILE);
+ }
+
+ @Override
+ public WhiteLabelTheme updateWhiteLabelTheme(WhiteLabelThemeCreateRequest createWhiteLabelTheme)
+ throws MetadataManagementException {
+ if (log.isDebugEnabled()) {
+ log.debug("Creating Metadata : [" + createWhiteLabelTheme.toString() + "]");
+ }
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
+ String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true);
+ File existingFaviconImage = null;
+ File existingLogoImage = null;
+ File existingLogoIconImage = null;
+ try {
+ WhiteLabelTheme theme = getWhiteLabelTheme(tenantDomain);
+ if (theme.getFaviconImage().getImageLocationType() == WhiteLabelImage.ImageLocationType.CUSTOM_FILE) {
+ existingFaviconImage = WhiteLabelStorageUtil.getWhiteLabelImageFile(theme.getFaviconImage(), WhiteLabelImage.ImageName.FAVICON, tenantDomain);
+ }
+ if (theme.getLogoImage().getImageLocationType() == WhiteLabelImage.ImageLocationType.CUSTOM_FILE) {
+ existingLogoImage = WhiteLabelStorageUtil.getWhiteLabelImageFile(theme.getLogoImage(), WhiteLabelImage.ImageName.LOGO, tenantDomain);
+ }
+ if (theme.getLogoIconImage().getImageLocationType() == WhiteLabelImage.ImageLocationType.CUSTOM_FILE) {
+ existingLogoIconImage = WhiteLabelStorageUtil.getWhiteLabelImageFile(theme.getLogoIconImage(), WhiteLabelImage.ImageName.LOGO_ICON, tenantDomain);
+ }
+ storeWhiteLabelImageIfRequired(createWhiteLabelTheme.getFavicon(), WhiteLabelImage.ImageName.FAVICON, tenantId);
+ storeWhiteLabelImageIfRequired(createWhiteLabelTheme.getLogo(), WhiteLabelImage.ImageName.LOGO, tenantId);
+ storeWhiteLabelImageIfRequired(createWhiteLabelTheme.getLogoIcon(), WhiteLabelImage.ImageName.LOGO_ICON, tenantId);
+ WhiteLabelTheme whiteLabelTheme = constructWhiteLabelTheme(createWhiteLabelTheme);
+ Metadata metadataWhiteLabelTheme = constructWhiteLabelThemeMetadata(whiteLabelTheme);
+ try {
+ MetadataManagementDAOFactory.beginTransaction();
+ metadataDAO.updateMetadata(tenantId, metadataWhiteLabelTheme);
+ MetadataManagementDAOFactory.commitTransaction();
+ if (log.isDebugEnabled()) {
+ log.debug("Metadata entry created successfully. " + createWhiteLabelTheme);
+ }
+ return whiteLabelTheme;
+ } catch (MetadataManagementDAOException e) {
+ MetadataManagementDAOFactory.rollbackTransaction();
+ restoreWhiteLabelImages(existingFaviconImage, existingLogoImage, existingLogoIconImage, tenantId);
+ String msg = "Error occurred while creating the metadata entry. " + createWhiteLabelTheme;
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (TransactionManagementException e) {
+ restoreWhiteLabelImages(existingFaviconImage, existingLogoImage, existingLogoIconImage, tenantId);
+ String msg = "Error occurred while opening a connection to the data source";
+ log.error(msg, e);
+ throw new MetadataManagementException("Error occurred while creating metadata record", e);
+ } finally {
+ MetadataManagementDAOFactory.closeConnection();
+ }
+ } catch (NotFoundException e) {
+ String msg = "Error occurred while retrieving existing white label theme";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while getting tenant details of white label";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+
+ }
+ }
+
+ /**
+ * This is method is useful to restore provided existing white label images (i.e: favicon/logo).
+ * For example if any exception occurred white updating/deleting white label, this method can be used to
+ * restore the existing images in any case. Note that the existing images should be first loaded so that
+ * those can be passed to this method in order to restore.
+ *
+ * @param existingFavicon existing favicon image file
+ * @param existingLogo existing logo image file
+ */
+ private void restoreWhiteLabelImages(File existingFavicon, File existingLogo, File existingLogoIcon, int tenantId)
+ throws MetadataManagementException {
+ WhiteLabelStorageUtil.deleteWhiteLabelImageForTenantIfExists(tenantId);
+ if (existingFavicon != null) {
+ WhiteLabelStorageUtil.storeWhiteLabelImage(existingFavicon, WhiteLabelImage.ImageName.FAVICON, tenantId);
+ }
+ if (existingLogo != null) {
+ WhiteLabelStorageUtil.storeWhiteLabelImage(existingLogo, WhiteLabelImage.ImageName.LOGO, tenantId);
+ }
+ if (existingLogoIcon != null) {
+ WhiteLabelStorageUtil.storeWhiteLabelImage(existingLogoIcon, WhiteLabelImage.ImageName.LOGO_ICON, tenantId);
+ }
+ }
+
+ /**
+ * This handles storing provided white label image if required.
+ * For example if the provided white label image is of URL type it doesn't need to be stored
+ *
+ * @param whiteLabelImage image to be stored
+ * @param imageName (i.e: FAVICON)
+ */
+ private void storeWhiteLabelImageIfRequired(WhiteLabelImageRequestPayload whiteLabelImage,
+ WhiteLabelImage.ImageName imageName, int tenantId)
+ throws MetadataManagementException {
+ if (whiteLabelImage.getImageType() == WhiteLabelImageRequestPayload.ImageType.BASE64) {
+ Base64File imageBase64 = new Gson().fromJson(whiteLabelImage.getImage(), Base64File.class);
+ WhiteLabelStorageUtil.updateWhiteLabelImage(imageBase64, imageName, tenantId);
+ }
+ }
+
+ /**
+ * Generate {@link WhiteLabelTheme} from provided {@link WhiteLabelThemeCreateRequest}
+ */
+ private WhiteLabelTheme constructWhiteLabelTheme(WhiteLabelThemeCreateRequest whiteLabelThemeCreateRequest) {
+ WhiteLabelTheme whiteLabelTheme = new WhiteLabelTheme();
+ WhiteLabelImageRequestPayload faviconPayload = whiteLabelThemeCreateRequest.getFavicon();
+ WhiteLabelImageRequestPayload logoPayload = whiteLabelThemeCreateRequest.getLogo();
+ WhiteLabelImageRequestPayload logoIconPayload = whiteLabelThemeCreateRequest.getLogoIcon();
+ WhiteLabelImage faviconImage = constructWhiteLabelImageDTO(faviconPayload);
+ WhiteLabelImage logoImage = constructWhiteLabelImageDTO(logoPayload);
+ WhiteLabelImage logoIconImage = constructWhiteLabelImageDTO(logoIconPayload);
+ whiteLabelTheme.setFaviconImage(faviconImage);
+ whiteLabelTheme.setLogoImage(logoImage);
+ whiteLabelTheme.setLogoIconImage(logoIconImage);
+ whiteLabelTheme.setFooterText(whiteLabelThemeCreateRequest.getFooterText());
+ whiteLabelTheme.setAppTitle(whiteLabelThemeCreateRequest.getAppTitle());
+ return whiteLabelTheme;
+ }
+
+ /**
+ * Generate {@link WhiteLabelImage} from provided {@link WhiteLabelImageRequestPayload}
+ */
+ private WhiteLabelImage constructWhiteLabelImageDTO(WhiteLabelImageRequestPayload image) {
+ WhiteLabelImage imageResponse = new WhiteLabelImage();
+ WhiteLabelImage.ImageLocationType imageLocationType = image.getImageType().getDTOImageLocationType();
+ imageResponse.setImageLocationType(imageLocationType);
+ String imageLocation;
+ if (image.getImageType() == WhiteLabelImageRequestPayload.ImageType.BASE64) {
+ Base64File imageBase64 = image.getImageAsBase64File();
+ imageLocation = imageBase64.getName();
+ } else {
+ imageLocation = image.getImageAsUrl();
+ }
+ imageResponse.setImageLocation(imageLocation);
+ return imageResponse;
+ }
+
+ /**
+ * Generate {@link Metadata} from provided {@link WhiteLabelImage}
+ */
+ private Metadata constructWhiteLabelThemeMetadata(WhiteLabelTheme whiteLabelTheme) {
+ String whiteLabelThemeJsonString = new Gson().toJson(whiteLabelTheme);
+ Metadata metadata = new Metadata();
+ metadata.setMetaKey(MetadataConstants.WHITELABEL_META_KEY);
+ metadata.setMetaValue(whiteLabelThemeJsonString);
+ return metadata;
+ }
+
+ @Override
+ public WhiteLabelTheme getWhiteLabelTheme(String tenantDomain) throws MetadataManagementException, NotFoundException, DeviceManagementException {
+ int tenantId = DeviceManagerUtil.getTenantId(tenantDomain);
+ if (log.isDebugEnabled()) {
+ log.debug("Retrieving whitelabel theme for tenant: " + tenantId);
+ }
+ try {
+ MetadataManagementDAOFactory.openConnection();
+ Metadata metadata = metadataDAO.getMetadata(tenantId, MetadataConstants.WHITELABEL_META_KEY);
+ if (metadata == null) {
+ String msg = "Whitelabel theme not found for tenant: " + tenantId;
+ log.error(msg);
+ throw new NotFoundException(msg);
+ }
+ return new Gson().fromJson(metadata.getMetaValue(), WhiteLabelTheme.class);
+ } catch (MetadataManagementDAOException e) {
+ String msg = "Error occurred while retrieving white label theme for tenant:" + tenantId;
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } finally {
+ MetadataManagementDAOFactory.closeConnection();
+ }
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/dao/util/MetadataConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/dao/util/MetadataConstants.java
new file mode 100644
index 00000000000..e16f466c6e3
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/dao/util/MetadataConstants.java
@@ -0,0 +1,22 @@
+/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.metadata.mgt.dao.util;
+
+public class MetadataConstants {
+ public static final String WHITELABEL_META_KEY = "whitelabel";
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java
new file mode 100644
index 00000000000..fc71a89e5e9
--- /dev/null
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/metadata/mgt/util/WhiteLabelStorageUtil.java
@@ -0,0 +1,222 @@
+/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
+ *
+ * Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.wso2.carbon.device.mgt.core.metadata.mgt.util;
+
+import org.apache.commons.io.IOUtils;
+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.Base64File;
+import org.wso2.carbon.device.mgt.common.FileResponse;
+import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.MetadataManagementException;
+import org.wso2.carbon.device.mgt.common.exceptions.NotFoundException;
+import org.wso2.carbon.device.mgt.common.metadata.mgt.WhiteLabelImage;
+import org.wso2.carbon.device.mgt.core.common.exception.StorageManagementException;
+import org.wso2.carbon.device.mgt.core.common.util.FileUtil;
+import org.wso2.carbon.device.mgt.core.common.util.StorageManagementUtil;
+import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
+import org.wso2.carbon.device.mgt.core.config.metadata.mgt.MetaDataConfiguration;
+import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * This class contains the default concrete implementation of ApplicationStorage Management.
+ */
+public class WhiteLabelStorageUtil {
+ private static final Log log = LogFactory.getLog(WhiteLabelStorageUtil.class);
+ private static final MetaDataConfiguration metadataConfig;
+ private static final String STORAGE_PATH;
+
+ static {
+ metadataConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig().getMetaDataConfiguration();
+ if (metadataConfig == null) {
+ throw new RuntimeException("Meta configuration is not found in cdm-config.xml");
+ }
+ STORAGE_PATH = metadataConfig.getWhiteLabelConfiguration().getWhiteLabelImages().getStoragePath();
+ }
+
+ /**
+ * Store provided white label {@link Base64File} image
+ *
+ * @param image base64 image file
+ * @param imageName {@link WhiteLabelImage.ImageName} (i.e FAVICON)
+ */
+ public static void storeWhiteLabelImage(Base64File image, WhiteLabelImage.ImageName imageName, int tenantId)
+ throws MetadataManagementException {
+ String storedLocation;
+ try {
+ String imageStoringBaseDirPath = STORAGE_PATH + File.separator + tenantId;
+ StorageManagementUtil.createArtifactDirectory(imageStoringBaseDirPath);
+ String storingDir = imageStoringBaseDirPath + File.separator + imageName;
+ StorageManagementUtil.createArtifactDirectory(storingDir);
+ storedLocation = storingDir + File.separator + image.getName();
+ StorageManagementUtil.saveFile(image, storedLocation);
+ } catch (IOException e) {
+ String msg = "IO Exception occurred while saving whitelabel artifacts for the tenant " + tenantId;
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ } catch (StorageManagementException e) {
+ String msg = "Error occurred while uploading white label image artifacts";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+ /**
+ * Store provided white label {@link File} image
+ *
+ * @param image white label file
+ * @param imageName {@link WhiteLabelImage.ImageName} (i.e FAVICON)
+ */
+ public static void storeWhiteLabelImage(File image, WhiteLabelImage.ImageName imageName, int tenantId) throws
+ MetadataManagementException {
+ try {
+ storeWhiteLabelImage(FileUtil.fileToBase64File(image), imageName, tenantId);
+ } catch (IOException e) {
+ String msg = "Error occurred when converting provided File object to Base64File class";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+
+ /**
+ * Update white label image for provided tenant
+ *
+ * @param image {@link Base64File} white label file
+ * @param imageName (i.e: FAVICON)
+ */
+ public static void updateWhiteLabelImage(Base64File image, WhiteLabelImage.ImageName imageName, int tenantId)
+ throws MetadataManagementException {
+ deleteWhiteLabelImageIfExists(imageName, tenantId);
+ storeWhiteLabelImage(image, imageName, tenantId);
+ }
+
+ /**
+ * Use to get a given {@link WhiteLabelImage.ImageName (i.e: LOGO)} white label image File
+ *
+ * @param image detail bean
+ * @param imageName (i.e: LOGO)
+ * @return white label image file {@link File}
+ */
+ public static File getWhiteLabelImageFile(WhiteLabelImage image, WhiteLabelImage.ImageName imageName, String tenantDomain)
+ throws MetadataManagementException, DeviceManagementException {
+ String fullPathToImage = getPathToImage(image, imageName, tenantDomain);
+ return new File(fullPathToImage);
+ }
+
+ /**
+ * Useful to get the given {@link WhiteLabelImage.ImageName (i.e: LOGO)} white label image InputStream
+ *
+ * @param image - white label image detail bean
+ * @param imageName (i.e: LOGO)
+ * @return white label image input stream
+ */
+ public static FileResponse getWhiteLabelImageStream(WhiteLabelImage image, WhiteLabelImage.ImageName imageName, String tenantDomain)
+ throws MetadataManagementException, NotFoundException, DeviceManagementException {
+ FileResponse fileResponse = new FileResponse();
+ String fullPathToFile = getPathToImage(image, imageName, tenantDomain);
+ try {
+ InputStream imageStream = StorageManagementUtil.getInputStream(fullPathToFile);
+ if (imageStream == null) {
+ String msg = "Failed to get the " + imageName + " image with the file name: " + fullPathToFile;
+ log.error(msg);
+ throw new NotFoundException(msg);
+ }
+ byte[] fileContent = IOUtils.toByteArray(imageStream);
+ String fileExtension = FileUtil.extractFileExtensionFromFilePath(image.getImageLocation());
+ String mimeType = FileResponse.ImageExtension.mimeTypeOf(fileExtension);
+ fileResponse.setMimeType(mimeType);
+ fileResponse.setFileContent(fileContent);
+ return fileResponse;
+ } catch (IOException e) {
+ String msg = "Error occurred when accessing the file in file path: " + fullPathToFile;
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+
+ /**
+ * Construct the path to white label image in the file system and return
+ *
+ * @param image - white label image detail bean
+ * @param imageName (i.e: LOGO)
+ * @return Full path to white label image in the system
+ */
+ private static String getPathToImage(WhiteLabelImage image, WhiteLabelImage.ImageName imageName, String tenantDomain)
+ throws MetadataManagementException, DeviceManagementException {
+ WhiteLabelImage.ImageLocationType imageLocationType = image.getImageLocationType();
+ if (imageLocationType == WhiteLabelImage.ImageLocationType.URL) {
+ String msg = "White label images of URL type is not stored, hence it doesn't have a path in file system.";
+ log.error(msg);
+ throw new MetadataManagementException(msg);
+ }
+ int tenantId = 0;
+ try {
+ tenantId = DeviceManagerUtil.getTenantId(tenantDomain);
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred while getting tenant details of logo";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ }
+ String fileName = image.getImageLocation();
+ String filePath = String.valueOf(tenantId);
+ if (imageLocationType == WhiteLabelImage.ImageLocationType.DEFAULT_FILE) {
+ filePath = metadataConfig.getWhiteLabelConfiguration().getWhiteLabelImages().getDefaultImagesLocation();
+ }
+ return STORAGE_PATH + File.separator + filePath + File.separator + imageName + File.separator + fileName;
+ }
+
+ /***
+ * This method is responsible to delete provided white label image file which if exist
+ */
+ public static void deleteWhiteLabelImageIfExists(WhiteLabelImage.ImageName imageName, int tenantId) throws MetadataManagementException {
+ String artifactPath = STORAGE_PATH + File.separator + tenantId + File.separator + imageName;
+ File artifact = new File(artifactPath);
+ if (artifact.exists()) {
+ try {
+ StorageManagementUtil.delete(artifact);
+ } catch (IOException e) {
+ String msg = "Error occurred while deleting whitelabel artifacts";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+ }
+
+ /***
+ * This method is responsible to delete all white label images for provided tenant
+ */
+ public static void deleteWhiteLabelImageForTenantIfExists(int tenantId) throws MetadataManagementException {
+ String artifactPath = STORAGE_PATH + File.separator + tenantId;
+ File artifact = new File(artifactPath);
+ if (artifact.exists()) {
+ try {
+ StorageManagementUtil.delete(artifact);
+ } catch (IOException e) {
+ String msg = "Error occurred while deleting whitelabel artifacts";
+ log.error(msg, e);
+ throw new MetadataManagementException(msg, e);
+ }
+ }
+ }
+}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
index 3371f8d8048..4770f9fee49 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/notification/mgt/NotificationManagementServiceImpl.java
@@ -18,8 +18,9 @@
package org.wso2.carbon.device.mgt.core.notification.mgt;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
+import io.entgra.notification.logger.DeviceLogContext;
+import io.entgra.notification.logger.impl.EntgraDeviceLoggerImpl;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
@@ -45,8 +46,8 @@ import java.util.List;
*/
public class NotificationManagementServiceImpl implements NotificationManagementService {
- private static final Log log = LogFactory.getLog(NotificationManagementServiceImpl.class);
-
+ private static final EntgraLogger log = new EntgraDeviceLoggerImpl(NotificationManagementServiceImpl.class);
+ DeviceLogContext.Builder deviceLogContexBuilder = new DeviceLogContext.Builder();
private NotificationDAO notificationDAO;
public NotificationManagementServiceImpl() {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
index 27882f4fbd3..55e9279760b 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/mgt/OperationManagerImpl.java
@@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.core.operation.mgt;
+import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -792,9 +793,7 @@ public class OperationManagerImpl implements OperationManager {
if (dtoOperation != null) {
long currentTime = Calendar.getInstance().getTime().getTime();
- log.info("Current timestamp:" + currentTime);
long updatedTime = Timestamp.valueOf(dtoOperation.getReceivedTimeStamp()).getTime();
- log.info("Updated timestamp: " + updatedTime);
// check if notnow frequency is met and set next pending operation if not, otherwise let notnow
// operation to proceed
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java
index 2ee7e320328..c1bd71a2a55 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/operation/timeout/task/impl/OperationTimeoutTask.java
@@ -32,31 +32,10 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask;
import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
public class OperationTimeoutTask extends DynamicPartitionedScheduleTask {
private static final Log log = LogFactory.getLog(OperationTimeoutTask.class);
- private OperationTimeout operationTimeoutConfig;
-
- @Override
- public void setProperties(Map properties) {
- super.setProperties(properties);
- String operationTimeoutTaskConfigStr = properties
- .get(OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG);
- Gson gson = new Gson();
- operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class);
- }
-
- @Override
- public String getProperty(String name) {
- return super.getProperty(name);
- }
-
- @Override
- public void refreshContext() {
- super.refreshContext();
- }
@Override
protected void setup() {
@@ -65,12 +44,15 @@ public class OperationTimeoutTask extends DynamicPartitionedScheduleTask {
@Override
protected void executeDynamicTask() {
+ String operationTimeoutTaskConfigStr = getProperty(
+ OperationTimeoutTaskManagerServiceImpl.OPERATION_TIMEOUT_TASK_CONFIG);
+ Gson gson = new Gson();
+ OperationTimeout operationTimeoutConfig = gson.fromJson(operationTimeoutTaskConfigStr, OperationTimeout.class);
try {
-
long timeMillis = System.currentTimeMillis() - operationTimeoutConfig.getTimeout() * 60 * 1000;
List deviceTypes = new ArrayList<>();
if (operationTimeoutConfig.getDeviceTypes().size() == 1 &&
- "ALL".equals(operationTimeoutConfig.getDeviceTypes().get( 0))) {
+ "ALL".equals(operationTimeoutConfig.getDeviceTypes().get(0))) {
try {
List deviceTypeList = DeviceManagementDataHolder.getInstance()
.getDeviceManagementProvider().getDeviceTypes();
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java
index 985fe76486c..1417dae501c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java
@@ -35,6 +35,7 @@ import org.wso2.carbon.device.mgt.common.invitation.mgt.DeviceEnrollmentType;
import org.wso2.carbon.device.mgt.common.metadata.mgt.Metadata;
import org.wso2.carbon.device.mgt.common.otp.mgt.OTPEmailTypes;
import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO;
+import org.wso2.carbon.device.mgt.common.otp.mgt.wrapper.DownloadURLDetails;
import org.wso2.carbon.device.mgt.common.spi.OTPManagementService;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@@ -109,6 +110,31 @@ public class OTPManagementServiceImpl implements OTPManagementService {
}
}
+ @Override
+ public void shareProductDownloadUrl(DownloadURLDetails downloadURLDetails) throws OTPManagementException {
+ if (StringUtils.isBlank(downloadURLDetails.getURL())) {
+ String msg = "Couldn't find the download URL with the request.";
+ log.error(msg);
+ throw new OTPManagementException(msg);
+ }
+ if (StringUtils.isBlank(downloadURLDetails.getFirstName())) {
+ String msg = "Couldn't find the First Name with the request.";
+ log.error(msg);
+ throw new OTPManagementException(msg);
+ }
+ if (StringUtils.isBlank(downloadURLDetails.getEmail())) {
+ String msg = "Couldn't find the e-mail address with the request.";
+ log.error(msg);
+ throw new OTPManagementException(msg);
+ }
+
+ Properties props = new Properties();
+ props.setProperty("first-name", downloadURLDetails.getFirstName());
+ props.setProperty("download-url", downloadURLDetails.getURL());
+ sendMail(props, downloadURLDetails.getEmail(),
+ DeviceManagementConstants.EmailAttributes.PRODUCT_DOWNLOAD_LINK_SHARING_TEMPLATE);
+ }
+
@Override
public OneTimePinDTO isValidOTP(String oneTimeToken) throws OTPManagementException, BadRequestException {
if (StringUtils.isBlank(oneTimeToken)){
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
index a84deb88944..3dedb8d5511 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderService.java
@@ -208,16 +208,6 @@ public interface DeviceManagementProviderService {
*/
PaginationResult getAllDevices(PaginationRequest request, boolean requireDeviceInfo) throws DeviceManagementException;
- /**
- * Method to retrieve all the devices with pagination support.
- *
- * @param request PaginationRequest object holding the data for pagination
- * @return PaginationResult - Result including the required parameters necessary to do pagination.
- * @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of
- * devices.
- */
- PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException;
-
/**
* Method to retrieve all the devices with pagination support.
*
@@ -225,9 +215,7 @@ public interface DeviceManagementProviderService {
* @throws DeviceManagementException If some unusual behaviour is observed while fetching billing of
* devices.
*/
- PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException;
-
-
+ PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException;
/**
* Method to retrieve all the devices with pagination support.
@@ -657,6 +645,8 @@ public interface DeviceManagementProviderService {
void sendEnrolmentInvitation(String templateName, EmailMetaInfo metaInfo) throws DeviceManagementException,
ConfigurationManagementException;
+ void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException;
+
void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException, ConfigurationManagementException;
FeatureManager getFeatureManager(String deviceType) throws DeviceTypeNotFoundException;
@@ -1042,4 +1032,6 @@ public interface DeviceManagementProviderService {
*/
PaginationResult getDevicesDetails(PaginationRequest request, List devicesIds, String groupName)
throws DeviceManagementException;
+
+ Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
index d6cf2d7fc34..d3363717ada 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/DeviceManagementProviderServiceImpl.java
@@ -48,6 +48,7 @@ import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
+import org.opensaml.xmlsec.signature.P;
import org.wso2.carbon.CarbonConstants;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
@@ -69,8 +70,10 @@ import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.StartupOperationConfig;
+import org.wso2.carbon.device.mgt.common.BillingResponse;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
+import org.wso2.carbon.device.mgt.common.app.mgt.MobileAppTypes;
import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfigurationException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
@@ -119,11 +122,12 @@ import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypePlatformVersion;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.DeviceManagementPluginRepository;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
+import org.wso2.carbon.device.mgt.core.cache.impl.BillingCacheManagerImpl;
import org.wso2.carbon.device.mgt.core.cache.impl.DeviceCacheManagerImpl;
+import org.wso2.carbon.device.mgt.core.common.Constants;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
import org.wso2.carbon.device.mgt.core.dao.ApplicationDAO;
-import org.wso2.carbon.device.mgt.core.dao.BillingDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceDAO;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
@@ -141,8 +145,10 @@ import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementServiceComponent;
import org.wso2.carbon.device.mgt.core.internal.PluginInitializationListener;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataDAO;
+import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOException;
import org.wso2.carbon.device.mgt.core.metadata.mgt.dao.MetadataManagementDAOFactory;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
+import org.wso2.carbon.device.mgt.core.operation.mgt.ProfileOperation;
import org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
import org.wso2.carbon.device.mgt.core.util.HttpReportingUtil;
import org.wso2.carbon.email.sender.core.ContentProviderInfo;
@@ -164,8 +170,7 @@ import java.io.StringWriter;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.sql.Timestamp;
-import java.text.Format;
-import java.text.SimpleDateFormat;
+import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
@@ -193,8 +198,8 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
private final EnrollmentDAO enrollmentDAO;
private final ApplicationDAO applicationDAO;
private MetadataDAO metadataDAO;
- private final BillingDAO billingDAO;
private final DeviceStatusDAO deviceStatusDAO;
+ int count = 0;
public DeviceManagementProviderServiceImpl() {
this.pluginRepository = new DeviceManagementPluginRepository();
@@ -203,7 +208,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
this.deviceTypeDAO = DeviceManagementDAOFactory.getDeviceTypeDAO();
this.enrollmentDAO = DeviceManagementDAOFactory.getEnrollmentDAO();
this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
- this.billingDAO = DeviceManagementDAOFactory.getBillingDAO();
this.deviceStatusDAO = DeviceManagementDAOFactory.getDeviceStatusDAO();
/* Registering a listener to retrieve events when some device management service plugin is installed after
@@ -430,21 +434,12 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//enroll Traccar device
if (HttpReportingUtil.isTrackerEnabled()) {
- try {
- DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().addDevice(device, tenantId);
- } catch (ExecutionException e) {
- log.error("ExecutionException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- } catch (InterruptedException e) {
- log.error("InterruptedException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- }
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().addDevice(device);
} else {
- log.info("Traccar is disabled");
+ if (log.isDebugEnabled()) {
+ log.debug("Traccar is disabled");
+ }
}
- //enroll Traccar device
if (status) {
addDeviceToGroups(deviceIdentifier, device.getEnrolmentInfo().getOwnership());
@@ -529,22 +524,13 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
extractDeviceLocationToUpdate(device);
//enroll Traccar device
if (HttpReportingUtil.isTrackerEnabled()) {
- try {
- int tenantId = this.getTenantId();
- DeviceManagementDataHolder.getInstance().getDeviceAPIClientService().modifyDevice(device, tenantId);
- } catch (ExecutionException e) {
- log.error("ExecutionException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- } catch (InterruptedException e) {
- log.error("InterruptedException : " + e);
- //throw new RuntimeException(e);
- //Exception was not thrown due to being conflicted with non-traccar features
- }
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().updateDevice(device);
} else {
- log.info("Traccar is disabled");
+ if (log.isDebugEnabled()) {
+ log.debug("Traccar is disabled");
+ }
}
- //enroll Traccar device
+
return status;
}
@@ -628,8 +614,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
//procees to dis-enroll a device from traccar starts
if (HttpReportingUtil.isTrackerEnabled()) {
- DeviceManagementDataHolder.getInstance().getDeviceAPIClientService()
- .disEnrollDevice(device.getId(), tenantId);
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().unLinkTraccarDevice(device.getEnrolmentInfo().getId());
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Traccar is disabled");
+ }
}
//procees to dis-enroll a device from traccar ends
@@ -749,6 +738,15 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
if (log.isDebugEnabled()) {
log.debug("Successfully permanently deleted the details of devices : " + validDeviceIdentifiers);
}
+ if (HttpReportingUtil.isTrackerEnabled()) {
+ for (int enrollmentId : enrollmentIds) {
+ DeviceManagementDataHolder.getInstance().getTraccarManagementService().removeDevice(enrollmentId);
+ }
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Traccar is disabled");
+ }
+ }
return true;
} catch (TransactionManagementException e) {
String msg = "Error occurred while initiating transaction";
@@ -1021,236 +1019,232 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
return this.getAllDevices(request, true);
}
- public PaginationResult calculateCost(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill, List allDevices) throws DeviceManagementException {
+ /**
+ * Calculate cost of a tenants Device List.
+ * Once the full device list of a tenant is sent here devices are looped for cost calculation
+ * Cost per tenant is retrieved from the Meta Table
+ * When looping the devices the most recent device status of that device is retrieved from status table
+ * If device is enrolled prior to start date now in removed state --> time is calculated from - startDate to last updated time
+ * If device is enrolled prior to start date now in not removed --> time is calculated from - startDate to endDate
+ * If device is enrolled after the start date now in removed state --> time is calculated from - dateOfEnrollment to last updated time
+ * If device is enrolled after the start date now in not removed --> time is calculated from - dateOfEnrollment to endDate
+ * Once time is calculated cost is set for each device
+ *
+ * @param tenantDomain Tenant domain cost id calculated for.
+ * @param startDate start date of usage period.
+ * @param endDate end date of usage period.
+ * @param allDevices device list of the tenant for the selected time-period.
+ * @return Whether status is changed or not
+ * @throws DeviceManagementException on errors while trying to calculate Cost
+ */
+ public BillingResponse calculateCost(String tenantDomain, Timestamp startDate, Timestamp endDate, List allDevices) throws MetadataManagementDAOException, DeviceManagementException {
- PaginationResult paginationResult = new PaginationResult();
+ BillingResponse billingResponse = new BillingResponse();
+ List deviceStatusNotAvailable = new ArrayList<>();
double totalCost = 0.0;
- boolean allDevicesBilledDateIsValid = true;
- ArrayList lastBilledDatesList = new ArrayList<>();
- List invalidDevices = new ArrayList<>();
- List removeBillingPeriodInvalidDevices = new ArrayList<>() ;
- List removeStatusUpdateInvalidDevices = new ArrayList<>() ;
try {
- MetadataManagementDAOFactory.beginTransaction();
+ MetadataManagementDAOFactory.openConnection();
Metadata metadata = metadataDAO.getMetadata(MultitenantConstants.SUPER_TENANT_ID, DeviceManagementConstants.META_KEY);
Gson g = new Gson();
Collection costData = null;
-
- Type collectionType = new TypeToken>() {}.getType();
+ Type collectionType = new TypeToken>() {
+ }.getType();
if (metadata != null) {
costData = g.fromJson(metadata.getMetaValue(), collectionType);
for (Cost tenantCost : costData) {
if (tenantCost.getTenantDomain().equals(tenantDomain)) {
for (Device device : allDevices) {
- device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, null, true));
long dateDiff = 0;
-
+ device.setDeviceStatusInfo(getDeviceStatusHistory(device, null, endDate, true));
List deviceStatus = device.getDeviceStatusInfo();
- boolean firstDateBilled = false;
- boolean deviceStatusIsValid = false;
-
- List deviceBilling = billingDAO.getBilling(device.getId(), startDate, endDate);
- boolean billDateIsInvalid = false;
-
- if (deviceBilling.isEmpty()) {
- billDateIsInvalid = false;
- }
-
- if (generateBill) {
- for (Billing bill : deviceBilling) {
- if ((bill.getBillingStart() <= startDate.getTime() && startDate.getTime() <= bill.getBillingEnd()) ||
- (bill.getBillingStart() <= endDate.getTime() && endDate.getTime() <= bill.getBillingEnd())) {
- billDateIsInvalid = true;
- invalidDevices.add(bill);
- }
- }
- }
-
- if (!billDateIsInvalid) {
- for (int i = 0; i < deviceStatus.size(); i++) {
- if (DeviceManagementConstants.ACTIVE_STATUS.equals(deviceStatus.get(i).getStatus().toString())) {
- if (deviceStatus.size() > i + 1) {
- if (!firstDateBilled) {
- firstDateBilled = true;
- if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
- } else {
- if (deviceStatus.get(i + 1).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - device.getEnrolmentInfo().getLastBilledDate());
- }
- }
- } else {
- if (deviceStatus.get(i).getUpdateTime().getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (deviceStatus.get(i + 1).getUpdateTime().getTime() - deviceStatus.get(i).getUpdateTime().getTime());
- }
- }
- } else {
-
- // If only one status row is retrieved this block is executed
- if (!firstDateBilled) {
- firstDateBilled = true;
-
- // Is executed if there is no lastBilled date and if the updates time is before the end date
- if (device.getEnrolmentInfo().getLastBilledDate() == 0) {
- if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
- }
- } else {
- if (endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
- }
- }
- } else {
- if (device.getEnrolmentInfo().getLastBilledDate() <= deviceStatus.get(i).getUpdateTime().getTime()
- && endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (endDate.getTime() - deviceStatus.get(i).getUpdateTime().getTime());
- }
- if (device.getEnrolmentInfo().getLastBilledDate() >= deviceStatus.get(i).getUpdateTime().getTime()
- && endDate.getTime() >= device.getEnrolmentInfo().getLastBilledDate()) {
- deviceStatusIsValid = true;
- dateDiff = dateDiff + (endDate.getTime() - device.getEnrolmentInfo().getLastBilledDate());
- }
- }
- }
+ if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) {
+ if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) {
+ if (deviceStatus.get(0).getUpdateTime().getTime() >= startDate.getTime()) {
+ dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - startDate.getTime();
}
+ } else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) {
+ dateDiff = endDate.getTime() - startDate.getTime();
}
-
- long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS);
- double cost = (tenantCost.getCost() / 365) * dateInDays;
- totalCost = cost + totalCost;
- device.setCost(Math.round(cost * 100.0) / 100.0);
- device.setDaysUsed((int) dateInDays);
-
- if (generateBill) {
- enrollmentDAO.updateEnrollmentLastBilledDate(device.getEnrolmentInfo(), endDate, tenantId);
- billingDAO.addBilling(device.getId(), tenantId, startDate, endDate);
- DeviceManagementDAOFactory.commitTransaction();
- }
-
} else {
-
- for (int i = 0; i < deviceStatus.size(); i++) {
- if (endDate.getTime() >= deviceStatus.get(i).getUpdateTime().getTime()
- && startDate.getTime() <= deviceStatus.get(i).getUpdateTime().getTime()) {
- deviceStatusIsValid = true;
+ if (!deviceStatus.isEmpty() && deviceStatus.get(0).getStatus().equals("REMOVED")) {
+ if (deviceStatus.get(0).getUpdateTime().getTime() >= device.getEnrolmentInfo().getDateOfEnrolment()) {
+ dateDiff = deviceStatus.get(0).getUpdateTime().getTime() - device.getEnrolmentInfo().getDateOfEnrolment();
}
+ } else if (!deviceStatus.isEmpty() && !deviceStatus.get(0).getStatus().equals("REMOVED")) {
+ dateDiff = endDate.getTime() - device.getEnrolmentInfo().getDateOfEnrolment();
}
- if (device.getEnrolmentInfo().getLastBilledDate() != 0) {
- Date date = new Date(device.getEnrolmentInfo().getLastBilledDate());
- Format format = new SimpleDateFormat("yyyy MM dd");
-
- for (String lastBillDate : lastBilledDatesList) {
- if (!lastBillDate.equals(format.format(date))) {
- lastBilledDatesList.add(format.format(date));
- }
- }
- }
- removeBillingPeriodInvalidDevices.add(device);
}
-
- if (!deviceStatusIsValid) {
- removeStatusUpdateInvalidDevices.add(device);
+ long dateInDays = TimeUnit.DAYS.convert(dateDiff, TimeUnit.MILLISECONDS);
+ double cost = (tenantCost.getCost() / 365) * dateInDays;
+ totalCost += cost;
+ device.setCost(Math.round(cost * 100.0) / 100.0);
+ long totalDays = dateInDays + device.getDaysUsed();
+ device.setDaysUsed((int) totalDays);
+ if (deviceStatus.isEmpty()) {
+ deviceStatusNotAvailable.add(device);
}
}
}
}
}
- } catch (DeviceManagementDAOException e) {
- String msg = "Error occurred while retrieving device list pertaining to the current tenant";
+ } catch (DeviceManagementException e) {
+ String msg = "Error occurred calculating cost of devices";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
- } catch (Exception e) {
- String msg = "Error occurred in getAllDevices";
+ } catch (SQLException e) {
+ String msg = "Error when retrieving data";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ } catch (MetadataManagementDAOException e) {
+ String msg = "Error when retrieving metadata of billing feature";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
- DeviceManagementDAOFactory.closeConnection();
MetadataManagementDAOFactory.closeConnection();
}
- if(!removeBillingPeriodInvalidDevices.isEmpty() && removeBillingPeriodInvalidDevices.size() == allDevices.size()) {
- allDevicesBilledDateIsValid = false;
- paginationResult.setMessage("Invalid bill period.");
+ if (!deviceStatusNotAvailable.isEmpty()) {
+ allDevices.removeAll(deviceStatusNotAvailable);
}
- if(!removeStatusUpdateInvalidDevices.isEmpty() && removeStatusUpdateInvalidDevices.size() == allDevices.size()) {
- allDevicesBilledDateIsValid = false;
- if (paginationResult.getMessage() != null){
- paginationResult.setMessage(paginationResult.getMessage() + " and no device updates within entered bill period.");
- } else {
- paginationResult.setMessage("Devices have not been updated within the given period or entered end date comes before the " +
- "last billed date.");
- }
- }
- allDevices.removeAll(removeBillingPeriodInvalidDevices);
- allDevices.removeAll(removeStatusUpdateInvalidDevices);
+ Calendar calStart = Calendar.getInstance();
+ Calendar calEnd = Calendar.getInstance();
+ calStart.setTimeInMillis(startDate.getTime());
+ calEnd.setTimeInMillis(endDate.getTime());
- paginationResult.setBilledDateIsValid(allDevicesBilledDateIsValid);
- paginationResult.setData(allDevices);
- paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0);
- return paginationResult;
+ billingResponse.setDevice(allDevices);
+ billingResponse.setYear(String.valueOf(calStart.get(Calendar.YEAR)));
+ billingResponse.setStartDate(startDate.toString());
+ billingResponse.setEndDate(endDate.toString());
+ billingResponse.setBillPeriod(calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR));
+ billingResponse.setTotalCostPerYear(Math.round(totalCost * 100.0) / 100.0);
+ billingResponse.setDeviceCount(allDevices.size());
+
+ return billingResponse;
}
@Override
- public PaginationResult getAllDevicesBillings(PaginationRequest request, int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException {
- if (request == null) {
- String msg = "Received incomplete pagination request for method getAllDeviceBillings";
- log.error(msg);
- throw new DeviceManagementException(msg);
- }
+ public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate) throws DeviceManagementException {
- DeviceManagerUtil.validateDeviceListPageSize(request);
PaginationResult paginationResult = new PaginationResult();
- List allDevices;
- int count = 0;
-
+ List allDevices = new ArrayList<>();
+ List billingResponseList = new ArrayList<>();
+ double totalCost = 0.0;
+ int deviceCount = 0;
+ Timestamp initialStartDate = startDate;
+ boolean remainingDaysConsidered = false;
try {
- DeviceManagementDAOFactory.beginTransaction();
- allDevices = deviceDAO.getDevices(request, tenantId);
- count = deviceDAO.getDeviceCount(request, tenantId);
- paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices);
+ DeviceManagementDAOFactory.openConnection();
- } catch (DeviceManagementDAOException e) {
- String msg = "Error occurred while retrieving device bill list pertaining to the current tenant";
- log.error(msg, e);
- throw new DeviceManagementException(msg, e);
- } catch (Exception e) {
- String msg = "Error occurred in getAllDevicesBillings";
- log.error(msg, e);
- throw new DeviceManagementException(msg, e);
- }
- paginationResult.setRecordsFiltered(count);
- paginationResult.setRecordsTotal(count);
- return paginationResult;
- }
+ // TODO Do the check of cache enabling here
+ paginationResult = BillingCacheManagerImpl.getInstance().getBillingFromCache(tenantDomain, startDate, endDate);
+ if (paginationResult == null) {
+ paginationResult = new PaginationResult();
+ long difference_In_Time = endDate.getTime() - startDate.getTime();
+
+ long difference_In_Years = (difference_In_Time / (1000L * 60 * 60 * 24 * 365));
+
+ long difference_In_Days = (difference_In_Time / (1000 * 60 * 60 * 24)) % 365;
+
+ for (int i = 1; i <= difference_In_Years; i++) {
+ List allDevicesPerYear = new ArrayList<>();
+ LocalDateTime oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
+ Timestamp newStartDate;
+ Timestamp newEndDate;
+
+ if (i == difference_In_Years) {
+ if (difference_In_Days == 0 || Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) {
+ remainingDaysConsidered = true;
+ oneYearAfterStart = startDate.toLocalDateTime();
+ newEndDate = endDate;
+ } else if (Timestamp.valueOf(oneYearAfterStart).getTime() >= endDate.getTime()) {
+ newEndDate = Timestamp.valueOf(oneYearAfterStart);
+ } else {
+ oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
+ newEndDate = Timestamp.valueOf(oneYearAfterStart);
+ }
+ } else {
+ oneYearAfterStart = startDate.toLocalDateTime().plusYears(1);
+ newEndDate = Timestamp.valueOf(oneYearAfterStart);
+ }
- @Override
- public PaginationResult createBillingFile(int tenantId, String tenantDomain, Timestamp startDate, Timestamp endDate, boolean generateBill) throws DeviceManagementException {
- PaginationResult paginationResult = new PaginationResult();
- List allDevices;
- try {
- DeviceManagementDAOFactory.beginTransaction();
- allDevices = deviceDAO.getDeviceListWithoutPagination(tenantId);
- paginationResult = calculateCost(tenantId, tenantDomain, startDate, endDate, generateBill, allDevices);
+ newStartDate = startDate;
+
+ // The query returns devices which are enrolled in this year now in not removed state
+ allDevicesPerYear.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate));
+
+ // The query returns devices which are enrolled in this year now in removed state
+ allDevicesPerYear.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, newStartDate, newEndDate));
+
+ // The query returns devices which are enrolled prior this year now in not removed state
+ allDevicesPerYear.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate));
+
+ // The query returns devices which are enrolled prior this year now in removed state
+ allDevicesPerYear.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, newStartDate, newEndDate));
+
+ BillingResponse billingResponse = calculateCost(tenantDomain, newStartDate, newEndDate, allDevicesPerYear);
+ billingResponseList.add(billingResponse);
+ allDevices.addAll(billingResponse.getDevice());
+ totalCost = totalCost + billingResponse.getTotalCostPerYear();
+ deviceCount = deviceCount + billingResponse.getDeviceCount();
+ LocalDateTime nextStartDate = oneYearAfterStart.plusDays(1);
+ startDate = Timestamp.valueOf(nextStartDate);
+ }
+
+ if (difference_In_Days != 0 && !remainingDaysConsidered) {
+ List allDevicesPerRemainingDays = new ArrayList<>();
+
+ // The query returns devices which are enrolled in this year now in not removed state
+ allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedYearlyDeviceList(tenantId, startDate, endDate));
+
+ // The query returns devices which are enrolled in this year now in removed state
+ allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedYearlyDeviceList(tenantId, startDate, endDate));
+
+ // The query returns devices which are enrolled prior this year now in not removed state
+ allDevicesPerRemainingDays.addAll(deviceDAO.getNonRemovedPriorYearsDeviceList(tenantId, startDate, endDate));
+
+ // The query returns devices which are enrolled prior this year now in removed state
+ allDevicesPerRemainingDays.addAll(deviceDAO.getRemovedPriorYearsDeviceList(tenantId, startDate, endDate));
+
+ BillingResponse billingResponse = calculateCost(tenantDomain, startDate, endDate, allDevicesPerRemainingDays);
+ billingResponseList.add(billingResponse);
+ allDevices.addAll(billingResponse.getDevice());
+ totalCost = totalCost + billingResponse.getTotalCostPerYear();
+ deviceCount = deviceCount + billingResponse.getDeviceCount();
+ }
+
+ Calendar calStart = Calendar.getInstance();
+ Calendar calEnd = Calendar.getInstance();
+ calStart.setTimeInMillis(initialStartDate.getTime());
+ calEnd.setTimeInMillis(endDate.getTime());
+
+ BillingResponse billingResponse = new BillingResponse("all", Math.round(totalCost * 100.0) / 100.0, allDevices, calStart.get(Calendar.YEAR) + " - " + calEnd.get(Calendar.YEAR), initialStartDate.toString(), endDate.toString(), allDevices.size());
+ billingResponseList.add(billingResponse);
+ paginationResult.setData(billingResponseList);
+ paginationResult.setTotalCost(Math.round(totalCost * 100.0) / 100.0);
+ paginationResult.setTotalDeviceCount(deviceCount);
+ BillingCacheManagerImpl.getInstance().addBillingToCache(paginationResult, tenantDomain, initialStartDate, endDate);
+ return paginationResult;
+ }
} catch (DeviceManagementDAOException e) {
- String msg = "Error occurred while retrieving device bill list without pagination pertaining to the current tenant";
+ String msg = "Error occurred while retrieving device bill list related to the current tenant";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
- } catch (Exception e) {
- String msg = "Error occurred in createBillingFile";
+ } catch (MetadataManagementDAOException e) {
+ String msg = "Error when retrieving metadata of billing feature";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ } catch (SQLException e) {
+ String msg = "Error occurred while opening a connection to the data source";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
+ } finally {
+ DeviceManagementDAOFactory.closeConnection();
}
return paginationResult;
}
@@ -1553,6 +1547,25 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
}
+ @Override
+ public void sendEnrolmentGuide(String enrolmentGuide) throws DeviceManagementException {
+
+ DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
+ String recipientMail = config.getEnrollmentGuideConfiguration().getMail();
+ Properties props = new Properties();
+ props.setProperty("mail-subject", "[Enrollment Guide Triggered] (#" + ++count + ")");
+ props.setProperty("enrollment-guide", enrolmentGuide);
+
+ try {
+ EmailMetaInfo metaInfo = new EmailMetaInfo(recipientMail, props);
+ sendEnrolmentInvitation(DeviceManagementConstants.EmailAttributes.ENROLLMENT_GUIDE_TEMPLATE, metaInfo);
+ } catch (ConfigurationManagementException e) {
+ String msg = "Error occurred while sending the mail.";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ }
+ }
+
@Override
public void sendRegistrationEmail(EmailMetaInfo metaInfo) throws DeviceManagementException,
ConfigurationManagementException {
@@ -4878,4 +4891,34 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
paginationResult.setData(populateAllDeviceInfo(subscribedDeviceDetails));
return paginationResult;
}
+
+ @Override
+ public Boolean sendDeviceNameChangedNotification(Device device) throws DeviceManagementException {
+
+ try {
+ ProfileOperation operation = new ProfileOperation();
+ operation.setCode(Constants.SEND_USERNAME);
+ operation.setType(Operation.Type.PROFILE);
+ operation.setPayLoad(device.getName());
+
+ DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
+ deviceIdentifier.setId(device.getDeviceIdentifier());
+ deviceIdentifier.setType(device.getType());
+
+ List deviceIdentifiers = new ArrayList<>();
+ deviceIdentifiers.add(deviceIdentifier);
+ Activity activity;
+ activity = addOperation(device.getType(), operation, deviceIdentifiers);
+
+ return activity != null;
+ } catch (OperationManagementException e) {
+ String msg = "Error occurred while sending operation";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ } catch (InvalidDeviceException e) {
+ String msg = "Invalid Device exception occurred";
+ log.error(msg, e);
+ throw new DeviceManagementException(msg, e);
+ }
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
index 5028f2560b0..8f12f8a1df6 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderService.java
@@ -41,6 +41,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@@ -335,4 +336,11 @@ public interface GroupManagementProviderService {
*/
boolean isDeviceMappedToGroup(int groupId, DeviceIdentifier deviceIdentifier) throws GroupManagementException;
+ /**
+ *
+ * @param identifiers identifiers of groups
+ * @return whether the groups has android, iOS, Windows device types
+ * @throws GroupManagementException
+ */
+ DeviceTypesOfGroups getDeviceTypesOfGroups(List identifiers) throws GroupManagementException;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
index aed9bc8782e..9981333428d 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/service/GroupManagementProviderServiceImpl.java
@@ -43,6 +43,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.DeviceIdentifier;
+import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
@@ -51,6 +52,7 @@ import org.wso2.carbon.device.mgt.common.exceptions.TrackerAlreadyExistException
import org.wso2.carbon.device.mgt.common.exceptions.TransactionManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
+import org.wso2.carbon.device.mgt.common.group.mgt.DeviceTypesOfGroups;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyExistException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupNotExistException;
@@ -79,6 +81,7 @@ import java.util.stream.Collectors;
public class GroupManagementProviderServiceImpl implements GroupManagementProviderService {
private static final Log log = LogFactory.getLog(GroupManagementProviderServiceImpl.class);
+ private static final String DEVICE_STATUS_REMOVED = "REMOVED";
private final GroupDAO groupDAO;
private final DeviceDAO deviceDAO;
@@ -1379,4 +1382,60 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
createGroupWithChildren(nextParentGroup, childrenGroups, requireGroupProps, tenantId, depth, counter);
}
}
+ @Override
+ public DeviceTypesOfGroups getDeviceTypesOfGroups(List identifiers) throws GroupManagementException {
+ DeviceTypesOfGroups deviceTypesOfGroups = new DeviceTypesOfGroups();
+ List groupsIDs = new ArrayList<>();
+ try {
+ for (String id : identifiers) {
+ groupsIDs.add(Integer.parseInt(id));
+ }
+
+ List deviceIDs = new ArrayList<>();
+ List allDevices = new ArrayList<>();
+ for (Integer groupID : groupsIDs) {
+ DeviceGroup deviceGroup = getGroup(groupID, false);
+ if (deviceGroup == null) {
+ String errorMessage = "Invalid Group ID provided.";
+ log.error(errorMessage);
+ throw new GroupManagementException(errorMessage);
+ }
+ List devices = getAllDevicesOfGroup(deviceGroup.getName(), false);
+ for (Device device : devices) {
+ if (!DEVICE_STATUS_REMOVED.equals(device.getEnrolmentInfo().getStatus().toString())
+ && !deviceIDs.contains(device.getDeviceIdentifier())) {
+ deviceIDs.add(device.getDeviceIdentifier());
+ allDevices.add(device);
+ }
+ }
+ }
+
+ for (Device device : allDevices) {
+ if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID.equals(device.getType())) {
+ deviceTypesOfGroups.setHasAndroid(true);
+ break;
+ }
+ }
+ for (Device device : allDevices) {
+ if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS.equals(device.getType())) {
+ deviceTypesOfGroups.setHasIos(true);
+ break;
+ }
+ }
+ for (Device device : allDevices) {
+ if (DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_WINDOWS.equals(device.getType())) {
+ deviceTypesOfGroups.setHasWindows(true);
+ break;
+ }
+ }
+
+ } catch (NumberFormatException e) {
+ String errorMessage = "Only numbers can exists in a group ID";
+ log.error(errorMessage);
+ throw new GroupManagementException(errorMessage, e);
+
+ }
+
+ return deviceTypesOfGroups;
+ }
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java
index 5182fc36516..9d2e1ee7ce2 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/status/task/impl/DeviceStatusMonitoringTask.java
@@ -37,7 +37,6 @@ import org.wso2.carbon.device.mgt.core.task.impl.DynamicPartitionedScheduleTask;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
-import java.util.Map;
/**
* This implements the Task service which monitors the device activity periodically & update the device-status if
@@ -47,19 +46,8 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
private static final Log log = LogFactory.getLog(DeviceStatusMonitoringTask.class);
private String deviceType;
- private DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig;
private int deviceTypeId = -1;
- @Override
- public void setProperties(Map properties) {
- super.setProperties(properties);
- deviceType = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE);
- deviceTypeId = Integer.parseInt(properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID));
- String deviceStatusTaskConfigStr = properties.get(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG);
- Gson gson = new Gson();
- deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class);
- }
-
@Override
protected void setup() {
}
@@ -92,6 +80,11 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
@Override
public void executeDynamicTask() {
+ deviceType = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE);
+ deviceTypeId = Integer.parseInt(getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_TYPE_ID));
+ String deviceStatusTaskConfigStr = getProperty(DeviceStatusTaskManagerServiceImpl.DEVICE_STATUS_TASK_CONFIG);
+ Gson gson = new Gson();
+ DeviceStatusTaskPluginConfig deviceStatusTaskPluginConfig = gson.fromJson(deviceStatusTaskConfigStr, DeviceStatusTaskPluginConfig.class);
try {
List enrolmentInfoTobeUpdated = new ArrayList<>();
List allDevicesForMonitoring = getAllDevicesForMonitoring();
@@ -102,10 +95,10 @@ public class DeviceStatusMonitoringTask extends DynamicPartitionedScheduleTask {
EnrolmentInfo enrolmentInfo = monitoringData.getDevice().getEnrolmentInfo();
EnrolmentInfo.Status status = null;
- if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig
+ if (lastUpdatedTime >= deviceStatusTaskPluginConfig
.getIdleTimeToMarkInactive()) {
status = EnrolmentInfo.Status.INACTIVE;
- } else if (lastUpdatedTime >= this.deviceStatusTaskPluginConfig
+ } else if (lastUpdatedTime >= deviceStatusTaskPluginConfig
.getIdleTimeToMarkUnreachable()) {
status = EnrolmentInfo.Status.UNREACHABLE;
}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java
index 0c6f77c15de..a13031eabb7 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DeviceDetailsRetrieverTask.java
@@ -48,7 +48,6 @@ import org.wso2.carbon.device.mgt.core.task.DeviceMgtTaskException;
import org.wso2.carbon.device.mgt.core.task.DeviceTaskManager;
import java.util.List;
-import java.util.Map;
public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask {
@@ -56,14 +55,9 @@ public class DeviceDetailsRetrieverTask extends DynamicPartitionedScheduleTask {
private String deviceType;
private DeviceManagementProviderService deviceManagementProviderService;
- @Override
- public void setProperties(Map map) {
- super.setProperties(map);
- deviceType = map.get("DEVICE_TYPE");
- }
-
@Override
public void executeDynamicTask() {
+ deviceType = getProperty("DEVICE_TYPE");
deviceManagementProviderService = DeviceManagementDataHolder.getInstance()
.getDeviceManagementProvider();
OperationMonitoringTaskConfig operationMonitoringTaskConfig = deviceManagementProviderService
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java
index 0bbb59d2bda..ad3269be004 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/task/impl/DynamicPartitionedScheduleTask.java
@@ -19,10 +19,11 @@
package org.wso2.carbon.device.mgt.core.task.impl;
import io.entgra.server.bootup.heartbeat.beacon.exception.HeartBeatManagementException;
+import io.entgra.task.mgt.common.constant.TaskMgtConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.wso2.carbon.device.mgt.common.ServerCtxInfo;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
+import org.wso2.carbon.device.mgt.common.ServerCtxInfo;
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
import org.wso2.carbon.ntask.core.Task;
@@ -37,11 +38,11 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
private Map properties;
@Override
- public void setProperties(Map properties) {
+ public final void setProperties(Map properties) {
this.properties = properties;
}
- public String getProperty(String name) {
+ public final String getProperty(String name) {
if (properties == null) {
return null;
}
@@ -62,7 +63,7 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
}
}
} catch (HeartBeatManagementException e) {
- log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function." , e);
+ log.error("Error Instantiating Variables necessary for Dynamic Task Scheduling. Dynamic Tasks will not function.", e);
}
setup();
}
@@ -70,11 +71,41 @@ public abstract class DynamicPartitionedScheduleTask implements Task {
@Override
public final void execute() {
refreshContext();
- executeDynamicTask();
+ if (taskContext != null && taskContext.isPartitioningEnabled()) {
+ String localHashIndex = getProperty(TaskMgtConstants.Task.LOCAL_HASH_INDEX);
+ // These tasks are not dynamically scheduled. They are added via a config so scheduled in each node
+ // during the server startup
+ if (localHashIndex == null ) {
+ if (log.isDebugEnabled()) {
+ log.debug("Executing startup scheduled task (" + getTaskName() + ") with class: " +
+ this.getClass().getName());
+ }
+ executeDynamicTask();
+ return;
+ }
+ if (localHashIndex.equals(String.valueOf(taskContext.getServerHashIndex()))) {
+ if (log.isDebugEnabled()) {
+ log.debug("Executing dynamically scheduled task (" + getTaskName() +
+ ") for current server hash index: " + localHashIndex);
+ }
+ executeDynamicTask();
+ } else {
+ if (log.isDebugEnabled()) {
+ log.debug("Ignoring execution of task (" + getTaskName() +
+ ") not belonging to current serer hash index: " + localHashIndex);
+ }
+ }
+ } else {
+ executeDynamicTask();
+ }
+ }
+
+ public String getTaskName() {
+ return getProperty(TaskMgtConstants.Task.LOCAL_TASK_NAME);
}
- public void refreshContext(){
- if(taskContext != null && taskContext.isPartitioningEnabled()) {
+ public void refreshContext() {
+ if (taskContext != null && taskContext.isPartitioningEnabled()) {
try {
updateContext();
} catch (HeartBeatManagementException e) {
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
index 8a88d53ac0d..65a26d13304 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceManagerUtil.java
@@ -58,6 +58,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.GroupPaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.EnrollmentConfiguration;
@@ -76,6 +77,7 @@ import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagement
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.common.type.mgt.DeviceTypeMetaDefinition;
import org.wso2.carbon.device.mgt.core.DeviceManagementConstants;
+import org.wso2.carbon.device.mgt.core.cache.BillingCacheKey;
import org.wso2.carbon.device.mgt.core.cache.DeviceCacheKey;
import org.wso2.carbon.device.mgt.core.cache.GeoCacheKey;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@@ -137,6 +139,7 @@ public final class DeviceManagerUtil {
public static final String GENERAL_CONFIG_RESOURCE_PATH = "general";
private static boolean isDeviceCacheInitialized = false;
+ private static boolean isBillingCacheInitialized = false;
private static boolean isAPIResourcePermissionCacheInitialized = false;
private static boolean isGeoFenceCacheInitialized = false;
@@ -652,6 +655,47 @@ public final class DeviceManagerUtil {
}
}
+ /**
+ * Enable Billing caching according to the configurations provided by cdm-config.xml
+ */
+ public static void initializeBillingCache() {
+ DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
+ int billingCacheExpiry = config.getBillingCacheConfiguration().getExpiryTime();
+ long billingCacheCapacity = config.getBillingCacheConfiguration().getCapacity();
+ CacheManager manager = getCacheManager();
+ if (config.getBillingCacheConfiguration().isEnabled()) {
+ if(!isBillingCacheInitialized) {
+ isBillingCacheInitialized = true;
+ if (manager != null) {
+ if (billingCacheExpiry > 0) {
+ manager.createCacheBuilder(DeviceManagementConstants.BILLING_CACHE).
+ setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
+ billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
+ Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build();
+ if(billingCacheCapacity > 0 ) {
+ ((CacheImpl) manager.getCache(DeviceManagementConstants.BILLING_CACHE)).
+ setCapacity(billingCacheCapacity);
+ }
+ } else {
+ manager.getCache(DeviceManagementConstants.BILLING_CACHE);
+ }
+ } else {
+ if (billingCacheExpiry > 0) {
+ Caching.getCacheManager().
+ createCacheBuilder(DeviceManagementConstants.BILLING_CACHE).
+ setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
+ billingCacheExpiry)).setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.
+ Duration(TimeUnit.SECONDS, billingCacheExpiry)).setStoreByValue(true).build();
+ ((CacheImpl)(manager.getCache(DeviceManagementConstants.BILLING_CACHE))).
+ setCapacity(billingCacheCapacity);
+ } else {
+ Caching.getCacheManager().getCache(DeviceManagementConstants.BILLING_CACHE);
+ }
+ }
+ }
+ }
+ }
+
/**
* Enable Geofence caching according to the configurations proviced by cdm-config.xml
*/
@@ -711,6 +755,28 @@ public final class DeviceManagerUtil {
return deviceCache;
}
+ /**
+ * Get billing cache object
+ * @return {@link Cache}
+ */
+ public static Cache getBillingCache() {
+ DeviceManagementConfig config = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
+ CacheManager manager = getCacheManager();
+ Cache billingCache = null;
+ if (config.getBillingCacheConfiguration().isEnabled()) {
+ if(!isBillingCacheInitialized) {
+ initializeBillingCache();
+ }
+ if (manager != null) {
+ billingCache = manager.getCache(DeviceManagementConstants.BILLING_CACHE);
+ } else {
+ billingCache = Caching.getCacheManager(DeviceManagementConstants.DM_CACHE_MANAGER)
+ .getCache(DeviceManagementConstants.BILLING_CACHE);
+ }
+ }
+ return billingCache;
+ }
+
/**
* Get geofence cache object
* @return {@link Cache}
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceMgtTenantMgtListener.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceMgtTenantMgtListener.java
index 5e0e0cff931..79f58e82a17 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceMgtTenantMgtListener.java
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/util/DeviceMgtTenantMgtListener.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.device.mgt.core.util;
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.exceptions.MetadataManagementException;
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
import org.wso2.carbon.device.mgt.common.roles.config.Role;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@@ -68,6 +69,12 @@ public class DeviceMgtTenantMgtListener implements TenantMgtListener {
PrivilegedCarbonContext.endTenantFlow();
}
}
+ try {
+ DeviceManagementDataHolder.getInstance().getWhiteLabelManagementService().
+ addDefaultWhiteLabelThemeIfNotExist(tenantInfoBean.getTenantId());
+ } catch (MetadataManagementException e) {
+ log.error("Error occurred while adding default white label theme to created tenant.", e);
+ }
}
@Override
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
index 005db8fb7da..d3b81f2655c 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/test/resources/sql/h2.sql
@@ -94,7 +94,6 @@ CREATE TABLE IF NOT EXISTS DM_ENROLMENT (
DATE_OF_ENROLMENT TIMESTAMP DEFAULT NULL,
DATE_OF_LAST_UPDATE TIMESTAMP DEFAULT NULL,
TENANT_ID INT NOT NULL,
- LAST_BILLED_DATE BIGINT DEFAULT 0,
PRIMARY KEY (ID),
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
@@ -564,16 +563,6 @@ ORDER BY TENANT_ID, DEVICE_ID;
-- END OF DASHBOARD RELATED VIEWS --
-CREATE TABLE IF NOT EXISTS DM_BILLING (
- INVOICE_ID INTEGER AUTO_INCREMENT NOT NULL,
- TENANT_ID INTEGER DEFAULT 0,
- DEVICE_ID INTEGER DEFAULT NULL,
- BILLING_START TIMESTAMP NOT NULL,
- BILLING_END TIMESTAMP NOT NULL,
- PRIMARY KEY (INVOICE_ID),
-CONSTRAINT fk_DM_BILLING_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
-REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
-);
-- DM_EXT_GROUP_MAPPING TABLE--
CREATE TABLE IF NOT EXISTS DM_EXT_GROUP_MAPPING (
ID INT NOT NULL AUTO_INCREMENT,
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
index 5f934cdba4f..a7be85cc99e 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.extensions/pom.xml
@@ -22,7 +22,7 @@
device-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml
index 78d65441e79..65d76a4ce82 100644
--- a/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml
+++ b/components/device-mgt/org.wso2.carbon.device.mgt.url.printer/pom.xml
@@ -23,7 +23,7 @@
device-mgt
org.wso2.carbon.devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml
index 01a2b614150..33b9d79a2d2 100644
--- a/components/device-mgt/pom.xml
+++ b/components/device-mgt/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml
index 62f34fec47c..675795d5513 100644
--- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml
+++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
heartbeat-management
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java
index a3920d362bc..99bfa8eba91 100644
--- a/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java
+++ b/components/heartbeat-management/io.entgra.server.bootup.heartbeat.beacon/src/main/java/io/entgra/server/bootup/heartbeat/beacon/dto/ElectedCandidate.java
@@ -19,13 +19,14 @@
package io.entgra.server.bootup.heartbeat.beacon.dto;
import java.sql.Timestamp;
+import java.util.ArrayList;
import java.util.List;
public class ElectedCandidate {
private String serverUUID;
private Timestamp timeOfElection;
- private List acknowledgedTaskList = null;
+ private List acknowledgedTaskList = new ArrayList<>();
public List getAcknowledgedTaskList() {
return acknowledgedTaskList;
diff --git a/components/heartbeat-management/pom.xml b/components/heartbeat-management/pom.xml
index 12b187f60bd..0c11fed91d3 100644
--- a/components/heartbeat-management/pom.xml
+++ b/components/heartbeat-management/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml
index 2f143b316a3..79bd49ff21a 100644
--- a/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml
+++ b/components/identity-extensions/org.wso2.carbon.device.mgt.oauth.extensions/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
identity-extensions
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
index 4ca291c2998..58c581c51a6 100644
--- a/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
+++ b/components/identity-extensions/org.wso2.carbon.identity.jwt.client.extension/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
identity-extensions
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/identity-extensions/pom.xml b/components/identity-extensions/pom.xml
index 12f156ebe63..f5f8d9e4f68 100644
--- a/components/identity-extensions/pom.xml
+++ b/components/identity-extensions/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/logger/io.entgra.notification.logger/pom.xml b/components/logger/io.entgra.notification.logger/pom.xml
new file mode 100644
index 00000000000..b0e30a6d4bb
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/pom.xml
@@ -0,0 +1,86 @@
+
+
+
+
+ 4.0.0
+
+
+ org.wso2.carbon.devicemgt
+ logger
+ 5.0.22-SNAPSHOT
+
+
+ io.entgra.notification.logger
+ Entgra - Notification Logger
+ bundle
+ http://entgra.io
+
+
+
+ org.wso2.carbon
+ org.wso2.carbon.logging
+
+
+ org.testng
+ testng
+
+
+ org.wso2.carbon.devicemgt
+ io.entgra.device.mgt.extensions.logger
+
+
+
+
+ 8
+ 8
+ UTF-8
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ Device Notification Logger Bundle
+
+ io.entgra.device.mgt.extensions.logger.*,
+ org.apache.commons.logging;version="[1.2,2)",
+ org.apache.log4j;version="[1.2,2)",
+ org.wso2.carbon.context;version="[4.4,5)
+
+
+ io.entgra.notification.logger.*
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java
new file mode 100644
index 00000000000..3becd28b9c1
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/DeviceLogContext.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package io.entgra.notification.logger;
+
+import io.entgra.device.mgt.extensions.logger.LogContext;
+
+public class DeviceLogContext extends LogContext {
+ private final String deviceName;
+ private final String operationCode;
+ private final String deviceType;
+ private final String tenantID;
+
+ private DeviceLogContext(Builder builder) {
+ this.operationCode = builder.operationCode;
+ this.deviceName = builder.deviceName;
+ this.deviceType = builder.deviceType;
+ this.tenantID = builder.tenantID;
+ }
+
+ public String getTenantID() {
+ return tenantID;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public String getOperationCode() {
+ return operationCode;
+ }
+
+ public String getDeviceType() {
+ return deviceType;
+ }
+
+
+ public static class Builder {
+ private String deviceName;
+ private String operationCode;
+ private String deviceType;
+ private String tenantID;
+
+ public Builder() {
+ }
+
+ public String getDeviceType() {
+ return deviceType;
+ }
+
+ public Builder setDeviceType(String deviceType) {
+ this.deviceType = deviceType;
+ return this;
+ }
+
+ public String getTenantID() {
+ return tenantID;
+ }
+
+ public Builder setTenantID(String tenantID) {
+ this.tenantID = tenantID;
+ return this;
+ }
+
+ public String getDeviceName() {
+ return deviceName;
+ }
+
+ public Builder setDeviceName(String deviceName) {
+ this.deviceName = deviceName;
+ return this;
+ }
+
+ public String getOperationCode() {
+ return operationCode;
+ }
+
+ public Builder setOperationCode(String operationCode) {
+ this.operationCode = operationCode;
+ return this;
+ }
+
+ public DeviceLogContext build() {
+ return new DeviceLogContext(this);
+ }
+
+ }
+}
diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java
new file mode 100644
index 00000000000..13702d570b8
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/UserLogContext.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package io.entgra.notification.logger;
+
+import io.entgra.device.mgt.extensions.logger.LogContext;
+
+public class UserLogContext extends LogContext {
+ private final String userName;
+ private final String userEmail;
+ private final String metaInfo;
+ private final String tenantID;
+
+ private UserLogContext(Builder builder) {
+ this.userEmail = builder.userEmail;
+ this.userName = builder.userName;
+ this.metaInfo = builder.metaInfo;
+ this.tenantID = builder.tenantID;
+ }
+
+ public String getTenantID() {
+ return tenantID;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public String getUserEmail() {
+ return userEmail;
+ }
+
+ public String getMetaInfo() {
+ return metaInfo;
+ }
+
+
+ public static class Builder {
+ private String userName;
+ private String userEmail;
+ private String metaInfo;
+ private String tenantID;
+
+ public Builder() {
+ }
+
+ public String getMetaInfo() {
+ return metaInfo;
+ }
+
+ public Builder setMetaInfo(String metaInfo) {
+ this.metaInfo = metaInfo;
+ return this;
+ }
+
+ public String getTenantID() {
+ return tenantID;
+ }
+
+ public Builder setTenantID(String tenantID) {
+ this.tenantID = tenantID;
+ return this;
+ }
+
+ public String getUserName() {
+ return userName;
+ }
+
+ public Builder setUserName(String userName) {
+ this.userName = userName;
+ return this;
+ }
+
+ public String getUserEmail() {
+ return userEmail;
+ }
+
+ public Builder setUserEmail(String userEmail) {
+ this.userEmail = userEmail;
+ return this;
+ }
+
+ public UserLogContext build() {
+ return new UserLogContext(this);
+ }
+
+ }
+}
diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java
new file mode 100644
index 00000000000..f1360ae6c3d
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraDeviceLoggerImpl.java
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.notification.logger.impl;
+
+
+import io.entgra.device.mgt.extensions.logger.LogContext;
+import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
+import io.entgra.notification.logger.DeviceLogContext;
+import io.entgra.notification.logger.util.MDCContextUtil;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.MDC;
+
+
+public class EntgraDeviceLoggerImpl implements EntgraLogger {
+
+ private static Log log = null;
+
+ public EntgraDeviceLoggerImpl(Class> clazz) {
+ log = LogFactory.getLog(clazz);
+ }
+
+ @Override
+ public void info(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void info(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void debug(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void debug(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void error(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void error(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void fatal(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void fatal(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void trace(Object object, LogContext logContext) {
+
+ }
+
+ @Override
+ public void trace(Object object, Throwable t, LogContext logContext) {
+
+ }
+
+ @Override
+ public void warn(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void warn(Object object, Throwable t, LogContext logContext) {
+ }
+
+ public void info(String message) {
+ }
+
+ public void info(String message, Throwable t) {
+ log.info(message, t);
+ }
+
+ @Override
+ public void info(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.info(message);
+ }
+
+
+ public void debug(String message) {
+ log.debug(message);
+ }
+
+
+ public void debug(String message, Throwable t) {
+ log.debug(message, t);
+ }
+
+ @Override
+ public void debug(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.debug(message);
+ }
+
+ public void error(String message) {
+ log.error(message);
+ }
+
+
+ public void error(String message, Throwable t) {
+ log.error(message, t);
+ }
+
+ @Override
+ public void error(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.error(message);
+ }
+
+ @Override
+ public void error(String message, Throwable t, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.error(message, t);
+ }
+
+
+ public void warn(String message) {
+ log.warn(message);
+ }
+
+
+ public void warn(String message, Throwable t) {
+ log.warn(message, t);
+ }
+
+ @Override
+ public void warn(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.warn(message);
+ }
+
+ @Override
+ public void warn(String message, Throwable t, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.warn(message, t);
+ }
+
+
+ public void trace(String message) {
+ log.trace(message);
+ }
+
+
+ public void trace(String message, Throwable t) {
+ log.trace(message, t);
+ }
+
+ @Override
+ public void trace(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.trace(message);
+ }
+
+
+ public void fatal(String message) {
+ log.fatal(message);
+ }
+
+
+ public void fatal(String message, Throwable t) {
+ log.fatal(message, t);
+ }
+
+ @Override
+ public void fatal(String message, LogContext logContext) {
+ DeviceLogContext deviceLogContext = (DeviceLogContext) logContext;
+ MDCContextUtil.populateDeviceMDCContext(deviceLogContext);
+ log.fatal(message);
+ }
+
+ @Override
+ public void debug(Object o) {
+ log.debug(o);
+ }
+
+ @Override
+ public void debug(Object o, Throwable throwable) {
+ log.debug(o, throwable);
+ }
+
+ @Override
+ public void error(Object o) {
+ log.error(o);
+ }
+
+ @Override
+ public void error(Object o, Throwable throwable) {
+ log.error(o, throwable);
+ }
+
+ @Override
+ public void fatal(Object o) {
+ log.fatal(0);
+ }
+
+ @Override
+ public void fatal(Object o, Throwable throwable) {
+ log.fatal(0, throwable);
+ }
+
+ @Override
+ public void info(Object o) {
+ log.info(o);
+ }
+
+ @Override
+ public void info(Object o, Throwable throwable) {
+ log.info(o, throwable);
+ }
+
+ @Override
+ public boolean isDebugEnabled() {
+ return log.isDebugEnabled();
+ }
+
+ @Override
+ public boolean isErrorEnabled() {
+ return log.isErrorEnabled();
+ }
+
+ @Override
+ public boolean isFatalEnabled() {
+ return log.isFatalEnabled();
+ }
+
+ @Override
+ public boolean isInfoEnabled() {
+ return log.isInfoEnabled();
+ }
+
+ @Override
+ public boolean isTraceEnabled() {
+ return log.isTraceEnabled();
+ }
+
+ @Override
+ public boolean isWarnEnabled() {
+ return log.isWarnEnabled();
+ }
+
+ @Override
+ public void trace(Object o) {
+ log.trace(o);
+ }
+
+ @Override
+ public void trace(Object o, Throwable throwable) {
+ log.trace(o, throwable);
+ }
+
+ @Override
+ public void warn(Object o) {
+ log.warn(o);
+ }
+
+ @Override
+ public void warn(Object o, Throwable throwable) {
+ log.warn(o, throwable);
+ }
+
+ @Override
+ public void clearLogContext() {
+ MDC.clear();
+ }
+}
diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java
new file mode 100644
index 00000000000..92beeabb2ff
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/impl/EntgraUserLoggerImpl.java
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.notification.logger.impl;
+
+
+import io.entgra.device.mgt.extensions.logger.LogContext;
+import io.entgra.device.mgt.extensions.logger.spi.EntgraLogger;
+import io.entgra.notification.logger.UserLogContext;
+import io.entgra.notification.logger.util.MDCContextUtil;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.log4j.MDC;
+
+
+public class EntgraUserLoggerImpl implements EntgraLogger {
+
+ private static Log log = null;
+
+ public EntgraUserLoggerImpl(Class> clazz) {
+ log = LogFactory.getLog(clazz);
+ }
+
+ @Override
+ public void info(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void info(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void debug(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void debug(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void error(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void error(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void fatal(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void fatal(Object object, Throwable t, LogContext logContext) {
+ }
+
+ @Override
+ public void trace(Object object, LogContext logContext) {
+
+ }
+
+ @Override
+ public void trace(Object object, Throwable t, LogContext logContext) {
+
+ }
+
+ @Override
+ public void warn(Object object, LogContext logContext) {
+ }
+
+ @Override
+ public void warn(Object object, Throwable t, LogContext logContext) {
+ }
+
+ public void info(String message) {
+ }
+
+ public void info(String message, Throwable t) {
+ log.info(message, t);
+ }
+
+ @Override
+ public void info(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.info(message);
+ }
+
+
+ public void debug(String message) {
+ log.debug(message);
+ }
+
+
+ public void debug(String message, Throwable t) {
+ log.debug(message, t);
+ }
+
+ @Override
+ public void debug(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.debug(message);
+ }
+
+ public void error(String message) {
+ log.error(message);
+ }
+
+
+ public void error(String message, Throwable t) {
+ log.error(message, t);
+ }
+
+ @Override
+ public void error(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.error(message);
+ }
+
+ @Override
+ public void error(String message, Throwable t, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.error(message, t);
+ }
+
+
+ public void warn(String message) {
+ log.warn(message);
+ }
+
+
+ public void warn(String message, Throwable t) {
+ log.warn(message, t);
+ }
+
+ @Override
+ public void warn(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.warn(message);
+ }
+
+ @Override
+ public void warn(String message, Throwable t, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.warn(message, t);
+ }
+
+
+ public void trace(String message) {
+ log.trace(message);
+ }
+
+
+ public void trace(String message, Throwable t) {
+ log.trace(message, t);
+ }
+
+ @Override
+ public void trace(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.trace(message);
+ }
+
+
+ public void fatal(String message) {
+ log.fatal(message);
+ }
+
+
+ public void fatal(String message, Throwable t) {
+ log.fatal(message, t);
+ }
+
+ @Override
+ public void fatal(String message, LogContext logContext) {
+ UserLogContext userLogContext = (UserLogContext) logContext;
+ MDCContextUtil.populateUserMDCContext(userLogContext);
+ log.fatal(message);
+ }
+
+ @Override
+ public void debug(Object o) {
+ log.debug(o);
+ }
+
+ @Override
+ public void debug(Object o, Throwable throwable) {
+ log.debug(o, throwable);
+ }
+
+ @Override
+ public void error(Object o) {
+ log.error(o);
+ }
+
+ @Override
+ public void error(Object o, Throwable throwable) {
+ log.error(o, throwable);
+ }
+
+ @Override
+ public void fatal(Object o) {
+ log.fatal(0);
+ }
+
+ @Override
+ public void fatal(Object o, Throwable throwable) {
+ log.fatal(0, throwable);
+ }
+
+ @Override
+ public void info(Object o) {
+ log.info(o);
+ }
+
+ @Override
+ public void info(Object o, Throwable throwable) {
+ log.info(o, throwable);
+ }
+
+ @Override
+ public boolean isDebugEnabled() {
+ return log.isDebugEnabled();
+ }
+
+ @Override
+ public boolean isErrorEnabled() {
+ return log.isErrorEnabled();
+ }
+
+ @Override
+ public boolean isFatalEnabled() {
+ return log.isFatalEnabled();
+ }
+
+ @Override
+ public boolean isInfoEnabled() {
+ return log.isInfoEnabled();
+ }
+
+ @Override
+ public boolean isTraceEnabled() {
+ return log.isTraceEnabled();
+ }
+
+ @Override
+ public boolean isWarnEnabled() {
+ return log.isWarnEnabled();
+ }
+
+ @Override
+ public void trace(Object o) {
+ log.trace(o);
+ }
+
+ @Override
+ public void trace(Object o, Throwable throwable) {
+ log.trace(o, throwable);
+ }
+
+ @Override
+ public void warn(Object o) {
+ log.warn(o);
+ }
+
+ @Override
+ public void warn(Object o, Throwable throwable) {
+ log.warn(o, throwable);
+ }
+
+ @Override
+ public void clearLogContext() {
+ MDC.clear();
+ }
+}
diff --git a/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java
new file mode 100644
index 00000000000..fd78c26dba3
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/main/java/io/entgra/notification/logger/util/MDCContextUtil.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2023, Entgra (pvt) Ltd. (http://entgra.io) All Rights Reserved.
+ *
+ * Entgra (pvt) Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.notification.logger.util;
+
+import io.entgra.notification.logger.DeviceLogContext;
+import io.entgra.notification.logger.UserLogContext;
+import org.apache.log4j.MDC;
+
+public final class MDCContextUtil {
+
+ public static void populateDeviceMDCContext(final DeviceLogContext mdcContext) {
+ if (mdcContext.getDeviceName() != null) {
+ MDC.put("DeviceName", mdcContext.getDeviceName());
+ }
+ if (mdcContext.getDeviceType() != null) {
+ MDC.put("DeviceType", mdcContext.getDeviceType());
+ }
+ if (mdcContext.getOperationCode() != null) {
+ MDC.put("OperationCode", mdcContext.getOperationCode());
+ }
+ if (mdcContext.getTenantID() != null) {
+ MDC.put("TenantId", mdcContext.getTenantID());
+ }
+ }
+
+ public static void populateUserMDCContext(final UserLogContext mdcContext) {
+ if (mdcContext.getUserName() != null) {
+ MDC.put("UserName", mdcContext.getUserName());
+ }
+ if (mdcContext.getUserEmail() != null) {
+ MDC.put("UserEmail", mdcContext.getUserEmail());
+ }
+ if (mdcContext.getMetaInfo() != null) {
+ MDC.put("MetaInfo", mdcContext.getMetaInfo());
+ }
+ if (mdcContext.getTenantID() != null) {
+ MDC.put("TenantId", mdcContext.getTenantID());
+ }
+ }
+}
+
+
diff --git a/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties b/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties
new file mode 100644
index 00000000000..b174b35e366
--- /dev/null
+++ b/components/logger/io.entgra.notification.logger/src/test/resources/log4j.properties
@@ -0,0 +1,32 @@
+#
+# Copyright 2023 Entgra Pvt. Ltd.. (http://entgra.io)
+#
+# 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.
+#
+
+#
+# This is the log4j configuration file used by Entgra Pvt. Ltd.
+#
+# IMPORTANT : Please do not remove or change the names of any
+# of the Appenders defined here. The layout pattern & log file
+# can be changed using the WSO2 Carbon Management Console, and those
+# settings will override the settings in this file.
+#
+
+log4j.rootLogger=DEBUG, STD_OUT
+
+# Redirect log messages to console
+log4j.appender.STD_OUT=org.apache.log4j.ConsoleAppender
+log4j.appender.STD_OUT.Target=System.out
+log4j.appender.STD_OUT.layout=org.apache.log4j.PatternLayout
+log4j.appender.STD_OUT.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
diff --git a/components/logger/pom.xml b/components/logger/pom.xml
new file mode 100644
index 00000000000..bc0f814449f
--- /dev/null
+++ b/components/logger/pom.xml
@@ -0,0 +1,44 @@
+
+
+
+ 4.0.0
+
+
+ carbon-devicemgt
+ org.wso2.carbon.devicemgt
+ 5.0.22-SNAPSHOT
+ ../../pom.xml
+
+
+ logger
+ pom
+ Entgra - Notification Logger Component
+ http://entgra.io
+
+
+ io.entgra.notification.logger
+
+
+
+ 8
+ 8
+ UTF-8
+
+
+
\ No newline at end of file
diff --git a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml
index adbad363b8c..d35d3b55904 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml
+++ b/components/policy-mgt/org.wso2.carbon.policy.decision.point/pom.xml
@@ -3,7 +3,7 @@
org.wso2.carbon.devicemgt
policy-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml
index 5ea8b324a79..63bf49d90e3 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml
+++ b/components/policy-mgt/org.wso2.carbon.policy.information.point/pom.xml
@@ -3,7 +3,7 @@
org.wso2.carbon.devicemgt
policy-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml
index e37d88532b7..ad871a76f38 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
policy-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
index 591761db5f1..5c12cead8d1 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.common/src/main/java/org/wso2/carbon/policy/mgt/common/PolicyAdministratorPoint.java
@@ -19,6 +19,7 @@
package org.wso2.carbon.policy.mgt.common;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.Profile;
@@ -164,5 +165,12 @@ public interface PolicyAdministratorPoint {
*/
List getPolicies(String policyType) throws PolicyManagementException;
- List getPolicyList() throws PolicyManagementException;
+ /**
+ * Returns a list of policies filtered by offset and limit
+ * @param request {@link PaginationRequest} contains offset and limit
+ * @return {@link List} - list of policies for current tenant
+ * @throws PolicyManagementException when there is an error while retrieving the policies from database or
+ * while retrieving device groups
+ */
+ List getPolicyList(PaginationRequest request) throws PolicyManagementException;
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
index be0b657d10e..00861dea8bf 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/pom.xml
@@ -22,7 +22,7 @@
org.wso2.carbon.devicemgt
policy-mgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../pom.xml
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
index 20b53f81a99..c5ae7c0a522 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyDAO.java
@@ -36,6 +36,7 @@
package org.wso2.carbon.policy.mgt.core.dao;
import org.wso2.carbon.device.mgt.common.Device;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.policy.mgt.CorrectiveAction;
import org.wso2.carbon.policy.mgt.common.Criterion;
import org.wso2.carbon.device.mgt.common.policy.mgt.DeviceGroupWrapper;
@@ -214,4 +215,13 @@ public interface PolicyDAO {
HashMap getAppliedPolicyIdsDeviceIds() throws PolicyManagerDAOException;
List getAllPolicies(String policyType) throws PolicyManagerDAOException;
+
+ /**
+ * This method is used to retrieve policies from the database based on the offset and limit
+ * sent through the PaginationRequest
+ * @param request {@link PaginationRequest} contains offset and limit
+ * @return {@link List} - list of policies for current tenant
+ * @throws PolicyManagerDAOException when there is an error while retrieving the policies from database
+ */
+ List getAllPolicies(PaginationRequest request) throws PolicyManagerDAOException;
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
index 78d5434d01e..a0a83c454d9 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/PolicyManagementDAOFactory.java
@@ -26,11 +26,14 @@ import org.wso2.carbon.device.mgt.common.exceptions.UnsupportedDatabaseEngineExc
import org.wso2.carbon.policy.mgt.core.config.datasource.DataSourceConfig;
import org.wso2.carbon.policy.mgt.core.config.datasource.JNDILookupDefinition;
import org.wso2.carbon.policy.mgt.core.dao.impl.MonitoringDAOImpl;
-import org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl;
import org.wso2.carbon.policy.mgt.core.dao.impl.ProfileDAOImpl;
import org.wso2.carbon.policy.mgt.core.dao.impl.feature.GenericFeatureDAOImpl;
import org.wso2.carbon.policy.mgt.core.dao.impl.feature.OracleServerFeatureDAOImpl;
import org.wso2.carbon.policy.mgt.core.dao.impl.feature.SQLServerFeatureDAOImpl;
+import org.wso2.carbon.policy.mgt.core.dao.impl.policy.GenericPolicyDAOImpl;
+import org.wso2.carbon.policy.mgt.core.dao.impl.policy.OraclePolicyDAOImpl;
+import org.wso2.carbon.policy.mgt.core.dao.impl.policy.PostgreSQLPolicyDAOImpl;
+import org.wso2.carbon.policy.mgt.core.dao.impl.policy.SQLServerPolicyDAOImpl;
import org.wso2.carbon.policy.mgt.core.dao.util.PolicyManagementDAOUtil;
import javax.sql.DataSource;
@@ -65,7 +68,22 @@ public class PolicyManagementDAOFactory {
}
public static PolicyDAO getPolicyDAO() {
- return new PolicyDAOImpl();
+ if (databaseEngine != null) {
+ switch (databaseEngine) {
+ case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
+ return new SQLServerPolicyDAOImpl();
+ case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
+ return new OraclePolicyDAOImpl();
+ case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
+ return new PostgreSQLPolicyDAOImpl();
+ case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
+ case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
+ return new GenericPolicyDAOImpl();
+ default:
+ throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
+ }
+ }
+ throw new IllegalStateException("Database engine has not initialized properly.");
}
public static ProfileDAO getProfileDAO() {
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java
similarity index 99%
rename from components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java
rename to components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java
index 063b5c47a89..02dc4005780 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/PolicyDAOImpl.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/AbstractPolicyDAOImpl.java
@@ -33,7 +33,7 @@
* under the License.
*/
-package org.wso2.carbon.policy.mgt.core.dao.impl;
+package org.wso2.carbon.policy.mgt.core.dao.impl.policy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -66,9 +66,12 @@ import java.util.HashMap;
import java.util.List;
import java.util.Properties;
-public class PolicyDAOImpl implements PolicyDAO {
+/**
+ * Abstract implementation of PolicyDAO which holds generic SQL queries.
+ */
+public abstract class AbstractPolicyDAOImpl implements PolicyDAO {
- private static final Log log = LogFactory.getLog(PolicyDAOImpl.class);
+ private static final Log log = LogFactory.getLog(AbstractPolicyDAOImpl.class);
@Override
public Policy addPolicy(Policy policy) throws PolicyManagerDAOException {
@@ -1838,7 +1841,7 @@ public class PolicyDAOImpl implements PolicyDAO {
}
}
- private List extractPolicyListFromDbResult(ResultSet resultSet, int tenantId) throws SQLException {
+ protected List extractPolicyListFromDbResult(ResultSet resultSet, int tenantId) throws SQLException {
List policies = new ArrayList<>();
while (resultSet.next()) {
Policy policy = new Policy();
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java
new file mode 100644
index 00000000000..d8916c95a95
--- /dev/null
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/GenericPolicyDAOImpl.java
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
+ *
+ * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
+ *
+ * Licensed under the Entgra Commercial License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://entgra.io/licenses/entgra-commercial/1.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.policy.mgt.core.dao.impl.policy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+public class GenericPolicyDAOImpl extends AbstractPolicyDAOImpl {
+
+ private static final Log log = LogFactory.getLog(GenericPolicyDAOImpl.class);
+
+ private Connection getConnection() {
+ return PolicyManagementDAOFactory.getConnection();
+ }
+
+ @Override
+ public List getAllPolicies(PaginationRequest request) throws PolicyManagerDAOException {
+ Connection conn;
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+
+ try {
+ conn = this.getConnection();
+ String query = "SELECT * " +
+ "FROM DM_POLICY " +
+ "WHERE TENANT_ID = ? " +
+ "ORDER BY ID LIMIT ?,?";
+
+ try (PreparedStatement stmt = conn.prepareStatement(query)) {
+ stmt.setInt(1, tenantId);
+ stmt.setInt(2, request.getStartIndex());
+ stmt.setInt(3, request.getRowCount());
+ try (ResultSet resultSet = stmt.executeQuery()) {
+ return this.extractPolicyListFromDbResult(resultSet, tenantId);
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while reading the policies from the database.";
+ log.error(msg, e);
+ throw new PolicyManagerDAOException(msg, e);
+ }
+ }
+}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java
new file mode 100644
index 00000000000..c8f89a906af
--- /dev/null
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/OraclePolicyDAOImpl.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
+ *
+ * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
+ *
+ * Licensed under the Entgra Commercial License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://entgra.io/licenses/entgra-commercial/1.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.policy.mgt.core.dao.impl.policy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+public class OraclePolicyDAOImpl extends AbstractPolicyDAOImpl {
+ private static final Log log = LogFactory.getLog(OraclePolicyDAOImpl.class);
+
+ private Connection getConnection() {
+ return PolicyManagementDAOFactory.getConnection();
+ }
+
+ @Override
+ public List getAllPolicies(PaginationRequest request) throws PolicyManagerDAOException {
+ Connection conn;
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+
+ try {
+ conn = this.getConnection();
+ String query = "SELECT * " +
+ "FROM DM_POLICY " +
+ "WHERE TENANT_ID = ? " +
+ "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
+
+ try (PreparedStatement stmt = conn.prepareStatement(query)) {
+ stmt.setInt(1, tenantId);
+ stmt.setInt(2, request.getStartIndex());
+ stmt.setInt(3, request.getRowCount());
+ try (ResultSet resultSet = stmt.executeQuery()) {
+ return this.extractPolicyListFromDbResult(resultSet, tenantId);
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while reading the policies from the database.";
+ log.error(msg, e);
+ throw new PolicyManagerDAOException(msg, e);
+ }
+ }
+}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java
new file mode 100644
index 00000000000..afb57d3466b
--- /dev/null
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/PostgreSQLPolicyDAOImpl.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
+ *
+ * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
+ *
+ * Licensed under the Entgra Commercial License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://entgra.io/licenses/entgra-commercial/1.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.policy.mgt.core.dao.impl.policy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+public class PostgreSQLPolicyDAOImpl extends AbstractPolicyDAOImpl {
+ private static final Log log = LogFactory.getLog(PostgreSQLPolicyDAOImpl.class);
+
+ private Connection getConnection() {
+ return PolicyManagementDAOFactory.getConnection();
+ }
+
+ @Override
+ public List getAllPolicies(PaginationRequest request) throws PolicyManagerDAOException {
+ Connection conn;
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+
+ try {
+ conn = this.getConnection();
+ String query = "SELECT * " +
+ "FROM DM_POLICY " +
+ "WHERE TENANT_ID = ? " +
+ "ORDER BY ID LIMIT ? OFFSET ?";
+
+ try (PreparedStatement stmt = conn.prepareStatement(query)) {
+ stmt.setInt(1, tenantId);
+ stmt.setInt(2, request.getRowCount());
+ stmt.setInt(3, request.getStartIndex());
+ try (ResultSet resultSet = stmt.executeQuery()) {
+ return this.extractPolicyListFromDbResult(resultSet, tenantId);
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while reading the policies from the database.";
+ log.error(msg, e);
+ throw new PolicyManagerDAOException(msg, e);
+ }
+ }
+}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java
new file mode 100644
index 00000000000..dc7e4024397
--- /dev/null
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/dao/impl/policy/SQLServerPolicyDAOImpl.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
+ *
+ * Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
+ *
+ * Licensed under the Entgra Commercial License, Version 1.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://entgra.io/licenses/entgra-commercial/1.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.policy.mgt.core.dao.impl.policy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.carbon.context.PrivilegedCarbonContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
+import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagementDAOFactory;
+import org.wso2.carbon.policy.mgt.core.dao.PolicyManagerDAOException;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.List;
+
+public class SQLServerPolicyDAOImpl extends AbstractPolicyDAOImpl {
+ private static final Log log = LogFactory.getLog(SQLServerPolicyDAOImpl.class);
+
+ private Connection getConnection() {
+ return PolicyManagementDAOFactory.getConnection();
+ }
+
+ @Override
+ public List getAllPolicies(PaginationRequest request) throws PolicyManagerDAOException {
+ Connection conn;
+ int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
+
+ try {
+ conn = this.getConnection();
+ String query = "SELECT * " +
+ "FROM DM_POLICY " +
+ "WHERE TENANT_ID = ? " +
+ "ORDER BY ID OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
+ try (PreparedStatement stmt = conn.prepareStatement(query)) {
+ stmt.setInt(1, tenantId);
+ stmt.setInt(2, request.getStartIndex());
+ stmt.setInt(3, request.getRowCount());
+ try (ResultSet resultSet = stmt.executeQuery()) {
+ return this.extractPolicyListFromDbResult(resultSet, tenantId);
+ }
+ }
+ } catch (SQLException e) {
+ String msg = "Error occurred while reading the policies from the database.";
+ log.error(msg, e);
+ throw new PolicyManagerDAOException(msg, e);
+ }
+ }
+}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java
index 3667f258c61..74e5d8e7f17 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/enforcement/PolicyEnforcementDelegatorImpl.java
@@ -44,6 +44,8 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementExcept
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.OperationMgtConstants;
+import org.wso2.carbon.device.mgt.core.operation.mgt.PolicyOperation;
+import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
import org.wso2.carbon.policy.mgt.common.PolicyEvaluationException;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
@@ -96,6 +98,7 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
*/
if (devicePolicy == null || devicePolicy.getId() != policy.getId() || updatedPolicyIds.contains
(policy.getId())) {
+ this.markPreviousPolicyBundlesRepeated(device);
this.addPolicyRevokeOperation(deviceIdentifiers);
this.addPolicyOperation(deviceIdentifiers, policy);
}
@@ -202,4 +205,29 @@ public class PolicyEnforcementDelegatorImpl implements PolicyEnforcementDelegato
throw new PolicyDelegationException(msg, e);
}
}
+
+ /**
+ * Update the previous pending policy operation's status as REPEATED
+ * @param device Device
+ * @throws PolicyDelegationException throws when getting pending operations
+ */
+ public void markPreviousPolicyBundlesRepeated(Device device) throws PolicyDelegationException {
+ DeviceManagementProviderService deviceManagerService = PolicyManagementDataHolder.getInstance().
+ getDeviceManagementService();
+ try {
+ List extends Operation> operations = deviceManagerService.getPendingOperations(device);
+ for(Operation operation : operations) {
+ String operationCode = operation.getCode();
+ if(PolicyOperation.POLICY_OPERATION_CODE.equals(operationCode) ||
+ OperationMgtConstants.OperationCodes.POLICY_REVOKE.equals(operationCode)) {
+ operation.setStatus(Operation.Status.REPEATED);
+ deviceManagerService.updateOperation(device, operation);
+ }
+ }
+ } catch (OperationManagementException e) {
+ String msg = "Error occurred while retrieving pending operations of device id "+device.getId();
+ log.error(msg, e);
+ throw new PolicyDelegationException(msg, e);
+ }
+ }
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java
index 42e34bf4907..f3249e48140 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/impl/PolicyAdministratorPointImpl.java
@@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.device.mgt.common.policy.mgt.Profile;
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
@@ -334,7 +335,7 @@ public class PolicyAdministratorPointImpl implements PolicyAdministratorPoint {
}
@Override
- public List getPolicyList() throws PolicyManagementException {
- return policyManager.getPolicyList();
+ public List getPolicyList(PaginationRequest request) throws PolicyManagementException {
+ return policyManager.getPolicyList(request);
}
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java
index b0b2c241d00..8f45900a21d 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/PolicyManager.java
@@ -20,6 +20,7 @@ package org.wso2.carbon.policy.mgt.core.mgt;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.policy.mgt.Policy;
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
import org.wso2.carbon.policy.mgt.core.mgt.bean.UpdatedPolicyDeviceListBean;
@@ -90,5 +91,12 @@ public interface PolicyManager {
List getPolicies(String type) throws PolicyManagementException;
- List getPolicyList() throws PolicyManagementException;
+ /**
+ * Returns list of policies with users, roles and groups attached to that policy
+ * @param request {@link PaginationRequest} contains offset and limit
+ * @return {@link List} - list of policies for current tenant
+ * @throws PolicyManagementException when there is an error while retrieving the policies from database or
+ * while retrieving device groups
+ */
+ List getPolicyList(PaginationRequest request) throws PolicyManagementException;
}
diff --git a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java
index 66a71a84263..1bd77a398f4 100644
--- a/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java
+++ b/components/policy-mgt/org.wso2.carbon.policy.mgt.core/src/main/java/org/wso2/carbon/policy/mgt/core/mgt/impl/PolicyManagerImpl.java
@@ -41,6 +41,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DynamicTaskContext;
+import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
@@ -1038,7 +1039,7 @@ public class PolicyManagerImpl implements PolicyManager {
.getInstance().getDeviceManagementService();
List allDevices;
try {
- allDevices = deviceManagementService.getAllDevices();
+ allDevices = deviceManagementService.getAllDevices(false);
} catch (DeviceManagementException e) {
throw new PolicyManagementException("Error occurred while getting the devices related to policy id (" +
policyId + ")", e);
@@ -1504,12 +1505,11 @@ public class PolicyManagerImpl implements PolicyManager {
}
@Override
- public List getPolicyList() throws PolicyManagementException {
-
+ public List getPolicyList(PaginationRequest request) throws PolicyManagementException {
List policyList;
try {
PolicyManagementDAOFactory.openConnection();
- policyList = policyDAO.getAllPolicies();
+ policyList = policyDAO.getAllPolicies(request);
for (Policy policy : policyList) {
policy.setRoles(policyDAO.getPolicyAppliedRoles(policy.getId()));
policy.setUsers(policyDAO.getPolicyAppliedUsers(policy.getId()));
@@ -1521,11 +1521,17 @@ public class PolicyManagerImpl implements PolicyManager {
}
Collections.sort(policyList);
} catch (PolicyManagerDAOException e) {
- throw new PolicyManagementException("Error occurred while getting all the policies.", e);
+ String msg = "Error occurred while getting all the policies.";
+ log.error(msg, e);
+ throw new PolicyManagementException(msg, e);
} catch (SQLException e) {
- throw new PolicyManagementException("Error occurred while opening a connection to the data source", e);
+ String msg = "Error occurred while opening a connection to the data source.";
+ log.error(msg, e);
+ throw new PolicyManagementException(msg, e);
} catch (GroupManagementException e) {
- throw new PolicyManagementException("Error occurred while getting device groups.", e);
+ String msg = "Error occurred while getting device groups.";
+ log.error(msg, e);
+ throw new PolicyManagementException(msg, e);
} finally {
PolicyManagementDAOFactory.closeConnection();
}
diff --git a/components/policy-mgt/pom.xml b/components/policy-mgt/pom.xml
index c7893323ec0..6709e908710 100644
--- a/components/policy-mgt/pom.xml
+++ b/components/policy-mgt/pom.xml
@@ -23,7 +23,7 @@
org.wso2.carbon.devicemgt
carbon-devicemgt
- 5.0.16-SNAPSHOT
+ 5.0.22-SNAPSHOT
../../pom.xml
diff --git a/components/task-mgt/pom.xml b/components/task-mgt/pom.xml
new file mode 100755
index 00000000000..3dd072c407e
--- /dev/null
+++ b/components/task-mgt/pom.xml
@@ -0,0 +1,39 @@
+
+
+
+
+
+ org.wso2.carbon.devicemgt
+ carbon-devicemgt
+ 5.0.22-SNAPSHOT
+ ../../pom.xml
+
+
+ 4.0.0
+ task-mgt
+ pom
+ Entgra IoT - Task Management Component
+ http://entgra.io
+
+
+ task-manager
+ task-watcher
+
+
+
\ No newline at end of file
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml b/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml
new file mode 100755
index 00000000000..e58e7e49694
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/pom.xml
@@ -0,0 +1,54 @@
+
+
+
+
+ task-manager
+ org.wso2.carbon.devicemgt
+ 5.0.22-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ io.entgra.task.mgt.common
+ bundle
+ Entgra IoT - Task Management Common
+ Entgra IoT - Task Management Common
+ https://entgra.io
+
+
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ Task Management Common Bundle
+
+ io.entgra.task.mgt.common.*
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java
new file mode 100755
index 00000000000..ece8d4dc265
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/bean/DynamicTask.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.bean;
+
+import java.util.Map;
+
+public class DynamicTask {
+
+ private int dynamicTaskId;
+ private String name;
+ private String cronExpression;
+ private boolean isEnabled;
+ private int tenantId;
+ private String taskClassName;
+ private Map properties;
+
+ public int getDynamicTaskId() {
+ return dynamicTaskId;
+ }
+
+ public void setDynamicTaskId(int dynamicTaskId) {
+ this.dynamicTaskId = dynamicTaskId;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getCronExpression() {
+ return cronExpression;
+ }
+
+ public void setCronExpression(String cronExpression) {
+ this.cronExpression = cronExpression;
+ }
+
+ public boolean isEnabled() {
+ return isEnabled;
+ }
+
+ public void setEnabled(boolean enable) {
+ isEnabled = enable;
+ }
+
+ public int getTenantId() {
+ return tenantId;
+ }
+
+ public void setTenantId(int tenantId) {
+ this.tenantId = tenantId;
+ }
+
+ public String getTaskClassName() {
+ return taskClassName;
+ }
+
+ public void setTaskClassName(String taskClassName) {
+ this.taskClassName = taskClassName;
+ }
+
+ public Map getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map properties) {
+ this.properties = properties;
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java
new file mode 100755
index 00000000000..2ffe9609642
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/constant/TaskMgtConstants.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.constant;
+
+public class TaskMgtConstants {
+ public static final class DataSourceProperties {
+ private DataSourceProperties() {
+ throw new AssertionError();
+ }
+
+ public static final String DB_CHECK_QUERY = "SELECT * FROM DM_DEVICE";
+ public static final String TASK_CONFIG_XML_NAME = "task-mgt-config.xml";
+ }
+
+ public static final class DataBaseTypes {
+ 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";
+ public static final String DB_TYPE_DB2 = "DB2";
+ public static final String DB_TYPE_H2 = "H2";
+ public static final String DB_TYPE_POSTGRESQL = "PostgreSQL";
+ }
+
+ public static final class Task {
+
+ public static final String DYNAMIC_TASK_TYPE = "DYNAMIC_TASK";
+ public static final String NAME_SEPARATOR = "_";
+ public static final String PROPERTY_KEY_COLUMN_NAME = "PROPERTY_NAME";
+ public static final String PROPERTY_VALUE_COLUMN_NAME = "PROPERTY_VALUE";
+ public static final String TENANT_ID_PROP = "__TENANT_ID_PROP__";
+ public static final String LOCAL_HASH_INDEX = "__LOCAL_HASH_INDEX__";
+ public static final String LOCAL_TASK_NAME = "__LOCAL_TASK_NAME__";
+ }
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java
new file mode 100755
index 00000000000..4c4c996c594
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/IllegalTransactionStateException.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+public class IllegalTransactionStateException extends RuntimeException {
+
+ private static final long serialVersionUID = -3151279331929070297L;
+
+ public IllegalTransactionStateException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public IllegalTransactionStateException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public IllegalTransactionStateException(String msg) {
+ super(msg);
+ }
+
+ public IllegalTransactionStateException() {
+ super();
+ }
+
+ public IllegalTransactionStateException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java
new file mode 100755
index 00000000000..9b683dba20e
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementDAOException.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+public class TaskManagementDAOException extends Exception {
+
+ public TaskManagementDAOException(String msg) {
+ super(msg);
+ }
+
+ public TaskManagementDAOException(String msg, Exception e) {
+ super(msg, e);
+ }
+
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java
new file mode 100755
index 00000000000..d9705e6438a
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskManagementException.java
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+public class TaskManagementException extends Exception {
+
+ public TaskManagementException(String msg) {
+ super(msg);
+ }
+
+ public TaskManagementException(String msg, Exception e) {
+ super(msg, e);
+ }
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java
new file mode 100755
index 00000000000..2d2f568fe23
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TaskNotFoundException.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+/**
+ * Represents the exception thrown during validating the request.
+ */
+public class TaskNotFoundException extends Exception {
+
+ public TaskNotFoundException(String message) {
+ super(message);
+ }
+
+ public TaskNotFoundException(String message, Exception ex) {
+ super(message, ex);
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java
new file mode 100755
index 00000000000..5e43237e436
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/TransactionManagementException.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+public class TransactionManagementException extends Exception {
+
+ private static final long serialVersionUID = -3151279321929070297L;
+
+ public TransactionManagementException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public TransactionManagementException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public TransactionManagementException(String msg) {
+ super(msg);
+ }
+
+ public TransactionManagementException() {
+ super();
+ }
+
+ public TransactionManagementException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java
new file mode 100755
index 00000000000..a29f954e12a
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/exception/UnsupportedDatabaseEngineException.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.exception;
+
+/**
+ * This runtime exception will be thrown if the server has configured with unsupported DB engine.
+ */
+public class UnsupportedDatabaseEngineException extends RuntimeException {
+
+ private static final long serialVersionUID = -3151279311929070297L;
+
+ public UnsupportedDatabaseEngineException(String msg, Exception nestedEx) {
+ super(msg, nestedEx);
+ }
+
+ public UnsupportedDatabaseEngineException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public UnsupportedDatabaseEngineException(String msg) {
+ super(msg);
+ }
+
+ public UnsupportedDatabaseEngineException() {
+ super();
+ }
+
+ public UnsupportedDatabaseEngineException(Throwable cause) {
+ super(cause);
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java
new file mode 100755
index 00000000000..fac557e0bd3
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.common/src/main/java/io/entgra/task/mgt/common/spi/TaskManagementService.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.common.spi;
+
+import io.entgra.task.mgt.common.exception.TaskNotFoundException;
+import io.entgra.task.mgt.common.exception.TaskManagementException;
+import io.entgra.task.mgt.common.bean.DynamicTask;
+
+import java.util.List;
+
+public interface TaskManagementService {
+
+ void init() throws TaskManagementException;
+
+ void createTask(DynamicTask dynamicTask) throws TaskManagementException;
+
+ void updateTask(int dynamicTaskId, DynamicTask dynamicTask) throws TaskManagementException, TaskNotFoundException;
+
+ void toggleTask(int dynamicTaskId, boolean isEnabled) throws TaskManagementException, TaskNotFoundException;
+
+ void deleteTask(int dynamicTaskId) throws TaskManagementException, TaskNotFoundException;
+
+ List getAllDynamicTasks() throws TaskManagementException;
+
+ DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementException;
+
+ List getActiveDynamicTasks() throws TaskManagementException;
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml b/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml
new file mode 100755
index 00000000000..d0621effa7d
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/pom.xml
@@ -0,0 +1,139 @@
+
+
+
+
+
+ org.wso2.carbon.devicemgt
+ task-manager
+ 5.0.22-SNAPSHOT
+ ../pom.xml
+
+
+ 4.0.0
+ io.entgra.task.mgt.core
+ bundle
+ Entgra IoT - Task manager Core
+ Entgra IoT - Task manager Core
+ http://entgra.io
+
+
+
+
+ org.apache.felix
+ maven-scr-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ true
+
+
+ ${project.artifactId}
+ ${project.artifactId}
+ ${carbon.device.mgt.version}
+ Task Management Core Bundle
+ io.entgra.task.mgt.core.internal
+
+ org.osgi.framework.*;version="${imp.package.version.osgi.framework}",
+ org.osgi.service.*;version="${imp.package.version.osgi.service}",
+ org.apache.commons.logging,
+ org.wso2.carbon.ndatasource.core,
+ org.w3c.dom,
+ javax.xml.bind.annotation,
+ javax.xml.bind,
+ javax.sql,
+ javax.naming,
+ io.entgra.task.mgt.common.*,
+ org.wso2.carbon.utils.*,
+ org.wso2.carbon.ntask.core.*,
+ org.wso2.carbon.ntask.common,
+ org.wso2.carbon.device.mgt.common.*,
+ org.wso2.carbon.context,
+ org.apache.commons.codec.binary;version="${commons-codec.wso2.osgi.version.range}",
+ org.apache.commons.codec.digest;version="${commons-codec.wso2.osgi.version.range}",
+ io.entgra.server.bootup.heartbeat.beacon.dto,
+ io.entgra.server.bootup.heartbeat.beacon.exception,
+ io.entgra.server.bootup.heartbeat.beacon.service,
+
+
+ !io.entgra.task.mgt.core.internal,
+ io.entgra.task.mgt.core.*
+
+
+
+
+
+
+
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi
+ provided
+
+
+ org.eclipse.osgi
+ org.eclipse.osgi.services
+ provided
+
+
+ org.wso2.carbon
+ org.wso2.carbon.ndatasource.core
+ provided
+
+
+ org.wso2.carbon.devicemgt
+ io.entgra.task.mgt.common
+ provided
+
+
+ org.wso2.carbon
+ org.wso2.carbon.logging
+ provided
+
+
+ org.wso2.carbon
+ org.wso2.carbon.utils
+ provided
+
+
+ commons-codec.wso2
+ commons-codec
+ provided
+
+
+ org.wso2.carbon.devicemgt
+ org.wso2.carbon.device.mgt.common
+ provided
+
+
+ org.wso2.carbon.devicemgt
+ io.entgra.server.bootup.heartbeat.beacon
+ provided
+
+
+
+
+ org.wso2.carbon.commons
+ org.wso2.carbon.ntask.core
+ provided
+
+
+
+
\ No newline at end of file
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java
new file mode 100755
index 00000000000..2779a07ff9e
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskConfigurationManager.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.config;
+
+import io.entgra.task.mgt.common.constant.TaskMgtConstants;
+import io.entgra.task.mgt.common.exception.TaskManagementException;
+import io.entgra.task.mgt.core.util.TaskManagementUtil;
+import org.w3c.dom.Document;
+import org.wso2.carbon.utils.CarbonUtils;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Unmarshaller;
+import java.io.File;
+
+/**
+ * Class responsible for the task mgt configuration initialization.
+ */
+public class TaskConfigurationManager {
+
+ private TaskManagementConfig taskManagementConfig;
+ private static volatile TaskConfigurationManager taskConfigurationManager;
+
+ private static final String TASK_MGT_CONFIG_PATH =
+ CarbonUtils.getCarbonConfigDirPath() + File.separator +
+ TaskMgtConstants.DataSourceProperties.TASK_CONFIG_XML_NAME;
+
+ public static TaskConfigurationManager getInstance() {
+ if (taskConfigurationManager == null) {
+ synchronized (TaskConfigurationManager.class) {
+ if (taskConfigurationManager == null) {
+ taskConfigurationManager = new TaskConfigurationManager();
+ }
+ }
+ }
+ return taskConfigurationManager;
+ }
+
+ public synchronized void initConfig() throws TaskManagementException {
+ try {
+ File taskMgtConfig = new File(TASK_MGT_CONFIG_PATH);
+ Document doc = TaskManagementUtil.convertToDocument(taskMgtConfig);
+
+ /* Un-marshaling Device Management configuration */
+ JAXBContext cdmContext = JAXBContext.newInstance(TaskManagementConfig.class);
+ Unmarshaller unmarshaller = cdmContext.createUnmarshaller();
+ //unmarshaller.setSchema(getSchema());
+ this.taskManagementConfig = (TaskManagementConfig) unmarshaller.unmarshal(doc);
+ } catch (JAXBException e) {
+ throw new TaskManagementException("Error occurred while initializing Data Source config", e);
+ }
+ }
+
+ public TaskManagementConfig getTaskManagementConfig() throws TaskManagementException {
+ if (taskManagementConfig == null) {
+ initConfig();
+ }
+ return taskManagementConfig;
+ }
+
+ public void setTaskManagementConfig(TaskManagementConfig taskManagementConfig) {
+ this.taskManagementConfig = taskManagementConfig;
+ }
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java
new file mode 100755
index 00000000000..2b3ae468ac9
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfig.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.config;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Represents Task Mgt configuration.
+ */
+@XmlRootElement(name = "TaskMgtConfiguration")
+@SuppressWarnings("unused")
+public final class TaskManagementConfig {
+
+ private TaskManagementConfigRepository taskMgtConfigRepository;
+ private boolean isTaskWatcherEnabled;
+
+ @XmlElement(name = "ManagementRepository", required = true)
+ public TaskManagementConfigRepository getTaskMgtConfigRepository() {
+ return taskMgtConfigRepository;
+ }
+
+ public void setTaskMgtConfigRepository(TaskManagementConfigRepository taskMgtConfigRepository) {
+ this.taskMgtConfigRepository = taskMgtConfigRepository;
+ }
+
+ @XmlElement(name = "TaskWatcherEnable", required = true)
+ public boolean isTaskWatcherEnabled() {
+ return isTaskWatcherEnabled;
+ }
+
+ public void setTaskWatcherEnabled(boolean enabled) {
+ this.isTaskWatcherEnabled = enabled;
+ }
+}
+
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java
new file mode 100755
index 00000000000..a81617f738f
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/TaskManagementConfigRepository.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.config;
+
+import io.entgra.task.mgt.core.config.datasource.DataSourceConfig;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Class for holding management repository data.
+ */
+@XmlRootElement(name = "ManagementRepository")
+public class TaskManagementConfigRepository {
+
+ private DataSourceConfig dataSourceConfig;
+
+ @XmlElement(name = "DataSourceConfiguration", required = true)
+ public DataSourceConfig getDataSourceConfig() {
+ return dataSourceConfig;
+ }
+
+ public void setDataSourceConfig(DataSourceConfig dataSourceConfig) {
+ this.dataSourceConfig = dataSourceConfig;
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java
new file mode 100755
index 00000000000..b4c4d9fc2d2
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/DataSourceConfig.java
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.config.datasource;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ * Class for holding data source configuration in task-mgt-config.xml at parsing with JAXB.
+ */
+@XmlRootElement(name = "DataSourceConfiguration")
+public class DataSourceConfig {
+
+ private JNDILookupDefinition jndiLookupDefinition;
+
+ @XmlElement(name = "JndiLookupDefinition", required = true)
+ public JNDILookupDefinition getJndiLookupDefinition() {
+ return jndiLookupDefinition;
+ }
+
+ public void setJndiLookupDefinition(JNDILookupDefinition jndiLookupDefinition) {
+ this.jndiLookupDefinition = jndiLookupDefinition;
+ }
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java
new file mode 100755
index 00000000000..5101af8d495
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/config/datasource/JNDILookupDefinition.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package io.entgra.task.mgt.core.config.datasource;
+
+import javax.xml.bind.annotation.*;
+import java.util.List;
+
+/**
+ * Class for hold JndiLookupDefinition of task-mgt-config.xml at parsing with JAXB.
+ */
+@XmlRootElement(name = "JndiLookupDefinition")
+public class JNDILookupDefinition {
+
+ private String jndiName;
+ private List jndiProperties;
+
+ @XmlElement(name = "Name", required = false)
+ public String getJndiName() {
+ return jndiName;
+ }
+
+ public void setJndiName(String jndiName) {
+ this.jndiName = jndiName;
+ }
+
+ @XmlElementWrapper(name = "Environment", required = false)
+ @XmlElement(name = "Property", nillable = false)
+ public List getJndiProperties() {
+ return jndiProperties;
+ }
+
+ public void setJndiProperties(List jndiProperties) {
+ this.jndiProperties = jndiProperties;
+ }
+
+ @XmlRootElement(name = "Property")
+ public static class JNDIProperty {
+
+ private String name;
+
+ private String value;
+
+ @XmlAttribute(name = "Name")
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @XmlValue
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+ }
+
+}
+
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java
new file mode 100755
index 00000000000..317870dba1a
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskDAO.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.dao;
+
+import io.entgra.task.mgt.common.bean.DynamicTask;
+import io.entgra.task.mgt.common.exception.TaskManagementDAOException;
+
+import java.util.List;
+
+/**
+ * This class represents the key operations associated with dynamic tasks.
+ */
+public interface DynamicTaskDAO {
+
+ int addTask(DynamicTask dynamicTask) throws TaskManagementDAOException;
+
+ boolean updateDynamicTask(DynamicTask dynamicTask) throws TaskManagementDAOException;
+
+ void deleteDynamicTask(int dynamicTaskId) throws TaskManagementDAOException;
+
+ DynamicTask getDynamicTaskById(int dynamicTaskId) throws TaskManagementDAOException;
+
+ List getAllDynamicTasks() throws TaskManagementDAOException;
+
+ List getActiveDynamicTasks() throws TaskManagementDAOException;
+
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java
new file mode 100755
index 00000000000..b458417298b
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/DynamicTaskPropDAO.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.dao;
+
+import io.entgra.task.mgt.common.exception.TaskManagementDAOException;
+
+import java.util.Map;
+
+/**
+ * This class represents the key operations associated with dynamic task properties.
+ */
+public interface DynamicTaskPropDAO {
+
+ void addTaskProperties(int dynamicTaskId, Map properties) throws TaskManagementDAOException;
+
+ Map getDynamicTaskProps(int dynamicTaskId) throws TaskManagementDAOException;
+
+ void updateDynamicTaskProps(int dynamicTaskId, Map properties)
+ throws TaskManagementDAOException;
+}
diff --git a/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java
new file mode 100755
index 00000000000..c8f8623777b
--- /dev/null
+++ b/components/task-mgt/task-manager/io.entgra.task.mgt.core/src/main/java/io/entgra/task/mgt/core/dao/common/TaskManagementDAOFactory.java
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2023, Entgra Pvt Ltd. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Entgra Pvt Ltd. licenses this file to you under the Apache License,
+ * Version 2.0 (the "License"); you may not use this file except
+ * in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package io.entgra.task.mgt.core.dao.common;
+
+import io.entgra.task.mgt.common.constant.TaskMgtConstants;
+import io.entgra.task.mgt.common.exception.IllegalTransactionStateException;
+import io.entgra.task.mgt.common.exception.TransactionManagementException;
+import io.entgra.task.mgt.common.exception.UnsupportedDatabaseEngineException;
+import io.entgra.task.mgt.core.config.datasource.DataSourceConfig;
+import io.entgra.task.mgt.core.config.datasource.JNDILookupDefinition;
+import io.entgra.task.mgt.core.dao.DynamicTaskDAO;
+import io.entgra.task.mgt.core.dao.DynamicTaskPropDAO;
+import io.entgra.task.mgt.core.dao.impl.DynamicTaskDAOImpl;
+import io.entgra.task.mgt.core.dao.impl.DynamicTaskPropDAOImpl;
+import io.entgra.task.mgt.core.dao.util.TaskManagementDAOUtil;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Hashtable;
+import java.util.List;
+
+public class TaskManagementDAOFactory {
+
+ private static DataSource dataSource;
+ private static String databaseEngine;
+ private static final Log log = LogFactory.getLog(TaskManagementDAOFactory.class);
+ private static ThreadLocal currentConnection = new ThreadLocal<>();
+
+
+ public static DynamicTaskDAO getDynamicTaskDAO() {
+ if (databaseEngine != null) {
+ switch (databaseEngine) {
+ case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2:
+ case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL:
+ return new DynamicTaskDAOImpl();
+ default:
+ throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
+ }
+ }
+ throw new IllegalStateException("Database engine has not initialized properly.");
+ }
+
+ public static DynamicTaskPropDAO getDynamicTaskPropDAO() {
+ if (databaseEngine != null) {
+ switch (databaseEngine) {
+ case TaskMgtConstants.DataBaseTypes.DB_TYPE_H2:
+ case TaskMgtConstants.DataBaseTypes.DB_TYPE_MYSQL:
+ return new DynamicTaskPropDAOImpl();
+ default:
+ throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
+ }
+ }
+ throw new IllegalStateException("Database engine has not initialized properly.");
+ }
+
+ public static void init(DataSourceConfig config) {
+ dataSource = resolveDataSource(config);
+ try {
+ databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
+ } catch (SQLException e) {
+ log.error("Error occurred while retrieving config.datasource connection", e);
+ }
+ }
+
+ public static void init(DataSource dtSource) {
+ dataSource = dtSource;
+ try {
+ databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
+ } catch (SQLException e) {
+ log.error("Error occurred while retrieving config.datasource connection", e);
+ }
+ }
+
+ public static void beginTransaction() throws TransactionManagementException {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ throw new IllegalTransactionStateException("A transaction is already active within the context of " +
+ "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
+ "transaction is already active is a sign of improper transaction handling");
+ }
+ try {
+ conn = dataSource.getConnection();
+ conn.setAutoCommit(false);
+ currentConnection.set(conn);
+ } catch (SQLException e) {
+ throw new TransactionManagementException("Error occurred while retrieving config.datasource connection", e);
+ }
+ }
+
+ public static void openConnection() throws SQLException {
+ Connection conn = currentConnection.get();
+ if (conn != null) {
+ throw new IllegalTransactionStateException("A transaction is already active within the context of " +
+ "this particular thread. Therefore, calling 'beginTransaction/openConnection' while another " +
+ "transaction is already active is a sign of improper transaction handling");
+ }
+ conn = dataSource.getConnection();
+ currentConnection.set(conn);
+ }
+
+ public static Connection getConnection() throws SQLException {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ return conn;
+ }
+
+ public static void commitTransaction() {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ try {
+ conn.commit();
+ } catch (SQLException e) {
+ log.error("Error occurred while committing the transaction", e);
+ }
+ }
+
+ public static void rollbackTransaction() {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ try {
+ conn.rollback();
+ } catch (SQLException e) {
+ log.warn("Error occurred while roll-backing the transaction", e);
+ }
+ }
+
+ public static void closeConnection() {
+ Connection conn = currentConnection.get();
+ if (conn == null) {
+ throw new IllegalTransactionStateException("No connection is associated with the current transaction. " +
+ "This might have ideally been caused by not properly initiating the transaction via " +
+ "'beginTransaction'/'openConnection' methods");
+ }
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.warn("Error occurred while close the connection");
+ }
+ currentConnection.remove();
+ }
+
+
+ /**
+ * Resolve data source from the data source definition
+ *
+ * @param config data source configuration
+ * @return data source resolved from the data source definition
+ */
+ private static DataSource resolveDataSource(DataSourceConfig config) {
+ DataSource dataSource = null;
+ if (config == null) {
+ throw new RuntimeException(
+ "Device Management Repository data source configuration " + "is null and " +
+ "thus, is not initialized");
+ }
+ io.entgra.task.mgt.core.config.datasource.JNDILookupDefinition jndiConfig = config.getJndiLookupDefinition();
+ if (jndiConfig != null) {
+ if (log.isDebugEnabled()) {
+ log.debug("Initializing Device Management Repository data source using the JNDI " +
+ "Lookup Definition");
+ }
+ List jndiPropertyList =
+ jndiConfig.getJndiProperties();
+ if (jndiPropertyList != null) {
+ Hashtable