Merge remote-tracking branch 'origin/tagchange' into tagchange

pull/513/head
Uddhika Ishara 2 months ago
commit a3178971e1

162
Jenkinsfile vendored

@ -0,0 +1,162 @@
pipeline {
agent {
label 'node-agent'
}
environment {
def isPendingUpstreamDependenciesExists = false
def triggeredViaPush = false
SCANNER_HOME = tool 'sonar-scanner'
JAVA_HOME = '/usr/lib/jvm/java-11-openjdk'
PATH = "${JAVA_HOME}/bin:${env.PATH}"
}
stages {
stage('Initialize Variables') {
steps {
script {
// Define swaggerEndPoint as a global variable
swaggerEndPoint = {
def matcher = (env.CHANGE_URL =~ /^(?<host>https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b)(?<path>[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/)
matcher.find()
return matcher.group('host') + '/api/v1/repos' + matcher.group('path')
}
echo "Swagger Endpoint: ${swaggerEndPoint.call()}"
}
}
}
stage('Tool Versioning') {
steps {
script {
sh 'java -version'
sh 'node --version'
sh 'npm --version'
sh 'jq --version'
}
}
}
stage('Check Environment Variables') {
steps {
script {
echo "CHANGE_ID: ${env.CHANGE_ID}"
echo "CHANGE_URL: ${env.CHANGE_URL}"
echo "CHANGE_AUTHOR: ${env.CHANGE_AUTHOR}"
echo "CHANGE_BRANCH: ${env.CHANGE_BRANCH}"
echo "JAVA_HOME: ${JAVA_HOME}"
echo "PATH: ${PATH}"
}
}
}
stage('Check SonarQube Installation') {
steps {
script {
echo "Initial JAVA_HOME: ${env.JAVA_HOME}"
echo "Initial PATH: ${env.PATH}"
withEnv(["JAVA_HOME=${env.JAVA_HOME}", "PATH=${env.JAVA_HOME}/bin:${env.PATH}"]) {
sh """
java -version
${SCANNER_HOME}/bin/sonar-scanner --version
"""
}
}
}
}
stage('Fetch Pending Upstream Dependencies') {
steps {
script {
if (env.CHANGE_ID) {
def url = swaggerEndPoint.call()
echo "Fetching from URL: ${url}"
withCredentials([usernamePassword(credentialsId: '4093a0bf-073a-4874-b929-be5b69273f4a', passwordVariable: 'password', usernameVariable: 'username')]) {
def response = sh(script: """curl -X GET "${url}" -H 'accept: application/json' -u \$username:\$password""", returnStdout: true).trim()
echo "API Response: ${response}"
isPendingUpstreamDependenciesExists = sh(script: "echo '${response}' | jq 'contains({\"labels\": [{ \"name\": \"pending upstream\"}]})'", returnStdout: true).trim().toBoolean()
}
} else {
echo '[Jenkinsfile] Triggered via a push request.'
echo '[Jenkinsfile] Skipping dependency checking.'
triggeredViaPush = true
}
}
}
}
stage('Execute Test Suites') {
steps {
script {
if (!isPendingUpstreamDependenciesExists) {
echo '[Jenkinsfile] Pending upstream dependencies do not exist.'
echo '[Jenkinsfile] Entering testing phase.'
try {
checkout scm
withCredentials([usernamePassword(credentialsId: 'builder2-deployer', passwordVariable: 'password', usernameVariable: 'username')]) {
sh """/opt/scripts/run-test.sh -u \$username -p \$password"""
}
currentBuild.result = 'SUCCESS'
message = 'Tests approved'
} catch (error) {
currentBuild.result = 'FAILURE'
message = 'Tests cannot be approved'
}
} else {
echo '[Jenkinsfile] Pending upstream dependencies exist.'
echo '[Jenkinsfile] Entering waiting phase.'
currentBuild.result = 'NOT_BUILT'
message = 'PR waiting due to pending upstream dependencies'
}
}
}
}
stage('Code Quality Check') {
steps {
script {
def projectName = "device-mgt-core-${env.CHANGE_ID}"
def projectKey = "device-mgt-core-${env.CHANGE_ID}"
withSonarQubeEnv('sonar') {
sh """
$SCANNER_HOME/bin/sonar-scanner \
-Dsonar.projectName=${projectName} \
-Dsonar.projectKey=${projectKey} \
-Dsonar.java.binaries=target
"""
}
}
}
}
stage('Report Job Status') {
steps {
script {
if (true) {
withCredentials([usernamePassword(credentialsId: '4093a0bf-073a-4874-b929-be5b69273f4a', passwordVariable: 'password', usernameVariable: 'username')]) {
def url = swaggerEndPoint.call() + '/reviews'
echo "[Jenkinsfile] Notifying pull request build status to ${url}"
def response = sh(script: """curl -X POST "${url}" -H 'accept: application/json' -H 'Content-Type: application/json' -u \$username:\$password -d '{ "body": "${message}" }'""", returnStdout: true).trim()
echo "API Response: ${response}"
}
}
def committerEmail = sh(
script: 'git --no-pager show -s --format=\'%ae\'',
returnStdout: true
).trim()
if (currentBuild.result == 'FAILURE') {
emailext(
subject: "${currentBuild.result}: Job ${env.JOB_NAME} [${env.BUILD_NUMBER}]",
body: 'Hi, Please find below.\n<pre>${BUILD_LOG_REGEX, regex="BUILD FAILURE", linesAfter=30, showTruncatedLines=false, escapeHtml=true}</pre>' + "Find more at : ${env.BUILD_URL}",
to: triggeredViaPush ? '$DEFAULT_RECIPIENTS' : committerEmail
)
}
}
}
}
}
}

@ -39,6 +39,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
import io.entgra.device.mgt.core.device.mgt.common.group.mgt.GroupManagementException;
import io.entgra.device.mgt.core.device.mgt.core.dto.GroupDetailsDTO;
@ -48,6 +49,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@ -119,13 +121,12 @@ public class GroupBasedSubscriptionManagementHelperServiceImpl implements Subscr
} else {
groupDetailsDTO = groupManagementProviderService.getGroupDetailsWithDevices(subscriptionInfo.getIdentifier(),
applicationDTO.getDeviceTypeId(), deviceSubscriptionFilterCriteria.getOwner(), deviceSubscriptionFilterCriteria.getName(),
deviceSubscriptionFilterCriteria.getDeviceStatus(), offset, limit);
List<Integer> paginatedDeviceIdsOwnByGroup = groupDetailsDTO.getDeviceIds();
deviceSubscriptionFilterCriteria.getDeviceStatus(), -1, -1);
List<Integer> nonPaginatedDeviceIdsOwnByGroup = groupDetailsDTO.getDeviceIds();
deviceSubscriptionDTOS = subscriptionDAO.getSubscriptionDetailsByDeviceIds(applicationReleaseDTO.getId(),
isUnsubscribe, tenantId, paginatedDeviceIdsOwnByGroup, dbSubscriptionStatus,
isUnsubscribe, tenantId, nonPaginatedDeviceIdsOwnByGroup, dbSubscriptionStatus,
null, deviceSubscriptionFilterCriteria.getTriggeredBy(), -1, -1);
}
deviceCount = SubscriptionManagementHelperUtil.getTotalDeviceSubscriptionCount(deviceSubscriptionDTOS,
subscriptionInfo.getDeviceSubscriptionFilterCriteria(), applicationDTO.getDeviceTypeId());
@ -146,7 +147,6 @@ public class GroupBasedSubscriptionManagementHelperServiceImpl implements Subscr
} finally {
ConnectionManagerUtil.closeDBConnection();
}
}
@Override
@ -193,12 +193,14 @@ public class GroupBasedSubscriptionManagementHelperServiceImpl implements Subscr
log.error(msg);
throw new NotFoundException(msg);
}
List<Device> devices = HelperUtil.getGroupManagementProviderService().
getAllDevicesOfGroup(subscriptionInfo.getIdentifier(), false);
List<String> deviceStatuses = Arrays.asList(EnrolmentInfo.Status.ACTIVE.name(),
EnrolmentInfo.Status.INACTIVE.name(), EnrolmentInfo.Status.UNREACHABLE.name());
List<Device> devices = HelperUtil.getGroupManagementProviderService().getAllDevicesOfGroup(subscriptionInfo.getIdentifier(), deviceStatuses, false);
List<Integer> deviceIdsOwnByGroup = devices.stream().map(Device::getId).collect(Collectors.toList());
SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.
getSubscriptionStatistic(deviceIdsOwnByGroup, isUnsubscribe, tenantId, applicationReleaseDTO.getId());
int allDeviceCount = HelperUtil.getGroupManagementProviderService().getDeviceCount(subscriptionInfo.getIdentifier());
SubscriptionStatisticDTO subscriptionStatisticDTO = subscriptionDAO.getSubscriptionStatistic
(deviceIdsOwnByGroup, isUnsubscribe, tenantId, applicationReleaseDTO.getId());
int allDeviceCount = HelperUtil.getGroupManagementProviderService().getDeviceCountWithGroup(subscriptionInfo.getIdentifier(),
applicationDAO.getApplication(applicationReleaseDTO.getUuid(), tenantId).getDeviceTypeId());
return SubscriptionManagementHelperUtil.getSubscriptionStatistics(subscriptionStatisticDTO, allDeviceCount);
} catch (ApplicationManagementDAOException e) {
String msg = "Error encountered while getting subscription statistics for group: " + subscriptionInfo.getIdentifier();

@ -40,6 +40,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationResult;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
@ -210,7 +211,8 @@ public class RoleBasedSubscriptionManagementHelperServiceImpl implements Subscri
for (String user : usersWithRole) {
PaginationRequest paginationRequest = new PaginationRequest(-1, -1);
paginationRequest.setOwner(user);
paginationRequest.setStatusList(Arrays.asList("ACTIVE", "INACTIVE", "UNREACHABLE"));
paginationRequest.setStatusList(Arrays.asList(EnrolmentInfo.Status.ACTIVE.name(),
EnrolmentInfo.Status.INACTIVE.name(),EnrolmentInfo.Status.UNREACHABLE.name()));
PaginationResult ownDeviceIds = HelperUtil.getDeviceManagementProviderService().
getAllDevicesIdList(paginationRequest);
if (ownDeviceIds.getData() != null) {

@ -39,6 +39,7 @@ import io.entgra.device.mgt.core.application.mgt.core.util.HelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.SubscriptionManagementHelperUtil;
import io.entgra.device.mgt.core.application.mgt.core.util.subscription.mgt.service.SubscriptionManagementHelperService;
import io.entgra.device.mgt.core.device.mgt.common.Device;
import io.entgra.device.mgt.core.device.mgt.common.EnrolmentInfo;
import io.entgra.device.mgt.core.device.mgt.common.PaginationRequest;
import io.entgra.device.mgt.core.device.mgt.common.PaginationResult;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.DeviceManagementException;
@ -196,7 +197,8 @@ public class UserBasedSubscriptionManagementHelperServiceImpl implements Subscri
List<Device> deviceListOwnByUser = new ArrayList<>();
PaginationRequest paginationRequest = new PaginationRequest(-1, -1);
paginationRequest.setOwner(username);
paginationRequest.setStatusList(Arrays.asList("ACTIVE", "INACTIVE", "UNREACHABLE"));
paginationRequest.setStatusList(Arrays.asList(EnrolmentInfo.Status.ACTIVE.name(),
EnrolmentInfo.Status.INACTIVE.name(),EnrolmentInfo.Status.UNREACHABLE.name()));
PaginationResult ownDeviceIds = HelperUtil.getDeviceManagementProviderService().
getAllDevicesIdList(paginationRequest);
if (ownDeviceIds.getData() != null) {

@ -24,6 +24,7 @@ public class WhiteLabelTheme {
private WhiteLabelImage logoIconImage;
private String footerText;
private String appTitle;
private String docUrl;
public String getFooterText() {
return footerText;
@ -64,4 +65,12 @@ public class WhiteLabelTheme {
public void setLogoIconImage(WhiteLabelImage logoIconImage) {
this.logoIconImage = logoIconImage;
}
public String getDocUrl() {
return docUrl;
}
public void setDocUrl(String docUrl) {
this.docUrl = docUrl;
}
}

@ -24,6 +24,7 @@ public class WhiteLabelThemeCreateRequest {
private WhiteLabelImageRequestPayload logoIcon;
private String footerText;
private String appTitle;
private String docUrl;
public WhiteLabelImageRequestPayload getFavicon() {
return favicon;
@ -64,4 +65,12 @@ public class WhiteLabelThemeCreateRequest {
public void setLogoIcon(WhiteLabelImageRequestPayload logoIcon) {
this.logoIcon = logoIcon;
}
public String getDocUrl() {
return docUrl;
}
public void setDocUrl(String docUrl) {
this.docUrl = docUrl;
}
}

@ -18,7 +18,6 @@
package io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt;
import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.documentation.DocConfiguration;
import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.whitelabel.WhiteLabelConfiguration;
import javax.xml.bind.annotation.XmlElement;
@ -27,7 +26,6 @@ import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "MetaDataConfiguration")
public class MetaDataConfiguration {
private WhiteLabelConfiguration whiteLabelConfiguration;
private DocConfiguration docConfiguration;
@XmlElement(name = "WhiteLabelConfiguration", required = true)
public WhiteLabelConfiguration getWhiteLabelConfiguration() {
@ -37,13 +35,4 @@ public class MetaDataConfiguration {
public void setWhiteLabelConfiguration(WhiteLabelConfiguration whiteLabelConfiguration) {
this.whiteLabelConfiguration = whiteLabelConfiguration;
}
@XmlElement(name = "DocConfiguration", required = true)
public DocConfiguration getDocConfiguration() {
return docConfiguration;
}
public void setDocConfiguration(DocConfiguration docConfiguration) {
this.docConfiguration = docConfiguration;
}
}

@ -1,36 +0,0 @@
/*
* Copyright (c) 2018 - 2024, 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.device.mgt.core.config.metadata.mgt.documentation;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DocConfiguration")
public class DocConfiguration {
private String docUrl;
@XmlElement(name = "DocUrl", required = true)
public String getDocUrl() {
return docUrl;
}
public void setDocUrl(String docUrl) {
this.docUrl = docUrl;
}
}

@ -26,6 +26,16 @@ public class WhiteLabelConfiguration {
private String footerText;
private String appTitle;
private WhiteLabelImages whiteLabelImages;
private String docUrl;
@XmlElement(name = "DocUrl", required = true)
public String getDocUrl() {
return docUrl;
}
public void setDocUrl(String docUrl) {
this.docUrl = docUrl;
}
@XmlElement(name = "FooterText", required = true)
public String getFooterText() {

@ -489,4 +489,15 @@ public interface GroupDAO {
throws GroupManagementDAOException;
int getDeviceCount(String groupName, int tenantId) throws GroupManagementDAOException;
/**
* Retrieves the count of devices for a specific group, device type, and tenant.
*
* @param groupName the name of the group
* @param deviceTypeId the ID of the device type (e.g., Android, iOS, Windows)
* @param tenantId the ID of the tenant
* @return the count of devices for the given group, device type, and tenant
* @throws GroupManagementDAOException if an error occurs during the retrieval of the device count
*/
int getDeviceCountWithGroup(String groupName, int deviceTypeId, int tenantId) throws GroupManagementDAOException;
}

@ -1584,4 +1584,37 @@ public abstract class AbstractGroupDAOImpl implements GroupDAO {
throw new GroupManagementDAOException(msg, e);
}
}
@Override
public int getDeviceCountWithGroup(String groupName, int deviceTypeId, int tenantId) throws GroupManagementDAOException {
int deviceCount = 0;
try {
Connection connection = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(e.ID) AS COUNT " +
"FROM DM_GROUP d " +
"INNER JOIN DM_DEVICE_GROUP_MAP m ON d.ID = m.GROUP_ID " +
"INNER JOIN DM_ENROLMENT e ON m.DEVICE_ID = e.DEVICE_ID " +
"INNER JOIN DM_DEVICE r ON e.DEVICE_ID = r.ID " +
"WHERE d.TENANT_ID = ? " +
"AND d.GROUP_NAME = ? " +
"AND r.DEVICE_TYPE_ID = ? " +
"AND e.STATUS NOT IN ('REMOVED', 'DELETED')";
try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
preparedStatement.setInt(1, tenantId);
preparedStatement.setString(2, groupName);
preparedStatement.setInt(3, deviceTypeId);
try (ResultSet resultSet = preparedStatement.executeQuery()) {
if (resultSet.next()) {
deviceCount = resultSet.getInt("COUNT");
}
}
}
return deviceCount;
} catch (SQLException e) {
String msg = "Error occurred while retrieving device count for the group: " + groupName;
log.error(msg, e);
throw new GroupManagementDAOException(msg, e);
}
}
}

@ -250,11 +250,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
Connection conn = getConnection();
String sql = "SELECT d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"d.DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"LAST_UPDATED_TIMESTAMP, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, DATE_OF_ENROLMENT) as DAYS_SINCE_ENROLLED " +
@ -291,12 +291,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"d.DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"d1.LAST_UPDATED_TIMESTAMP, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, DATE_OF_ENROLMENT) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
@ -336,11 +336,11 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"d.DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"LAST_UPDATED_TIMESTAMP, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"DATE_OF_LAST_UPDATE, " +
"TIMESTAMPDIFF(DAY, ?, ?) as DAYS_SINCE_ENROLLED " +
@ -377,12 +377,12 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
try {
conn = this.getConnection();
String sql = "select d.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"d.DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"NAME, " +
"DATE_OF_ENROLMENT, " +
"DATE_OF_LAST_UPDATE, " +
"LAST_UPDATED_TIMESTAMP, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"STATUS, " +
"TIMESTAMPDIFF(DAY, DATE_OF_LAST_UPDATE, ?) AS DAYS_USED " +
"from DM_DEVICE d, DM_ENROLMENT e " +
@ -425,9 +425,9 @@ public class GenericDeviceDAOImpl extends AbstractDeviceDAOImpl {
conn = this.getConnection();
String sql = "SELECT " +
"DM_DEVICE.ID AS DEVICE_ID, " +
"DEVICE_IDENTIFICATION, " +
"d.DEVICE_IDENTIFICATION, " +
"DESCRIPTION, " +
"LAST_UPDATED_TIMESTAMP, " +
"d.LAST_UPDATED_TIMESTAMP, " +
"DM_DEVICE.NAME AS DEVICE_NAME, " +
"DEVICE_TYPE, " +
"DM_ENROLMENT.ID AS ENROLMENT_ID, " +

@ -18,6 +18,7 @@
package io.entgra.device.mgt.core.device.mgt.core.internal;
import io.entgra.device.mgt.core.device.mgt.common.authorization.GroupAccessAuthorizationService;
import io.entgra.device.mgt.core.device.mgt.common.exceptions.MetadataManagementException;
import io.entgra.device.mgt.core.device.mgt.common.metadata.mgt.DeviceStatusManagementService;
import io.entgra.device.mgt.core.device.mgt.core.authorization.GroupAccessAuthorizationServiceImpl;
import io.entgra.device.mgt.core.device.mgt.core.metadata.mgt.DeviceStatusManagementServiceImpl;
@ -335,15 +336,14 @@ public class DeviceManagementServiceComponent {
bundleContext.registerService(MetadataManagementService.class.getName(), metadataManagementService, null);
/* Registering Whitelabel Service */
try {
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);
} catch (MetadataManagementException e) {
log.error("Error occurred while initializing the white label management service", e);
}
/* Registering DeviceState Filter Service */
DeviceStatusManagementService deviceStatusManagementService = new DeviceStatusManagementServiceImpl();

@ -60,8 +60,53 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
private final MetadataDAO metadataDAO;
public WhiteLabelManagementServiceImpl() {
public WhiteLabelManagementServiceImpl() throws MetadataManagementException {
this.metadataDAO = MetadataManagementDAOFactory.getMetadataDAO();
initializeWhiteLabelThemes();
}
/**
* Initializes white label theme for a tenant by retrieving white label metadata and updating it if necessary.
* If the white label metadata is found and the DocUrl is missing,it updates the metadata with the default value
* for DocUrl.
*
* @throws MetadataManagementException if an error occurs while managing metadata or transactions.
*/
private void initializeWhiteLabelThemes() throws MetadataManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
WhiteLabelTheme defaultTheme = getDefaultWhiteLabelTheme();
Metadata whiteLabelMetadata = getWhiteLabelMetaData(tenantId);
if (whiteLabelMetadata != null) {
WhiteLabelTheme whiteLabelTheme = new Gson().fromJson(whiteLabelMetadata.getMetaValue(),
WhiteLabelTheme.class);
if (whiteLabelTheme.getDocUrl() == null) {
whiteLabelTheme.setDocUrl(defaultTheme.getDocUrl());
Metadata updatedMetadata = constructWhiteLabelThemeMetadata(whiteLabelTheme);
try {
MetadataManagementDAOFactory.beginTransaction();
metadataDAO.updateMetadata(tenantId, updatedMetadata);
MetadataManagementDAOFactory.commitTransaction();
if (log.isDebugEnabled()) {
log.debug("WhiteLabel theme's DocUrl was missing and has been updated to the default value " +
"for tenant: " + tenantId);
}
} catch (MetadataManagementDAOException e) {
MetadataManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while fetching white label metadata for tenant: " + tenantId;
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Transaction failed while updating white label theme for tenant: "
+ tenantId;
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} finally {
MetadataManagementDAOFactory.closeConnection();
}
}
} else {
addDefaultWhiteLabelThemeIfNotExist(tenantId);
}
}
@Override
@ -128,7 +173,7 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
*/
private FileResponse getImageFileResponseFromUrl(String url) throws IOException, NotFoundException {
FileResponse fileResponse = new FileResponse();
try(CloseableHttpClient client = HttpClients.createDefault()) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet imageGetRequest = new HttpGet(url);
HttpResponse response = client.execute(imageGetRequest);
InputStream imageStream = response.getEntity().getContent();
@ -183,6 +228,16 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
WhiteLabelStorageUtil.deleteWhiteLabelImageForTenantIfExists(tenantId);
}
/**
* Get default metaDataConfiguration DocUrl from config
*/
private String getDefaultDocUrl() {
MetaDataConfiguration metaDataConfiguration = DeviceConfigurationManager.getInstance().
getDeviceManagementConfig().getMetaDataConfiguration();
WhiteLabelConfiguration whiteLabelConfiguration = metaDataConfiguration.getWhiteLabelConfiguration();
return whiteLabelConfiguration.getDocUrl();
}
/**
* Construct and return default whitelabel detail bean {@link WhiteLabelImage}
*/
@ -193,11 +248,13 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
WhiteLabelImage logo = constructDefaultLogoImage();
WhiteLabelImage logoIcon = constructDefaultLogoIconImage();
WhiteLabelTheme defaultTheme = new WhiteLabelTheme();
String docUrl = getDefaultDocUrl();
defaultTheme.setFooterText(footerText);
defaultTheme.setAppTitle(appTitle);
defaultTheme.setLogoImage(logo);
defaultTheme.setLogoIconImage(logoIcon);
defaultTheme.setFaviconImage(favicon);
defaultTheme.setDocUrl(docUrl);
return defaultTheme;
}
@ -386,6 +443,7 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
whiteLabelTheme.setLogoIconImage(logoIconImage);
whiteLabelTheme.setFooterText(whiteLabelThemeCreateRequest.getFooterText());
whiteLabelTheme.setAppTitle(whiteLabelThemeCreateRequest.getAppTitle());
whiteLabelTheme.setDocUrl(whiteLabelThemeCreateRequest.getDocUrl());
return whiteLabelTheme;
}
@ -418,6 +476,38 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
return metadata;
}
/**
* updates the given WhiteLabelTheme with default value for docUrl
*
* @param whiteLabelTheme the WhiteLabelTheme to be updated with defaults if necessary.
* @param tenantId the ID of the tenant whose metadata is being updated.
* @throws MetadataManagementException exception for an error occurs during the update or transaction commit.
*/
private void updateWhiteLabelThemeWithDefaults(WhiteLabelTheme whiteLabelTheme, int tenantId)
throws MetadataManagementException {
WhiteLabelTheme defaultTheme = getDefaultWhiteLabelTheme();
if (whiteLabelTheme.getDocUrl() == null) {
whiteLabelTheme.setDocUrl(defaultTheme.getDocUrl());
}
Metadata updatedMetadata = constructWhiteLabelThemeMetadata(whiteLabelTheme);
try {
MetadataManagementDAOFactory.beginTransaction();
metadataDAO.updateMetadata(tenantId, updatedMetadata);
MetadataManagementDAOFactory.commitTransaction();
} catch (MetadataManagementDAOException e) {
MetadataManagementDAOFactory.rollbackTransaction();
String msg = "Error occurred while updating metadata for tenant: " + tenantId;
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} catch (TransactionManagementException e) {
String msg = "Error occurred while committing the transaction for tenant: " + tenantId;
log.error(msg, e);
throw new MetadataManagementException(msg, e);
} finally {
MetadataManagementDAOFactory.closeConnection();
}
}
@Override
public WhiteLabelTheme getWhiteLabelTheme(String tenantDomain) throws MetadataManagementException, DeviceManagementException {
int tenantId = DeviceManagerUtil.getTenantId(tenantDomain);
@ -435,17 +525,22 @@ public class WhiteLabelManagementServiceImpl implements WhiteLabelManagementServ
throw new MetadataManagementException(msg);
}
}
return new Gson().fromJson(metadata.getMetaValue(), WhiteLabelTheme.class);
WhiteLabelTheme whiteLabelTheme = new Gson().fromJson(metadata.getMetaValue(), WhiteLabelTheme.class);
if (whiteLabelTheme.getDocUrl() == null) {
updateWhiteLabelThemeWithDefaults(whiteLabelTheme, tenantId);
}
return whiteLabelTheme;
}
/**
* Load White label Meta Data for given tenant Id.
*
* @param tenantId Id of the tenant
* @return {@link Metadata}
* @throws MetadataManagementException if an error occurred while getting Meta-Data info from Database for a
* given tenant ID.
*/
private Metadata getWhiteLabelMetaData (int tenantId) throws MetadataManagementException {
private Metadata getWhiteLabelMetaData(int tenantId) throws MetadataManagementException {
try {
MetadataManagementDAOFactory.openConnection();
return metadataDAO.getMetadata(tenantId, MetadataConstants.WHITELABEL_META_KEY);

@ -1176,9 +1176,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
public double generateCost(List<Device> allDevices, Timestamp startDate, Timestamp endDate, Cost tenantCost, List<Device> deviceStatusNotAvailable, double totalCost) throws DeviceManagementException {
List<DeviceStatus> deviceStatus;
try {
for (Device device : allDevices) {
long dateDiff = 0;
deviceStatus = getDeviceStatusHistoryInsideTransaction(device, null, endDate, true);
int tenantId = this.getTenantId();
deviceStatus = deviceStatusDAO.getStatus(device.getId(), tenantId, null, endDate, true);
if (device.getEnrolmentInfo().getDateOfEnrolment() < startDate.getTime()) {
if (!deviceStatus.isEmpty() && (String.valueOf(deviceStatus.get(0).getStatus()).equals("REMOVED")
|| String.valueOf(deviceStatus.get(0).getStatus()).equals("DELETED"))) {
@ -1221,6 +1223,11 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
deviceStatusNotAvailable.add(device);
}
}
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred in retrieving status history for a device in billing.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return totalCost;
}
@ -2233,33 +2240,6 @@ public class DeviceManagementProviderServiceImpl implements DeviceManagementProv
}
}
/*
This is just to avoid breaking the billing functionality as it required to call getDeviceStatusHistory method
without transaction handling.
*/
private List<DeviceStatus> getDeviceStatusHistoryInsideTransaction(
Device device, Date fromDate, Date toDate, boolean billingStatus)
throws DeviceManagementException {
if (log.isDebugEnabled()) {
log.debug("get status history of device: " + device.getDeviceIdentifier());
}
try {
DeviceManagementDAOFactory.getConnection();
int tenantId = this.getTenantId();
return deviceStatusDAO.getStatus(device.getId(), tenantId, fromDate, toDate, billingStatus);
} catch (DeviceManagementDAOException e) {
String msg = "Error occurred in retrieving status history for device :" + device.getDeviceIdentifier();
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.info(msg, e);
throw new DeviceManagementException(msg, e);
} finally {
DeviceManagementDAOFactory.closeConnection();
}
}
@Override
public List<DeviceStatus> getDeviceStatusHistory(Device device, Date fromDate, Date toDate, boolean billingStatus) throws DeviceManagementException {
if (log.isDebugEnabled()) {

@ -392,4 +392,13 @@ public interface GroupManagementProviderService {
int getDeviceCount(String groupName) throws GroupManagementException;
/**
* Retrieves the count of devices for a specific group and device type.
*
* @param groupName the name of the group
* @param deviceTypeId the ID of the device type (e.g., Android, iOS, Windows)
* @return the count of devices for the given group and device type
* @throws GroupManagementException if an error occurs during the retrieval of the device count
*/
int getDeviceCountWithGroup(String groupName, int deviceTypeId) throws GroupManagementException;
}

@ -1746,4 +1746,23 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
GroupManagementDAOFactory.closeConnection();
}
}
@Override
public int getDeviceCountWithGroup(String groupName,int deviceTypeId) throws GroupManagementException {
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
try {
GroupManagementDAOFactory.openConnection();
return groupDAO.getDeviceCountWithGroup(groupName,deviceTypeId, tenantId);
} catch (SQLException e) {
String msg = "SQL error occurred while retrieving device count.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} catch (GroupManagementDAOException e) {
String msg = "DAO error occurred while retrieving device count.";
log.error(msg, e);
throw new GroupManagementException(msg, e);
} finally {
GroupManagementDAOFactory.closeConnection();
}
}
}

@ -20,7 +20,7 @@ package io.entgra.device.mgt.core.device.mgt.core.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.MetaDataConfiguration;
import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.documentation.DocConfiguration;
import io.entgra.device.mgt.core.device.mgt.core.config.metadata.mgt.whitelabel.WhiteLabelConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
@ -1289,7 +1289,7 @@ public final class DeviceManagerUtil {
*/
public static String getDocUrl() {
DeviceManagementConfig deviceManagementConfig = DeviceConfigurationManager.getInstance().getDeviceManagementConfig();
DocConfiguration docConfiguration = deviceManagementConfig.getMetaDataConfiguration().getDocConfiguration();
return docConfiguration.getDocUrl();
WhiteLabelConfiguration whiteLabelConfig = deviceManagementConfig.getMetaDataConfiguration().getWhiteLabelConfiguration();
return whiteLabelConfig.getDocUrl();
}
}

@ -160,9 +160,9 @@
</RemoteSessionConfiguration>
<DefaultGroupsConfiguration>BYOD,COPE</DefaultGroupsConfiguration>
<MetaDataConfiguration>
<DocConfiguration>
<WhiteLabelConfiguration>
<DocUrl>https://docs.entgra.io/uem/6.0.0</DocUrl>
</DocConfiguration>
</WhiteLabelConfiguration>
</MetaDataConfiguration>
</DeviceMgtConfiguration>

@ -343,7 +343,7 @@
<Scope>and:ops:lock-devices</Scope>
<Scope>and:ops:unlock-devices</Scope>
<Scope>and:ops:location</Scope>
<Scope>and:ops:clear-password</Scope>
<Scope>and:ops:clear-pwd</Scope>
<Scope>and:ops:control-camera</Scope>
<Scope>and:ops:enterprise-wipe</Scope>
<Scope>and:ops:wipe</Scope>
@ -356,7 +356,7 @@
<Scope>and:ops:send-app-restrictions</Scope>
<Scope>and:ops:file-transfer</Scope>
<Scope>and:ops:set-webclip</Scope>
<Scope>and:ops:password-policy</Scope>
<Scope>and:ops:pwd-policy</Scope>
<Scope>and:ops:change-lock-code</Scope>
<Scope>and:ops:upgrade-firmware</Scope>
<Scope>and:ops:send-notif</Scope>

@ -200,10 +200,8 @@
<DefaultLogoIconName>icon.png</DefaultLogoIconName>
<DefaultImagesLocation>default</DefaultImagesLocation>
</WhiteLabelImages>
</WhiteLabelConfiguration>
<DocConfiguration>
<DocUrl>https://docs.entgra.io/uem/6.0.0</DocUrl>
</DocConfiguration>
</WhiteLabelConfiguration>
</MetaDataConfiguration>
<OperationTimeoutConfigurations>

@ -345,7 +345,7 @@
<Scope>and:ops:lock-devices</Scope>
<Scope>and:ops:unlock-devices</Scope>
<Scope>and:ops:location</Scope>
<Scope>and:ops:clear-password</Scope>
<Scope>and:ops:clear-pwd</Scope>
<Scope>and:ops:control-camera</Scope>
<Scope>and:ops:enterprise-wipe</Scope>
<Scope>and:ops:wipe</Scope>
@ -358,7 +358,7 @@
<Scope>and:ops:send-app-restrictions</Scope>
<Scope>and:ops:file-transfer</Scope>
<Scope>and:ops:set-webclip</Scope>
<Scope>and:ops:password-policy</Scope>
<Scope>and:ops:pwd-policy</Scope>
<Scope>and:ops:change-lock-code</Scope>
<Scope>and:ops:upgrade-firmware</Scope>
<Scope>and:ops:send-notif</Scope>

@ -348,12 +348,10 @@
<DefaultLogoIconName>icon.png</DefaultLogoIconName>
<DefaultImagesLocation>default</DefaultImagesLocation>
</WhiteLabelImages>
</WhiteLabelConfiguration>
<DocConfiguration>
{% if product_conf is defined %}
<DocUrl>https://docs.entgra.io/uem/{{product_conf.server_version}}</DocUrl>
{% endif %}
</DocConfiguration>
</WhiteLabelConfiguration>
</MetaDataConfiguration>
<OperationTimeoutConfigurations>
<OperationTimeouts>

Loading…
Cancel
Save