mirror of
https://repository.entgra.net/community/device-mgt-core.git
synced 2025-10-06 02:01:45 +00:00
Merge branch 'master' of https://github.com/wso2/carbon-device-mgt into transport
This commit is contained in:
commit
34f1f4dfe2
@ -288,6 +288,19 @@ public class CertificateGenerator {
|
|||||||
return lookUpCertificate;
|
return lookUpCertificate;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public CertificateResponse verifyCertificateDN(String distinguishedName) throws KeystoreException {
|
||||||
|
CertificateResponse lookUpCertificate = null;
|
||||||
|
KeyStoreReader keyStoreReader = new KeyStoreReader();
|
||||||
|
if (distinguishedName != null && !distinguishedName.isEmpty()) {
|
||||||
|
String[] dnSplits = distinguishedName.split("/CN=");
|
||||||
|
if (dnSplits != null) {
|
||||||
|
String commonNameExtracted = dnSplits[dnSplits.length-1];
|
||||||
|
lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return lookUpCertificate;
|
||||||
|
}
|
||||||
|
|
||||||
public static String getCommonName(X509Certificate requestCertificate) {
|
public static String getCommonName(X509Certificate requestCertificate) {
|
||||||
String distinguishedName = requestCertificate.getSubjectDN().getName();
|
String distinguishedName = requestCertificate.getSubjectDN().getName();
|
||||||
if(distinguishedName != null && !distinguishedName.isEmpty()) {
|
if(distinguishedName != null && !distinguishedName.isEmpty()) {
|
||||||
|
|||||||
@ -56,6 +56,8 @@ public interface CertificateManagementService {
|
|||||||
|
|
||||||
public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException;
|
public CertificateResponse verifyPEMSignature(X509Certificate requestCertificate) throws KeystoreException;
|
||||||
|
|
||||||
|
public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException;
|
||||||
|
|
||||||
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException;
|
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException;
|
||||||
|
|
||||||
String extractChallengeToken(X509Certificate certificate);
|
String extractChallengeToken(X509Certificate certificate);
|
||||||
|
|||||||
@ -108,6 +108,10 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe
|
|||||||
return certificateGenerator.verifyPEMSignature(requestCertificate);
|
return certificateGenerator.verifyPEMSignature(requestCertificate);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override public CertificateResponse verifySubjectDN(String requestDN) throws KeystoreException {
|
||||||
|
return certificateGenerator.verifyCertificateDN(requestDN);
|
||||||
|
}
|
||||||
|
|
||||||
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {
|
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {
|
||||||
return certificateGenerator.extractCertificateFromSignature(headerSignature);
|
return certificateGenerator.extractCertificateFromSignature(headerSignature);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -64,7 +64,8 @@
|
|||||||
</Private-Package>
|
</Private-Package>
|
||||||
<Export-Package>
|
<Export-Package>
|
||||||
org.wso2.carbon.device.mgt.analytics.dashboard,
|
org.wso2.carbon.device.mgt.analytics.dashboard,
|
||||||
org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception
|
org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception,
|
||||||
|
org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean
|
||||||
</Export-Package>
|
</Export-Package>
|
||||||
<Import-Package>
|
<Import-Package>
|
||||||
org.osgi.framework,
|
org.osgi.framework,
|
||||||
|
|||||||
@ -18,12 +18,12 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.analytics.dashboard;
|
package org.wso2.carbon.device.mgt.analytics.dashboard;
|
||||||
|
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterException;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.*;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* To be updated...
|
* To be updated...
|
||||||
@ -31,62 +31,56 @@ import java.util.Map;
|
|||||||
public interface GadgetDataService {
|
public interface GadgetDataService {
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getTotalDeviceCount() throws SQLException;
|
DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getActiveDeviceCount() throws SQLException;
|
DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getInactiveDeviceCount() throws SQLException;
|
DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getRemovedDeviceCount() throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getNonCompliantDeviceCount() throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
|
||||||
int getUnmonitoredDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
throws InvalidParameterException, SQLException;
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getDeviceCount(Map<String, Object> filters) throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws SQLException;
|
PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
@SuppressWarnings("unused")
|
|
||||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
|
||||||
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
|
||||||
int startIndex, int resultCount) throws InvalidParameterException, SQLException;
|
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters, int startIndex, int resultCount)
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
throws InvalidParameterException, SQLException;
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws SQLException;
|
List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,13 +16,13 @@
|
|||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl;
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||||
|
|
||||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAO;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterException;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
|
|
||||||
import java.sql.Connection;
|
import java.sql.Connection;
|
||||||
@ -30,114 +30,47 @@ import java.sql.PreparedStatement;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.LinkedHashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceDAO {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getTotalDeviceCount() throws SQLException {
|
public DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException {
|
||||||
return this.getDeviceCount(null);
|
int totalDeviceCount;
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getActiveDeviceCount() throws SQLException {
|
|
||||||
Map<String, Object> filters = new HashMap<>();
|
|
||||||
filters.put("CONNECTIVITY_STATUS", "ACTIVE");
|
|
||||||
return this.getDeviceCount(filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getInactiveDeviceCount() throws SQLException {
|
|
||||||
Map<String, Object> filters = new HashMap<>();
|
|
||||||
filters.put("CONNECTIVITY_STATUS", "INACTIVE");
|
|
||||||
return this.getDeviceCount(filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getRemovedDeviceCount() throws SQLException {
|
|
||||||
Map<String, Object> filters = new HashMap<>();
|
|
||||||
filters.put("CONNECTIVITY_STATUS", "REMOVED");
|
|
||||||
return this.getDeviceCount(filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getNonCompliantDeviceCount() throws SQLException {
|
|
||||||
Map<String, Object> filters = new HashMap<>();
|
|
||||||
filters.put("IS_COMPLIANT", 0);
|
|
||||||
return this.getDeviceCount(filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getUnmonitoredDeviceCount() throws SQLException {
|
|
||||||
Map<String, Object> filters = new HashMap<>();
|
|
||||||
filters.put("POLICY_ID", -1);
|
|
||||||
return this.getDeviceCount(filters);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
|
||||||
throws InvalidParameterException, SQLException {
|
|
||||||
|
|
||||||
if (startIndex < 0) {
|
|
||||||
throw new InvalidParameterException("Start index (startIndex) should be " +
|
|
||||||
"equal to 0 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resultCount < 5) {
|
|
||||||
throw new InvalidParameterException("Result count (resultCount) should be " +
|
|
||||||
"equal to 5 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Connection con;
|
|
||||||
PreparedStatement stmt = null;
|
|
||||||
ResultSet rs = null;
|
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
|
||||||
List<Map<String, Object>> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
|
|
||||||
int totalRecordsCount = 0;
|
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
totalDeviceCount = this.getFilteredDeviceCount(null);
|
||||||
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
} catch (InvalidParameterValueException e) {
|
||||||
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?";
|
throw new AssertionError(e);
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
stmt.setInt(2, startIndex);
|
|
||||||
stmt.setInt(3, resultCount);
|
|
||||||
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
Map<String, Object> filteredNonCompliantDeviceCountByFeature;
|
|
||||||
while (rs.next()) {
|
|
||||||
filteredNonCompliantDeviceCountByFeature = new HashMap<>();
|
|
||||||
filteredNonCompliantDeviceCountByFeature.put("FEATURE_CODE", rs.getString("FEATURE_CODE"));
|
|
||||||
filteredNonCompliantDeviceCountByFeature.put("DEVICE_COUNT", rs.getInt("DEVICE_COUNT"));
|
|
||||||
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
|
|
||||||
}
|
|
||||||
// fetching total records count
|
|
||||||
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
|
|
||||||
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?)";
|
|
||||||
|
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
while (rs.next()) {
|
|
||||||
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
|
||||||
}
|
}
|
||||||
PaginationResult paginationResult = new PaginationResult();
|
|
||||||
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
DeviceCountByGroupEntry deviceCountByGroupEntry = new DeviceCountByGroupEntry();
|
||||||
paginationResult.setRecordsTotal(totalRecordsCount);
|
deviceCountByGroupEntry.setGroup("total");
|
||||||
return paginationResult;
|
deviceCountByGroupEntry.setDisplayNameForGroup("Total");
|
||||||
|
deviceCountByGroupEntry.setDeviceCount(totalDeviceCount);
|
||||||
|
|
||||||
|
return deviceCountByGroupEntry;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getDeviceCount(Map<String, Object> filters) throws SQLException {
|
@Override
|
||||||
|
public DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
int filteredDeviceCount = this.getFilteredDeviceCount(filterSet);
|
||||||
|
|
||||||
|
DeviceCountByGroupEntry deviceCountByGroupEntry = new DeviceCountByGroupEntry();
|
||||||
|
deviceCountByGroupEntry.setGroup("filtered");
|
||||||
|
deviceCountByGroupEntry.setDisplayNameForGroup("Filtered");
|
||||||
|
deviceCountByGroupEntry.setDeviceCount(filteredDeviceCount);
|
||||||
|
|
||||||
|
return deviceCountByGroupEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getFilteredDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
@ -179,13 +112,16 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDeviceCount;
|
return filteredDeviceCount;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters)
|
@Override
|
||||||
throws InvalidParameterException, SQLException {
|
public DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
throw new InvalidParameterException("nonCompliantFeatureCode should not be either null or empty.");
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
@ -193,7 +129,8 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
int filteredDeviceCount = 0;
|
int filteredDeviceCount = 0;
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
// appending filters to support advanced filtering options
|
// appending filters to support advanced filtering options
|
||||||
// [1] appending filter columns
|
// [1] appending filter columns
|
||||||
if (filters != null && filters.size() > 0) {
|
if (filters != null && filters.size() > 0) {
|
||||||
@ -225,15 +162,98 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
} finally {
|
} finally {
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
}
|
}
|
||||||
return filteredDeviceCount;
|
|
||||||
|
DeviceCountByGroupEntry deviceCountByGroupEntry = new DeviceCountByGroupEntry();
|
||||||
|
deviceCountByGroupEntry.setGroup("feature-non-compliant-and-filtered");
|
||||||
|
deviceCountByGroupEntry.setDisplayNameForGroup("Feature-non-compliant-and-filtered");
|
||||||
|
deviceCountByGroupEntry.setDeviceCount(filteredDeviceCount);
|
||||||
|
|
||||||
|
return deviceCountByGroupEntry;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws SQLException {
|
@Override
|
||||||
|
public List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException {
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
|
List<DeviceCountByGroupEntry> deviceCountsByConnectivityStatuses = new ArrayList<>();
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql = "SELECT CONNECTIVITY_STATUS, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 " +
|
||||||
|
"WHERE TENANT_ID = ? GROUP BY CONNECTIVITY_STATUS";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry deviceCountByConnectivityStatus;
|
||||||
|
while (rs.next()) {
|
||||||
|
deviceCountByConnectivityStatus = new DeviceCountByGroupEntry();
|
||||||
|
deviceCountByConnectivityStatus.setGroup(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
deviceCountByConnectivityStatus.setDisplayNameForGroup(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
deviceCountByConnectivityStatus.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
deviceCountsByConnectivityStatuses.add(deviceCountByConnectivityStatus);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
return deviceCountsByConnectivityStatuses;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException {
|
||||||
|
// getting non-compliant device count
|
||||||
|
DeviceCountByGroupEntry nonCompliantDeviceCount = new DeviceCountByGroupEntry();
|
||||||
|
nonCompliantDeviceCount.setGroup(GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT);
|
||||||
|
nonCompliantDeviceCount.setDisplayNameForGroup("Non-compliant");
|
||||||
|
nonCompliantDeviceCount.setDeviceCount(getNonCompliantDeviceCount());
|
||||||
|
|
||||||
|
// getting unmonitored device count
|
||||||
|
DeviceCountByGroupEntry unmonitoredDeviceCount = new DeviceCountByGroupEntry();
|
||||||
|
unmonitoredDeviceCount.setGroup(GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED);
|
||||||
|
unmonitoredDeviceCount.setDisplayNameForGroup("Unmonitored");
|
||||||
|
unmonitoredDeviceCount.setDeviceCount(getUnmonitoredDeviceCount());
|
||||||
|
|
||||||
|
List<DeviceCountByGroupEntry> deviceCountsByPotentialVulnerabilities = new ArrayList<>();
|
||||||
|
deviceCountsByPotentialVulnerabilities.add(nonCompliantDeviceCount);
|
||||||
|
deviceCountsByPotentialVulnerabilities.add(unmonitoredDeviceCount);
|
||||||
|
|
||||||
|
return deviceCountsByPotentialVulnerabilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getNonCompliantDeviceCount() throws SQLException {
|
||||||
|
FilterSet filterSet = new FilterSet();
|
||||||
|
filterSet.setPotentialVulnerability(GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT);
|
||||||
|
try {
|
||||||
|
return this.getFilteredDeviceCount(filterSet);
|
||||||
|
} catch (InvalidParameterValueException e) {
|
||||||
|
throw new AssertionError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int getUnmonitoredDeviceCount() throws SQLException {
|
||||||
|
FilterSet filterSet = new FilterSet();
|
||||||
|
filterSet.setPotentialVulnerability(GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED);
|
||||||
|
try {
|
||||||
|
return this.getFilteredDeviceCount(filterSet);
|
||||||
|
} catch (InvalidParameterValueException e) {
|
||||||
|
throw new AssertionError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DeviceCountByGroupEntry> filteredDeviceCountsByPlatforms = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql, advancedSqlFiltering = "";
|
String sql, advancedSqlFiltering = "";
|
||||||
@ -263,8 +283,13 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredDeviceCountByPlatform;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
|
filteredDeviceCountByPlatform = new DeviceCountByGroupEntry();
|
||||||
|
filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase());
|
||||||
|
filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
@ -272,19 +297,22 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDeviceCountsByPlatforms;
|
return filteredDeviceCountsByPlatforms;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
@Override
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException {
|
public List<DeviceCountByGroupEntry>
|
||||||
|
getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
throw new InvalidParameterException("Non-compliant feature code (nonCompliantFeatureCode) " +
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
"should not be either null or empty.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
|
List<DeviceCountByGroupEntry> filteredDeviceCountsByPlatforms = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql, advancedSqlFiltering = "";
|
String sql, advancedSqlFiltering = "";
|
||||||
@ -315,8 +343,13 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredDeviceCountByPlatform;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
|
filteredDeviceCountByPlatform = new DeviceCountByGroupEntry();
|
||||||
|
filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase());
|
||||||
|
filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
@ -324,12 +357,17 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDeviceCountsByPlatforms;
|
return filteredDeviceCountsByPlatforms;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws SQLException {
|
@Override
|
||||||
|
public List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
|
List<DeviceCountByGroupEntry> filteredDeviceCountsByOwnershipTypes = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql, advancedSqlFiltering = "";
|
String sql, advancedSqlFiltering = "";
|
||||||
@ -359,8 +397,13 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredDeviceCountByOwnershipType;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
|
filteredDeviceCountByOwnershipType = new DeviceCountByGroupEntry();
|
||||||
|
filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
@ -368,19 +411,22 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDeviceCountsByOwnershipTypes;
|
return filteredDeviceCountsByOwnershipTypes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
@Override
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException {
|
public List<DeviceCountByGroupEntry>
|
||||||
|
getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
throw new InvalidParameterException("Non-compliant feature code (nonCompliantFeatureCode) " +
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
"should not be either null or empty.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
|
List<DeviceCountByGroupEntry> filteredDeviceCountsByOwnershipTypes = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql, advancedSqlFiltering = "";
|
String sql, advancedSqlFiltering = "";
|
||||||
@ -411,8 +457,13 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredDeviceCountByOwnershipType;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
|
filteredDeviceCountByOwnershipType = new DeviceCountByGroupEntry();
|
||||||
|
filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
@ -420,191 +471,22 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDeviceCountsByOwnershipTypes;
|
return filteredDeviceCountsByOwnershipTypes;
|
||||||
}
|
}
|
||||||
|
|
||||||
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
@Override
|
||||||
int startIndex, int resultCount) throws InvalidParameterException, SQLException {
|
public List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
if (startIndex < 0) {
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
throw new InvalidParameterException("Start index (startIndex) should be " +
|
|
||||||
"equal to 0 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resultCount < 5) {
|
|
||||||
throw new InvalidParameterException("Result count (resultCount) should be " +
|
|
||||||
"equal to 5 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
int totalRecordsCount = 0;
|
|
||||||
try {
|
|
||||||
con = this.getConnection();
|
|
||||||
String sql, advancedSqlFiltering = "";
|
|
||||||
// appending filters if exist, to support advanced filtering options
|
|
||||||
// [1] appending filter columns, if exist
|
|
||||||
if (filters != null && filters.size() > 0) {
|
|
||||||
for (String column : filters.keySet()) {
|
|
||||||
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 " +
|
|
||||||
"WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?";
|
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
// [2] appending filter column values, if exist
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
if (filters != null && filters.values().size() > 0) {
|
|
||||||
int i = 2;
|
|
||||||
for (Object value : filters.values()) {
|
|
||||||
if (value instanceof Integer) {
|
|
||||||
stmt.setInt(i, (Integer) value);
|
|
||||||
} else if (value instanceof String) {
|
|
||||||
stmt.setString(i, (String) value);
|
|
||||||
}
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
stmt.setInt(i, startIndex);
|
|
||||||
stmt.setInt(++i, resultCount);
|
|
||||||
} else {
|
|
||||||
stmt.setInt(2, startIndex);
|
|
||||||
stmt.setInt(3, resultCount);
|
|
||||||
}
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
Map<String, Object> filteredDeviceWithDetails;
|
|
||||||
while (rs.next()) {
|
|
||||||
filteredDeviceWithDetails = new HashMap<>();
|
|
||||||
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
|
|
||||||
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
|
|
||||||
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
|
|
||||||
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
|
|
||||||
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
|
||||||
}
|
|
||||||
// fetching total records count
|
|
||||||
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
|
||||||
|
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
while (rs.next()) {
|
|
||||||
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
|
||||||
}
|
|
||||||
PaginationResult paginationResult = new PaginationResult();
|
|
||||||
paginationResult.setData(filteredDevicesWithDetails);
|
|
||||||
paginationResult.setRecordsTotal(totalRecordsCount);
|
|
||||||
return paginationResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
|
||||||
Map<String, Object> filters, int startIndex, int resultCount)
|
|
||||||
throws InvalidParameterException, SQLException {
|
|
||||||
|
|
||||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
|
||||||
throw new InvalidParameterException("Non-compliant feature code (nonCompliantFeatureCode) " +
|
|
||||||
"should not be either null or empty.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (startIndex < 0) {
|
|
||||||
throw new InvalidParameterException("Start index (startIndex) should be " +
|
|
||||||
"equal to 0 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (resultCount < 5) {
|
|
||||||
throw new InvalidParameterException("Result count (resultCount) should be " +
|
|
||||||
"equal to 5 or greater than that.");
|
|
||||||
}
|
|
||||||
|
|
||||||
Connection con;
|
|
||||||
PreparedStatement stmt = null;
|
|
||||||
ResultSet rs = null;
|
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
|
||||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
|
||||||
int totalRecordsCount = 0;
|
|
||||||
try {
|
|
||||||
con = this.getConnection();
|
|
||||||
String sql, advancedSqlFiltering = "";
|
|
||||||
// appending filters if exist, to support advanced filtering options
|
|
||||||
// [1] appending filter columns, if exist
|
|
||||||
if (filters != null && filters.size() > 0) {
|
|
||||||
for (String column : filters.keySet()) {
|
|
||||||
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
|
|
||||||
"WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?";
|
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
// [2] appending filter column values, if exist
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
stmt.setString(2, nonCompliantFeatureCode);
|
|
||||||
if (filters != null && filters.values().size() > 0) {
|
|
||||||
int i = 3;
|
|
||||||
for (Object value : filters.values()) {
|
|
||||||
if (value instanceof Integer) {
|
|
||||||
stmt.setInt(i, (Integer) value);
|
|
||||||
} else if (value instanceof String) {
|
|
||||||
stmt.setString(i, (String) value);
|
|
||||||
}
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
stmt.setInt(i, startIndex);
|
|
||||||
stmt.setInt(++i, resultCount);
|
|
||||||
} else {
|
|
||||||
stmt.setInt(3, startIndex);
|
|
||||||
stmt.setInt(4, resultCount);
|
|
||||||
}
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
Map<String, Object> filteredDeviceWithDetails;
|
|
||||||
while (rs.next()) {
|
|
||||||
filteredDeviceWithDetails = new HashMap<>();
|
|
||||||
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
|
|
||||||
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
|
|
||||||
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
|
|
||||||
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
|
|
||||||
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
|
||||||
}
|
|
||||||
// fetching total records count
|
|
||||||
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
|
||||||
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
|
||||||
|
|
||||||
stmt = con.prepareStatement(sql);
|
|
||||||
stmt.setInt(1, tenantId);
|
|
||||||
stmt.setString(2, nonCompliantFeatureCode);
|
|
||||||
|
|
||||||
// executing query
|
|
||||||
rs = stmt.executeQuery();
|
|
||||||
// fetching query results
|
|
||||||
while (rs.next()) {
|
|
||||||
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
|
||||||
}
|
|
||||||
PaginationResult paginationResult = new PaginationResult();
|
|
||||||
paginationResult.setData(filteredDevicesWithDetails);
|
|
||||||
paginationResult.setRecordsTotal(totalRecordsCount);
|
|
||||||
return paginationResult;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws SQLException {
|
|
||||||
Connection con;
|
|
||||||
PreparedStatement stmt = null;
|
|
||||||
ResultSet rs = null;
|
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
|
||||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql;
|
String sql;
|
||||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||||
// appending filters to support advanced filtering options
|
// appending filters to support advanced filtering options
|
||||||
// [1] appending filter columns, if exist
|
// [1] appending filter columns, if exist
|
||||||
if (filters != null && filters.size() > 0) {
|
if (filters != null && filters.size() > 0) {
|
||||||
@ -629,13 +511,14 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
Map<String, Object> filteredDeviceWithDetails;
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceWithDetails = new HashMap<>();
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@ -644,24 +527,26 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDevicesWithDetails;
|
return filteredDevicesWithDetails;
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
@Override
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException {
|
public List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
throw new InvalidParameterException("Non-compliant feature code (nonCompliantFeatureCode) " +
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
"should not be either null or empty.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
Connection con;
|
Connection con;
|
||||||
PreparedStatement stmt = null;
|
PreparedStatement stmt = null;
|
||||||
ResultSet rs = null;
|
ResultSet rs = null;
|
||||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
try {
|
try {
|
||||||
con = this.getConnection();
|
con = this.getConnection();
|
||||||
String sql;
|
String sql;
|
||||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
"DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
// appending filters to support advanced filtering options
|
// appending filters to support advanced filtering options
|
||||||
// [1] appending filter columns, if exist
|
// [1] appending filter columns, if exist
|
||||||
if (filters != null && filters.size() > 0) {
|
if (filters != null && filters.size() > 0) {
|
||||||
@ -687,13 +572,14 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
// executing query
|
// executing query
|
||||||
rs = stmt.executeQuery();
|
rs = stmt.executeQuery();
|
||||||
// fetching query results
|
// fetching query results
|
||||||
Map<String, Object> filteredDeviceWithDetails;
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
filteredDeviceWithDetails = new HashMap<>();
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
filteredDeviceWithDetails.put("connectivity-details", rs.getString("CONNECTIVITY_STATUS"));
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@ -702,7 +588,50 @@ public class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
|||||||
return filteredDevicesWithDetails;
|
return filteredDevicesWithDetails;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Connection getConnection() throws SQLException {
|
protected Map<String, Object> extractDatabaseFiltersFromBean(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException {
|
||||||
|
if (filterSet == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = new LinkedHashMap<>();
|
||||||
|
|
||||||
|
String connectivityStatus = filterSet.getConnectivityStatus();
|
||||||
|
if (connectivityStatus != null) {
|
||||||
|
filters.put("CONNECTIVITY_STATUS", connectivityStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
String potentialVulnerability = filterSet.getPotentialVulnerability();
|
||||||
|
if (potentialVulnerability != null) {
|
||||||
|
if (GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT.equals(potentialVulnerability) ||
|
||||||
|
GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED.equals(potentialVulnerability)) {
|
||||||
|
if (GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT.equals(potentialVulnerability)) {
|
||||||
|
filters.put("IS_COMPLIANT", 0);
|
||||||
|
} else {
|
||||||
|
filters.put("POLICY_ID", -1);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new InvalidParameterValueException("Invalid use of value for potential vulnerability. " +
|
||||||
|
"Value of potential vulnerability could only be either " +
|
||||||
|
GadgetDataServiceDAOConstants.PotentialVulnerability.NON_COMPLIANT + " or " +
|
||||||
|
GadgetDataServiceDAOConstants.PotentialVulnerability.UNMONITORED + ".");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String platform = filterSet.getPlatform();
|
||||||
|
if (platform != null) {
|
||||||
|
filters.put("PLATFORM", platform);
|
||||||
|
}
|
||||||
|
|
||||||
|
String ownership = filterSet.getOwnership();
|
||||||
|
if (ownership != null) {
|
||||||
|
filters.put("OWNERSHIP", ownership);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filters;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected Connection getConnection() throws SQLException {
|
||||||
return GadgetDataServiceDAOFactory.getConnection();
|
return GadgetDataServiceDAOFactory.getConnection();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -18,85 +18,56 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||||
|
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterException;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.*;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
public interface GadgetDataServiceDAO {
|
public interface GadgetDataServiceDAO {
|
||||||
|
|
||||||
/**
|
DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
* Method to get total filtered device count from a particular tenant.
|
|
||||||
*
|
DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||||
* @return Total filtered device count.
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
*/
|
|
||||||
int getTotalDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Method to get active device count from a particular tenant.
|
* Method to get total device count from a particular tenant.
|
||||||
*
|
*
|
||||||
* @return active device count.
|
* @return Total device count.
|
||||||
*/
|
*/
|
||||||
int getActiveDeviceCount() throws SQLException;
|
DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException;
|
||||||
|
|
||||||
/**
|
List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException;
|
||||||
* Method to get inactive device count from a particular tenant.
|
|
||||||
*
|
|
||||||
* @return inactive device count.
|
|
||||||
*/
|
|
||||||
int getInactiveDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
/**
|
List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException;
|
||||||
* Method to get removed device count from a particular tenant.
|
|
||||||
*
|
|
||||||
* @return removed device count.
|
|
||||||
*/
|
|
||||||
int getRemovedDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to get non-compliant device count from a particular tenant.
|
|
||||||
*
|
|
||||||
* @return Non-compliant device count.
|
|
||||||
*/
|
|
||||||
int getNonCompliantDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to get unmonitored device count from a particular tenant.
|
|
||||||
*
|
|
||||||
* @return Unmonitored device count.
|
|
||||||
*/
|
|
||||||
int getUnmonitoredDeviceCount() throws SQLException;
|
|
||||||
|
|
||||||
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
throws InvalidParameterException, SQLException;
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
int getDeviceCount(Map<String, Object> filters) throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws SQLException;
|
List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws SQLException;
|
PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
|
||||||
|
|
||||||
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
|
||||||
int startIndex, int resultCount) throws InvalidParameterException, SQLException;
|
|
||||||
|
|
||||||
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters, int startIndex, int resultCount)
|
FilterSet filterSet, int startIndex, int resultCount) throws InvalidParameterValueException, SQLException;
|
||||||
throws InvalidParameterException, SQLException;
|
|
||||||
|
|
||||||
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws SQLException;
|
List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws InvalidParameterException, SQLException;
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,38 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||||
|
|
||||||
|
public final class GadgetDataServiceDAOConstants {
|
||||||
|
|
||||||
|
public static class PotentialVulnerability {
|
||||||
|
|
||||||
|
// These constants do not hold actual database values
|
||||||
|
// These are just abstract values defined and used @ Gadget Data Service DAO Implementation layer
|
||||||
|
public static final String NON_COMPLIANT = "NON_COMPLIANT";
|
||||||
|
public static final String UNMONITORED = "UNMONITORED";
|
||||||
|
|
||||||
|
private PotentialVulnerability() {
|
||||||
|
throw new AssertionError();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private GadgetDataServiceDAOConstants() { throw new AssertionError(); }
|
||||||
|
|
||||||
|
}
|
||||||
@ -20,8 +20,13 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
|||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import org.apache.commons.logging.Log;
|
||||||
import org.apache.commons.logging.LogFactory;
|
import org.apache.commons.logging.LogFactory;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.GadgetDataServiceDAOImpl;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.GenericGadgetDataServiceDAOImpl;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.MSSQLGadgetDataServiceDAOImpl;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.OracleGadgetDataServiceDAOImpl;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl.PostgreSQLGadgetDataServiceDAOImpl;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
|
||||||
import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
|
import org.wso2.carbon.device.mgt.common.IllegalTransactionStateException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.UnsupportedDatabaseEngineException;
|
||||||
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
|
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
|
||||||
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
|
import org.wso2.carbon.device.mgt.core.config.datasource.JNDILookupDefinition;
|
||||||
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
@ -41,7 +46,23 @@ public class GadgetDataServiceDAOFactory {
|
|||||||
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
|
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
|
||||||
|
|
||||||
public static GadgetDataServiceDAO getGadgetDataServiceDAO() {
|
public static GadgetDataServiceDAO getGadgetDataServiceDAO() {
|
||||||
return new GadgetDataServiceDAOImpl();
|
if (databaseEngine != null) {
|
||||||
|
switch (databaseEngine) {
|
||||||
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_H2:
|
||||||
|
return new GenericGadgetDataServiceDAOImpl();
|
||||||
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MYSQL:
|
||||||
|
return new GenericGadgetDataServiceDAOImpl();
|
||||||
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_MSSQL:
|
||||||
|
return new MSSQLGadgetDataServiceDAOImpl();
|
||||||
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_POSTGRESQL:
|
||||||
|
return new PostgreSQLGadgetDataServiceDAOImpl();
|
||||||
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
|
||||||
|
return new OracleGadgetDataServiceDAOImpl();
|
||||||
|
default:
|
||||||
|
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw new IllegalStateException("Database engine has not initialized properly.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void init(DataSourceConfig config) {
|
public static void init(DataSourceConfig config) {
|
||||||
|
|||||||
@ -0,0 +1,74 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean;
|
||||||
|
|
||||||
|
public class DetailedDeviceEntry {
|
||||||
|
|
||||||
|
private int deviceId;
|
||||||
|
private String deviceIdentification;
|
||||||
|
private String platform;
|
||||||
|
private String ownershipType;
|
||||||
|
private String connectivityStatus;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public int getDeviceId() {
|
||||||
|
return deviceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDeviceId(int deviceId) {
|
||||||
|
this.deviceId = deviceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getDeviceIdentification() {
|
||||||
|
return deviceIdentification;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDeviceIdentification(String deviceIdentification) {
|
||||||
|
this.deviceIdentification = deviceIdentification;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getPlatform() {
|
||||||
|
return platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPlatform(String platform) {
|
||||||
|
this.platform = platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getOwnershipType() {
|
||||||
|
return ownershipType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setOwnershipType(String ownershipType) {
|
||||||
|
this.ownershipType = ownershipType;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getConnectivityStatus() {
|
||||||
|
return connectivityStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConnectivityStatus(String connectivityStatus) {
|
||||||
|
this.connectivityStatus = connectivityStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean;
|
||||||
|
|
||||||
|
public class DeviceCountByGroupEntry {
|
||||||
|
|
||||||
|
private String group;
|
||||||
|
private String displayNameForGroup;
|
||||||
|
private int deviceCount;
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getGroup() {
|
||||||
|
return group;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroup(String group) {
|
||||||
|
this.group = group;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public String getDisplayNameForGroup() {
|
||||||
|
return displayNameForGroup;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDisplayNameForGroup(String displayNameForGroup) {
|
||||||
|
this.displayNameForGroup = displayNameForGroup;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public int getDeviceCount() {
|
||||||
|
return deviceCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDeviceCount(int deviceCount) {
|
||||||
|
this.deviceCount = deviceCount;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,62 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean;
|
||||||
|
|
||||||
|
public class FilterSet {
|
||||||
|
|
||||||
|
private String connectivityStatus;
|
||||||
|
private String potentialVulnerability;
|
||||||
|
private String platform;
|
||||||
|
private String ownership;
|
||||||
|
|
||||||
|
public String getConnectivityStatus() {
|
||||||
|
return connectivityStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setConnectivityStatus(String connectivityStatus) {
|
||||||
|
this.connectivityStatus = connectivityStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPotentialVulnerability() {
|
||||||
|
return potentialVulnerability;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPotentialVulnerability(String potentialVulnerability) {
|
||||||
|
this.potentialVulnerability = potentialVulnerability;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPlatform() {
|
||||||
|
return platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void setPlatform(String platform) {
|
||||||
|
this.platform = platform;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOwnership() {
|
||||||
|
return ownership;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unused")
|
||||||
|
public void setOwnership(String ownership) {
|
||||||
|
this.ownership = ownership;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -22,7 +22,7 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception;
|
|||||||
* Custom exception class for catching invalid parameter issues,
|
* Custom exception class for catching invalid parameter issues,
|
||||||
* relevant to Gadget Data Service DAO layer.
|
* relevant to Gadget Data Service DAO layer.
|
||||||
*/
|
*/
|
||||||
public class InvalidParameterException extends Exception {
|
public class InvalidParameterValueException extends Exception {
|
||||||
|
|
||||||
private String errorMessage;
|
private String errorMessage;
|
||||||
private static final long serialVersionUID = 2021891706072918864L;
|
private static final long serialVersionUID = 2021891706072918864L;
|
||||||
@ -34,7 +34,7 @@ public class InvalidParameterException extends Exception {
|
|||||||
* @param nestedException Nested exception.
|
* @param nestedException Nested exception.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public InvalidParameterException(String errorMessage, Exception nestedException) {
|
public InvalidParameterValueException(String errorMessage, Exception nestedException) {
|
||||||
super(errorMessage, nestedException);
|
super(errorMessage, nestedException);
|
||||||
setErrorMessage(errorMessage);
|
setErrorMessage(errorMessage);
|
||||||
}
|
}
|
||||||
@ -46,7 +46,7 @@ public class InvalidParameterException extends Exception {
|
|||||||
* @param cause Cause of this exception.
|
* @param cause Cause of this exception.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public InvalidParameterException(String errorMessage, Throwable cause) {
|
public InvalidParameterValueException(String errorMessage, Throwable cause) {
|
||||||
super(errorMessage, cause);
|
super(errorMessage, cause);
|
||||||
setErrorMessage(errorMessage);
|
setErrorMessage(errorMessage);
|
||||||
}
|
}
|
||||||
@ -56,7 +56,7 @@ public class InvalidParameterException extends Exception {
|
|||||||
*
|
*
|
||||||
* @param errorMessage Specific error message.
|
* @param errorMessage Specific error message.
|
||||||
*/
|
*/
|
||||||
public InvalidParameterException(String errorMessage) {
|
public InvalidParameterValueException(String errorMessage) {
|
||||||
super(errorMessage);
|
super(errorMessage);
|
||||||
setErrorMessage(errorMessage);
|
setErrorMessage(errorMessage);
|
||||||
}
|
}
|
||||||
@ -67,7 +67,7 @@ public class InvalidParameterException extends Exception {
|
|||||||
* @param cause Cause of this exception.
|
* @param cause Cause of this exception.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("unused")
|
@SuppressWarnings("unused")
|
||||||
public InvalidParameterException(Throwable cause) {
|
public InvalidParameterValueException(Throwable cause) {
|
||||||
super(cause);
|
super(cause);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -0,0 +1,281 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl;
|
||||||
|
|
||||||
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DeviceCountByGroupEntry> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC LIMIT ?, ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredNonCompliantDeviceCountByFeature;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroupEntry();
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
|
||||||
|
}
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
|
||||||
|
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 2;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering +
|
||||||
|
"ORDER BY DEVICE_ID ASC LIMIT ?, ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 3;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(3, startIndex);
|
||||||
|
stmt.setInt(4, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,283 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl;
|
||||||
|
|
||||||
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class MSSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DeviceCountByGroupEntry> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC " +
|
||||||
|
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredNonCompliantDeviceCountByFeature;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroupEntry();
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
|
||||||
|
}
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
|
||||||
|
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC " +
|
||||||
|
"OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 2;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering +
|
||||||
|
"ORDER BY DEVICE_ID ASC OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 3;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(3, startIndex);
|
||||||
|
stmt.setInt(4, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,283 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl;
|
||||||
|
|
||||||
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class OracleGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DeviceCountByGroupEntry> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT FEATURE_CODE, COUNT(DEVICE_ID) " +
|
||||||
|
"AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY " +
|
||||||
|
"DEVICE_COUNT DESC) rs) WHERE offset >= ? AND ROWNUM <= ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredNonCompliantDeviceCountByFeature;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroupEntry();
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
|
||||||
|
}
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
|
||||||
|
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, " +
|
||||||
|
"OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering +
|
||||||
|
"ORDER BY DEVICE_ID ASC) rs) WHERE offset >= ? AND ROWNUM <= ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 2;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT * FROM (SELECT ROWNUM offset, rs.* FROM (SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, " +
|
||||||
|
"OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " +
|
||||||
|
advancedSqlFiltering + "ORDER BY DEVICE_ID ASC) rs) WHERE offset >= ? AND ROWNUM <= ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 3;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(3, startIndex);
|
||||||
|
stmt.setInt(4, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,281 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* you may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl;
|
||||||
|
|
||||||
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DetailedDeviceEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.DeviceCountByGroupEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.FilterSet;
|
||||||
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class PostgreSQLGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DeviceCountByGroupEntry> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? GROUP BY FEATURE_CODE ORDER BY DEVICE_COUNT DESC OFFSET ? LIMIT ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DeviceCountByGroupEntry filteredNonCompliantDeviceCountByFeature;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroupEntry();
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE"));
|
||||||
|
filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||||
|
filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature);
|
||||||
|
}
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM " +
|
||||||
|
"(SELECT DISTINCT FEATURE_CODE FROM DEVICES_VIEW_2 WHERE TENANT_ID = ?) NON_COMPLIANT_FEATURE_CODE";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_1 WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 2;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(2, startIndex);
|
||||||
|
stmt.setInt(3, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
|
||||||
|
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||||
|
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
throw new InvalidParameterValueException("Start index should be equal to 0 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (resultCount < 5) {
|
||||||
|
throw new InvalidParameterValueException("Result count should be equal to 5 or greater than that.");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||||
|
|
||||||
|
Connection con;
|
||||||
|
PreparedStatement stmt = null;
|
||||||
|
ResultSet rs = null;
|
||||||
|
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||||
|
List<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||||
|
int totalRecordsCount = 0;
|
||||||
|
try {
|
||||||
|
con = this.getConnection();
|
||||||
|
String sql, advancedSqlFiltering = "";
|
||||||
|
// appending filters if exist, to support advanced filtering options
|
||||||
|
// [1] appending filter columns, if exist
|
||||||
|
if (filters != null && filters.size() > 0) {
|
||||||
|
for (String column : filters.keySet()) {
|
||||||
|
advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? ";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||||
|
"DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering +
|
||||||
|
"ORDER BY DEVICE_ID ASC OFFSET ? LIMIT ?";
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
// [2] appending filter column values, if exist
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
if (filters != null && filters.values().size() > 0) {
|
||||||
|
int i = 3;
|
||||||
|
for (Object value : filters.values()) {
|
||||||
|
if (value instanceof Integer) {
|
||||||
|
stmt.setInt(i, (Integer) value);
|
||||||
|
} else if (value instanceof String) {
|
||||||
|
stmt.setString(i, (String) value);
|
||||||
|
}
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
stmt.setInt(i, startIndex);
|
||||||
|
stmt.setInt(++i, resultCount);
|
||||||
|
} else {
|
||||||
|
stmt.setInt(3, startIndex);
|
||||||
|
stmt.setInt(4, resultCount);
|
||||||
|
}
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
DetailedDeviceEntry filteredDeviceWithDetails;
|
||||||
|
while (rs.next()) {
|
||||||
|
filteredDeviceWithDetails = new DetailedDeviceEntry();
|
||||||
|
filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID"));
|
||||||
|
filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION"));
|
||||||
|
filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM"));
|
||||||
|
filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP"));
|
||||||
|
filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS"));
|
||||||
|
filteredDevicesWithDetails.add(filteredDeviceWithDetails);
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetching total records count
|
||||||
|
sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 " +
|
||||||
|
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||||
|
|
||||||
|
stmt = con.prepareStatement(sql);
|
||||||
|
stmt.setInt(1, tenantId);
|
||||||
|
stmt.setString(2, nonCompliantFeatureCode);
|
||||||
|
|
||||||
|
// executing query
|
||||||
|
rs = stmt.executeQuery();
|
||||||
|
// fetching query results
|
||||||
|
while (rs.next()) {
|
||||||
|
totalRecordsCount = rs.getInt("DEVICE_COUNT");
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||||
|
}
|
||||||
|
PaginationResult paginationResult = new PaginationResult();
|
||||||
|
paginationResult.setData(filteredDevicesWithDetails);
|
||||||
|
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||||
|
return paginationResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -20,13 +20,12 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.impl;
|
|||||||
|
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
|
||||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterException;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.bean.*;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* To be updated...
|
* To be updated...
|
||||||
@ -34,8 +33,34 @@ import java.util.Map;
|
|||||||
public class GadgetDataServiceImpl implements GadgetDataService {
|
public class GadgetDataServiceImpl implements GadgetDataService {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getTotalDeviceCount() throws SQLException {
|
public DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
int totalDeviceCount;
|
DeviceCountByGroupEntry filteredDeviceCount;
|
||||||
|
try {
|
||||||
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
|
filteredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filterSet);
|
||||||
|
} finally {
|
||||||
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
|
}
|
||||||
|
return filteredDeviceCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, FilterSet filterSet)
|
||||||
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
DeviceCountByGroupEntry featureNonCompliantDeviceCount;
|
||||||
|
try {
|
||||||
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
|
featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory.
|
||||||
|
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filterSet);
|
||||||
|
} finally {
|
||||||
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
|
}
|
||||||
|
return featureNonCompliantDeviceCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException {
|
||||||
|
DeviceCountByGroupEntry totalDeviceCount;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
|
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
|
||||||
@ -46,69 +71,34 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getActiveDeviceCount() throws SQLException {
|
public List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException {
|
||||||
int activeDeviceCount;
|
List<DeviceCountByGroupEntry> deviceCountsByConnectivityStatuses;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount();
|
deviceCountsByConnectivityStatuses = GadgetDataServiceDAOFactory.
|
||||||
|
getGadgetDataServiceDAO().getDeviceCountsByConnectivityStatuses();
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
return activeDeviceCount;
|
return deviceCountsByConnectivityStatuses;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getInactiveDeviceCount() throws SQLException {
|
public List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException {
|
||||||
int inactiveDeviceCount;
|
List<DeviceCountByGroupEntry> deviceCountsByPotentialVulnerabilities;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount();
|
deviceCountsByPotentialVulnerabilities = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
|
getDeviceCountsByPotentialVulnerabilities();
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
return inactiveDeviceCount;
|
return deviceCountsByPotentialVulnerabilities;
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getRemovedDeviceCount() throws SQLException {
|
|
||||||
int removedDeviceCount;
|
|
||||||
try {
|
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
|
||||||
removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount();
|
|
||||||
} finally {
|
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
|
||||||
}
|
|
||||||
return removedDeviceCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getNonCompliantDeviceCount() throws SQLException {
|
|
||||||
int nonCompliantDeviceCount;
|
|
||||||
try {
|
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
|
||||||
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.
|
|
||||||
getGadgetDataServiceDAO().getNonCompliantDeviceCount();
|
|
||||||
} finally {
|
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
|
||||||
}
|
|
||||||
return nonCompliantDeviceCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getUnmonitoredDeviceCount() throws SQLException {
|
|
||||||
int unmonitoredDeviceCount;
|
|
||||||
try {
|
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
|
||||||
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
|
|
||||||
} finally {
|
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
|
||||||
}
|
|
||||||
return unmonitoredDeviceCount;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||||
throws SQLException, InvalidParameterException {
|
throws SQLException, InvalidParameterValueException {
|
||||||
PaginationResult paginationResult;
|
PaginationResult paginationResult;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
@ -121,38 +111,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public int getDeviceCount(Map<String, Object> filters) throws SQLException {
|
public List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||||
int deviceCount;
|
throws InvalidParameterValueException, SQLException {
|
||||||
try {
|
List<DeviceCountByGroupEntry> deviceCountsByPlatforms;
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
|
||||||
deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters);
|
|
||||||
} finally {
|
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
|
||||||
}
|
|
||||||
return deviceCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters)
|
|
||||||
throws SQLException, InvalidParameterException {
|
|
||||||
int featureNonCompliantDeviceCount;
|
|
||||||
try {
|
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
|
||||||
featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory.
|
|
||||||
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters);
|
|
||||||
} finally {
|
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
|
||||||
}
|
|
||||||
return featureNonCompliantDeviceCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws SQLException {
|
|
||||||
Map<String, Integer> deviceCountsByPlatforms;
|
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getDeviceCountsByPlatforms(filters);
|
getDeviceCountsByPlatforms(filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -160,13 +125,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
public List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws SQLException, InvalidParameterException {
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms;
|
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByPlatforms;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters);
|
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -174,12 +139,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws SQLException {
|
public List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||||
Map<String, Integer> deviceCountsByOwnershipTypes;
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
List<DeviceCountByGroupEntry> deviceCountsByOwnershipTypes;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getDeviceCountsByOwnershipTypes(filters);
|
getDeviceCountsByOwnershipTypes(filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -187,13 +153,14 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
public List<DeviceCountByGroupEntry>
|
||||||
Map<String, Object> filters) throws SQLException, InvalidParameterException {
|
getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||||
Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes;
|
FilterSet filterSet) throws SQLException, InvalidParameterValueException {
|
||||||
|
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByOwnershipTypes;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
featureNonCompliantDeviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
featureNonCompliantDeviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters);
|
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -201,13 +168,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
public PaginationResult getDevicesWithDetails(FilterSet filterSet,
|
||||||
int startIndex, int resultCount) throws InvalidParameterException, SQLException {
|
int startIndex, int resultCount) throws InvalidParameterValueException, SQLException {
|
||||||
PaginationResult paginationResult;
|
PaginationResult paginationResult;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getDevicesWithDetails(filters, startIndex, resultCount);
|
getDevicesWithDetails(filterSet, startIndex, resultCount);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -216,13 +183,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters, int startIndex, int resultCount)
|
FilterSet filterSet, int startIndex, int resultCount)
|
||||||
throws InvalidParameterException, SQLException {
|
throws InvalidParameterValueException, SQLException {
|
||||||
PaginationResult paginationResult;
|
PaginationResult paginationResult;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, startIndex, resultCount);
|
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet, startIndex, resultCount);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -230,11 +197,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws SQLException {
|
public List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||||
List<Map<String, Object>> devicesWithDetails;
|
throws InvalidParameterValueException, SQLException {
|
||||||
|
List<DetailedDeviceEntry> devicesWithDetails;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters);
|
devicesWithDetails = GadgetDataServiceDAOFactory.
|
||||||
|
getGadgetDataServiceDAO().getDevicesWithDetails(filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
@ -242,13 +211,13 @@ public class GadgetDataServiceImpl implements GadgetDataService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
public List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||||
Map<String, Object> filters) throws SQLException, InvalidParameterException {
|
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||||
List<Map<String, Object>> featureNonCompliantDevicesWithDetails;
|
List<DetailedDeviceEntry> featureNonCompliantDevicesWithDetails;
|
||||||
try {
|
try {
|
||||||
GadgetDataServiceDAOFactory.openConnection();
|
GadgetDataServiceDAOFactory.openConnection();
|
||||||
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters);
|
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet);
|
||||||
} finally {
|
} finally {
|
||||||
GadgetDataServiceDAOFactory.closeConnection();
|
GadgetDataServiceDAOFactory.closeConnection();
|
||||||
}
|
}
|
||||||
|
|||||||
@ -72,14 +72,14 @@ public class GadgetDataServiceComponent {
|
|||||||
//do nothing
|
//do nothing
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setDataSourceService(DataSourceService dataSourceService) {
|
protected void setDataSourceService(DataSourceService dataSourceService) {
|
||||||
if (log.isDebugEnabled()) {
|
if (log.isDebugEnabled()) {
|
||||||
log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
||||||
}
|
}
|
||||||
//do nothing
|
//do nothing
|
||||||
}
|
}
|
||||||
|
|
||||||
public void unsetDataSourceService(DataSourceService dataSourceService) {
|
protected void unsetDataSourceService(DataSourceService dataSourceService) {
|
||||||
if (log.isDebugEnabled()) {
|
if (log.isDebugEnabled()) {
|
||||||
log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -43,11 +43,9 @@
|
|||||||
<source>1.7</source>
|
<source>1.7</source>
|
||||||
<target>1.7</target>
|
<target>1.7</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
<version>2.3.2</version>
|
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-war-plugin</artifactId>
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
<version>2.2</version>
|
|
||||||
<configuration>
|
<configuration>
|
||||||
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
|
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
|
||||||
<warName>devicemgt_admin</warName>
|
<warName>devicemgt_admin</warName>
|
||||||
@ -88,7 +86,6 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</profile>
|
</profile>
|
||||||
|
|
||||||
<profile>
|
<profile>
|
||||||
<id>client</id>
|
<id>client</id>
|
||||||
<build>
|
<build>
|
||||||
@ -207,6 +204,11 @@
|
|||||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.swagger</groupId>
|
||||||
|
<artifactId>swagger-annotations</artifactId>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@ -18,19 +18,17 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Authentication related REST-API implementation.
|
* Authentication related REST-API interface.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "Authentication")
|
||||||
@Produces({ "application/json", "application/xml" })
|
@Produces({ "application/json", "application/xml" })
|
||||||
@Consumes({ "application/json", "application/xml" })
|
@Consumes({ "application/json", "application/xml" })
|
||||||
public class Authentication {
|
public interface Authentication {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Authentication.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -18,43 +18,21 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException;
|
|
||||||
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
|
|
||||||
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
|
|
||||||
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
|
|
||||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.exception.Message;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.*;
|
||||||
import javax.ws.rs.DELETE;
|
|
||||||
import javax.ws.rs.GET;
|
|
||||||
import javax.ws.rs.HeaderParam;
|
|
||||||
import javax.ws.rs.POST;
|
|
||||||
import javax.ws.rs.Path;
|
|
||||||
import javax.ws.rs.PathParam;
|
|
||||||
import javax.ws.rs.Produces;
|
|
||||||
import javax.ws.rs.QueryParam;
|
|
||||||
import javax.ws.rs.core.MediaType;
|
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
|
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "Certificate", description = "certificate related tasks such as saving certificates")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
@Produces({"application/json", "application/xml"})
|
@Produces({ "application/json", "application/xml" })
|
||||||
@Consumes({ "application/json", "application/xml" })
|
@Consumes({ "application/json", "application/xml" })
|
||||||
public class Certificate {
|
public interface Certificate {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Operation.class);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save a list of certificates and relevant information in the database.
|
* Save a list of certificates and relevant information in the database.
|
||||||
@ -65,30 +43,8 @@ public class Certificate {
|
|||||||
*/
|
*/
|
||||||
@POST
|
@POST
|
||||||
@Path("saveCertificate")
|
@Path("saveCertificate")
|
||||||
public Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
|
Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
EnrollmentCertificate[] enrollmentCertificates) {
|
EnrollmentCertificate[] enrollmentCertificates);
|
||||||
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
|
||||||
CertificateManagementService certificateService;
|
|
||||||
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
|
|
||||||
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate;
|
|
||||||
certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
|
||||||
try {
|
|
||||||
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
|
|
||||||
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
|
|
||||||
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
|
|
||||||
certificate.setSerial(enrollmentCertificate.getSerial());
|
|
||||||
certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
|
|
||||||
certificates.add(certificate);
|
|
||||||
}
|
|
||||||
certificateService.saveCertificate(certificates);
|
|
||||||
return Response.status(Response.Status.CREATED).entity("Added successfully.").
|
|
||||||
type(responseMediaType).build();
|
|
||||||
} catch (KeystoreException e) {
|
|
||||||
String msg = "Error occurred while converting PEM file to X509Certificate.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get a certificate when the serial number is given.
|
* Get a certificate when the serial number is given.
|
||||||
@ -98,31 +54,8 @@ public class Certificate {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("{serialNumber}")
|
@Path("{serialNumber}")
|
||||||
public Response getCertificate(@HeaderParam("Accept") String acceptHeader,
|
Response getCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
@PathParam("serialNumber") String serialNumber) {
|
@PathParam("serialNumber") String serialNumber);
|
||||||
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
|
||||||
Message message = new Message();
|
|
||||||
|
|
||||||
if (serialNumber == null || serialNumber.isEmpty()) {
|
|
||||||
message.setErrorMessage("Invalid serial number");
|
|
||||||
message.setDiscription("Serial number is missing or invalid.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
|
||||||
CertificateResponse certificateResponse;
|
|
||||||
try {
|
|
||||||
certificateResponse = certificateService.getCertificateBySerial(serialNumber);
|
|
||||||
if(certificateResponse != null) {
|
|
||||||
certificateResponse.setCertificate(null); //avoid sending byte array in response.
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build();
|
|
||||||
} catch (KeystoreException e) {
|
|
||||||
String msg = "Error occurred while converting PEM file to X509Certificate";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all certificates in a paginated manner.
|
* Get all certificates in a paginated manner.
|
||||||
@ -134,61 +67,13 @@ public class Certificate {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("paginate")
|
@Path("paginate")
|
||||||
public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader,
|
Response getAllCertificates(@HeaderParam("Accept") String acceptHeader,
|
||||||
@QueryParam("start") int startIndex,
|
@QueryParam("start") int startIndex, @QueryParam("length") int length)
|
||||||
@QueryParam("length") int length)
|
throws MDMAPIException;
|
||||||
throws MDMAPIException {
|
|
||||||
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
|
||||||
Message message = new Message();
|
|
||||||
|
|
||||||
if (startIndex < 0) {
|
|
||||||
message.setErrorMessage("Invalid start index.");
|
|
||||||
message.setDiscription("Start index cannot be less that 0.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
|
||||||
} else if (length <= 0) {
|
|
||||||
message.setErrorMessage("Invalid length value.");
|
|
||||||
message.setDiscription("Length should be a positive integer.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
|
||||||
PaginationRequest paginationRequest = new PaginationRequest(startIndex, length);
|
|
||||||
try {
|
|
||||||
PaginationResult certificates = certificateService.getAllCertificates(paginationRequest);
|
|
||||||
return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build();
|
|
||||||
} catch (CertificateManagementDAOException e) {
|
|
||||||
String msg = "Error occurred while fetching all certificates.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@DELETE
|
@DELETE
|
||||||
@Path("{serialNumber}")
|
@Path("{serialNumber}")
|
||||||
public Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
|
Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
@PathParam("serialNumber") String serialNumber) throws MDMAPIException {
|
@PathParam("serialNumber") String serialNumber) throws MDMAPIException;
|
||||||
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
|
||||||
Message message = new Message();
|
|
||||||
|
|
||||||
if (serialNumber == null || serialNumber.isEmpty()) {
|
|
||||||
message.setErrorMessage("Invalid serial number");
|
|
||||||
message.setDiscription("Serial number is missing or invalid.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
|
||||||
boolean deleted;
|
|
||||||
try {
|
|
||||||
deleted = certificateService.removeCertificate(serialNumber);
|
|
||||||
if(deleted){
|
|
||||||
return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
} catch (CertificateManagementDAOException e) {
|
|
||||||
String msg = "Error occurred while converting PEM file to X509Certificate";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,96 +18,29 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
|
|
||||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
|
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.*;
|
||||||
import javax.ws.rs.GET;
|
|
||||||
import javax.ws.rs.POST;
|
|
||||||
import javax.ws.rs.PUT;
|
|
||||||
import javax.ws.rs.Produces;
|
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* General Tenant Configuration REST-API implementation.
|
* General Tenant Configuration REST-API implementation.
|
||||||
* All end points support JSON, XMl with content negotiation.
|
* All end points support JSON, XMl with content negotiation.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "Configuration", description = "General Tenant Configuration implementation")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
@Produces({"application/json", "application/xml"})
|
@Produces({ "application/json", "application/xml" })
|
||||||
@Consumes({ "application/json", "application/xml" })
|
@Consumes({ "application/json", "application/xml" })
|
||||||
public class Configuration {
|
public interface Configuration {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Configuration.class);
|
@POST
|
||||||
|
Response saveTenantConfiguration(TenantConfiguration configuration);
|
||||||
|
|
||||||
@POST
|
@GET
|
||||||
public Response saveTenantConfiguration(TenantConfiguration configuration) {
|
Response getConfiguration();
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
|
|
||||||
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
|
||||||
//Schedule the task service
|
|
||||||
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
|
|
||||||
responseMsg.setMessageFromServer("Tenant configuration saved successfully.");
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (ConfigurationManagementException e) {
|
|
||||||
String msg = "Error occurred while saving the tenant configuration.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@PUT
|
||||||
public Response getConfiguration() {
|
Response updateConfiguration(TenantConfiguration configuration);
|
||||||
String msg;
|
|
||||||
try {
|
|
||||||
TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService().
|
|
||||||
getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
|
||||||
ConfigurationEntry configurationEntry = new ConfigurationEntry();
|
|
||||||
configurationEntry.setContentType("text");
|
|
||||||
configurationEntry.setName("notifierFrequency");
|
|
||||||
configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency());
|
|
||||||
List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration();
|
|
||||||
if (configList == null) {
|
|
||||||
configList = new ArrayList<>();
|
|
||||||
}
|
|
||||||
configList.add(configurationEntry);
|
|
||||||
tenantConfiguration.setConfiguration(configList);
|
|
||||||
return Response.status(Response.Status.OK).entity(tenantConfiguration).build();
|
|
||||||
} catch (ConfigurationManagementException e) {
|
|
||||||
msg = "Error occurred while retrieving the tenant configuration.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
|
||||||
public Response updateConfiguration(TenantConfiguration configuration) {
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
|
|
||||||
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
|
||||||
//Schedule the task service
|
|
||||||
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
|
|
||||||
responseMsg.setMessageFromServer("Tenant configuration updated successfully.");
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (ConfigurationManagementException e) {
|
|
||||||
String msg = "Error occurred while updating the tenant configuration.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,36 +18,19 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.*;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementAdminService;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
|
||||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
|
||||||
|
|
||||||
import javax.ws.rs.DELETE;
|
import javax.ws.rs.*;
|
||||||
import javax.ws.rs.GET;
|
|
||||||
import javax.ws.rs.PUT;
|
|
||||||
import javax.ws.rs.Path;
|
|
||||||
import javax.ws.rs.PathParam;
|
|
||||||
import javax.ws.rs.Produces;
|
|
||||||
import javax.ws.rs.QueryParam;
|
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Device related operations
|
* Device related operations such as get all the available devices, etc.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "Devices")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class Device {
|
public interface Device {
|
||||||
private static Log log = LogFactory.getLog(Device.class);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all devices. We have to use accept all the necessary query parameters sent by datatable.
|
* Get all devices. We have to use accept all the necessary query parameters sent by datatable.
|
||||||
@ -56,49 +39,26 @@ public class Device {
|
|||||||
* @return Device List
|
* @return Device List
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user,
|
@ApiOperation(
|
||||||
@QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status,
|
consumes = MediaType.APPLICATION_JSON,
|
||||||
@QueryParam("start") int startIdx, @QueryParam("length") int length,
|
produces = MediaType.APPLICATION_JSON,
|
||||||
@QueryParam("device-name") String deviceName,
|
httpMethod = "GET",
|
||||||
@QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) {
|
value = "Returns the set of devices that matches a given device type, user, role, "
|
||||||
try {
|
+ "enrollment status, ownership type",
|
||||||
DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService();
|
notes = "Returns 500 if the operation fails",
|
||||||
//Length > 0 means this is a pagination request.
|
response = Device.class,
|
||||||
if (length > 0) {
|
responseContainer = "List")
|
||||||
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
|
@ApiResponses(value = { @ApiResponse(code = 200, message = "List of Devices"),
|
||||||
paginationRequest.setDeviceName(deviceName);
|
@ApiResponse(code = 500, message = "Server Error") })
|
||||||
paginationRequest.setOwner(user);
|
Response getAllDevices(
|
||||||
if (ownership != null) {
|
@ApiParam(name = "type", value = "Provide the device type, such as ios, android or windows", required = true) @QueryParam("type") String type,
|
||||||
paginationRequest.setOwnership(ownership.toString());
|
@ApiParam(name = "user", value = "Get the details of the devices registered to a user by providing the user name", required = true) @QueryParam("user") String user,
|
||||||
}
|
@ApiParam(name = "role", value = "Get the details of the devices registered to a specific role by providing the role name", required = true) @QueryParam("role") String role,
|
||||||
if (status != null) {
|
@ApiParam(name = "status", value = "Provide the device status details, such as active or inactive", required = true) @QueryParam("status") EnrolmentInfo.Status status,
|
||||||
paginationRequest.setStatus(status.toString());
|
@ApiParam(name = "start", value = "Provide the starting pagination index", required = true) @QueryParam("start") int startIdx,
|
||||||
}
|
@ApiParam(name = "length", value = "Provide how many device details you require from the starting pagination index", required = true) @QueryParam("length") int length,
|
||||||
paginationRequest.setDeviceType(type);
|
@ApiParam(name = "device-name", value = "Provide the name of a registered device and receive the specified device details", required = true) @QueryParam("device-name") String deviceName,
|
||||||
return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build();
|
@ApiParam(name = "ownership", value = "Provide the device ownership type and receive the specific device details", required = true) @QueryParam("ownership") EnrolmentInfo.OwnerShip ownership);
|
||||||
}
|
|
||||||
|
|
||||||
List<org.wso2.carbon.device.mgt.common.Device> allDevices;
|
|
||||||
if ((type != null) && !type.isEmpty()) {
|
|
||||||
allDevices = service.getAllDevices(type);
|
|
||||||
} else if ((user != null) && !user.isEmpty()) {
|
|
||||||
allDevices = service.getDevicesOfUser(user);
|
|
||||||
} else if ((role != null) && !role.isEmpty()) {
|
|
||||||
allDevices = service.getAllDevicesOfRole(role);
|
|
||||||
} else if (status != null) {
|
|
||||||
allDevices = service.getDevicesByStatus(status);
|
|
||||||
} else if (deviceName != null) {
|
|
||||||
allDevices = service.getDevicesByName(deviceName);
|
|
||||||
} else {
|
|
||||||
allDevices = service.getAllDevices();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(allDevices).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the device list.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch device details for a given device type and device Id.
|
* Fetch device details for a given device type and device Id.
|
||||||
@ -106,33 +66,17 @@ public class Device {
|
|||||||
* @return Device wrapped inside Response
|
* @return Device wrapped inside Response
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
|
@ApiOperation(
|
||||||
|
produces = MediaType.APPLICATION_JSON,
|
||||||
|
httpMethod = "GET",
|
||||||
|
value = "Fetch device details for a given device type and device Id",
|
||||||
|
notes = "Returns 500 if the operation fails",
|
||||||
|
response = Device.class)
|
||||||
|
@ApiResponses(value = { @ApiResponse(code = 200, message = "Matching Device"),
|
||||||
|
@ApiResponse(code = 500, message = "Server Error") })
|
||||||
@Path("view")
|
@Path("view")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public Response getDevice(@QueryParam("type") String type,
|
Response getDevice(@QueryParam("type") String type, @QueryParam("id") String id);
|
||||||
@QueryParam("id") String id) {
|
|
||||||
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
|
||||||
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
org.wso2.carbon.device.mgt.common.Device device;
|
|
||||||
try {
|
|
||||||
device = deviceManagementProviderService.getDevice(deviceIdentifier);
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the device information.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
if (device == null) {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
|
|
||||||
responsePayload.setMessageFromServer("Requested device by type: " +
|
|
||||||
type + " and id: " + id + " does not exist.");
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + ".");
|
|
||||||
responsePayload.setResponseContent(device);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch device details of a given user.
|
* Fetch device details of a given user.
|
||||||
@ -142,20 +86,7 @@ public class Device {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("user/{user}")
|
@Path("user/{user}")
|
||||||
public Response getDevice(@PathParam("user") String user) {
|
Response getDevice(@PathParam("user") String user);
|
||||||
List<org.wso2.carbon.device.mgt.common.Device> devices;
|
|
||||||
try {
|
|
||||||
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user);
|
|
||||||
if (devices == null) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(devices).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the devices list of given user.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch device count of a given user.
|
* Fetch device count of a given user.
|
||||||
@ -165,16 +96,7 @@ public class Device {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("user/{user}/count")
|
@Path("user/{user}/count")
|
||||||
public Response getDeviceCount(@PathParam("user") String user) {
|
Response getDeviceCount(@PathParam("user") String user);
|
||||||
try {
|
|
||||||
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user);
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the devices list of given user.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current device count
|
* Get current device count
|
||||||
@ -182,17 +104,15 @@ public class Device {
|
|||||||
* @return device count
|
* @return device count
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
|
@ApiOperation(
|
||||||
|
httpMethod = "GET",
|
||||||
|
value = "Returns the current device count",
|
||||||
|
notes = "Returns 500 if the operation fails",
|
||||||
|
response = Integer.class)
|
||||||
|
@ApiResponses(value = { @ApiResponse(code = 200, message = "Device count"),
|
||||||
|
@ApiResponse(code = 500, message = "Server Error") })
|
||||||
@Path("count")
|
@Path("count")
|
||||||
public Response getDeviceCount() {
|
Response getDeviceCount();
|
||||||
try {
|
|
||||||
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount();
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the device count.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the list of devices that matches with the given name.
|
* Get the list of devices that matches with the given name.
|
||||||
@ -203,37 +123,17 @@ public class Device {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("name/{name}/{tenantDomain}")
|
@Path("name/{name}/{tenantDomain}")
|
||||||
public Response getDevicesByName(@PathParam("name") String deviceName,
|
Response getDevicesByName(@PathParam("name") String deviceName,
|
||||||
@PathParam("tenantDomain") String tenantDomain) {
|
@PathParam("tenantDomain") String tenantDomain);
|
||||||
List<org.wso2.carbon.device.mgt.common.Device> devices;
|
|
||||||
try {
|
|
||||||
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName);
|
|
||||||
return Response.status(Response.Status.OK).entity(devices).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the devices list of device name.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the list of available device types.
|
* Get the list of available device types.
|
||||||
*
|
*
|
||||||
* @return list of device types.
|
* @return list of device types.
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("types")
|
@Path("types")
|
||||||
public Response getDeviceTypes() {
|
Response getDeviceTypes();
|
||||||
List<DeviceType> deviceTypes;
|
|
||||||
try {
|
|
||||||
deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes();
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceTypes).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the list of device types.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update device.
|
* Update device.
|
||||||
@ -242,24 +142,8 @@ public class Device {
|
|||||||
*/
|
*/
|
||||||
@PUT
|
@PUT
|
||||||
@Path("type/{type}/id/{deviceId}")
|
@Path("type/{type}/id/{deviceId}")
|
||||||
public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
|
Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
|
||||||
org.wso2.carbon.device.mgt.common.Device updatedDevice) {
|
org.wso2.carbon.device.mgt.common.Device updatedDevice);
|
||||||
try {
|
|
||||||
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
deviceIdentifier.setType(deviceType);
|
|
||||||
deviceIdentifier.setId(deviceId);
|
|
||||||
org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier);
|
|
||||||
device.setName(updatedDevice.getName());
|
|
||||||
device.setDescription(updatedDevice.getDescription());
|
|
||||||
Boolean response = deviceManagementService.modifyEnrollment(device);
|
|
||||||
return Response.status(Response.Status.OK).entity(response).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the list of device types.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* disenroll device.
|
* disenroll device.
|
||||||
@ -268,18 +152,6 @@ public class Device {
|
|||||||
*/
|
*/
|
||||||
@DELETE
|
@DELETE
|
||||||
@Path("type/{type}/id/{deviceId}")
|
@Path("type/{type}/id/{deviceId}")
|
||||||
public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) {
|
Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId);
|
||||||
try {
|
|
||||||
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
deviceIdentifier.setType(deviceType);
|
|
||||||
deviceIdentifier.setId(deviceId);
|
|
||||||
Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier);
|
|
||||||
return Response.status(Response.Status.OK).entity(response).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the list of device types.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,65 +16,28 @@
|
|||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
|
||||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
|
||||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
|
|
||||||
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
|
|
||||||
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
|
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
import javax.ws.rs.Path;
|
import javax.ws.rs.Path;
|
||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Device information related operations.
|
||||||
|
*/
|
||||||
|
@Api(value = "DeviceInfo")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class DeviceInformation {
|
public interface DeviceInformation {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(DeviceInformation.class);
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{type}/{id}")
|
@Path("{type}/{id}")
|
||||||
public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) {
|
Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
DeviceInformationManager informationManager;
|
|
||||||
DeviceInfo deviceInfo;
|
|
||||||
try {
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
deviceIdentifier.setId(id);
|
|
||||||
deviceIdentifier.setType(type);
|
|
||||||
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
|
|
||||||
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
|
|
||||||
} catch (DeviceDetailsMgtException e) {
|
|
||||||
String msg = "Error occurred while getting the device information.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceInfo).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("location/{type}/{id}")
|
@Path("location/{type}/{id}")
|
||||||
public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) {
|
Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
DeviceInformationManager informationManager;
|
|
||||||
DeviceLocation deviceLocation;
|
|
||||||
try {
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
deviceIdentifier.setId(id);
|
|
||||||
deviceIdentifier.setType(type);
|
|
||||||
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
|
|
||||||
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
|
|
||||||
} catch (DeviceDetailsMgtException e) {
|
|
||||||
String msg = "Error occurred while getting the device location.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceLocation).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
@ -18,13 +18,8 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
|
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
|
||||||
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@ -34,76 +29,30 @@ import javax.ws.rs.Path;
|
|||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DeviceNotification management REST-API implementation.
|
* DeviceNotification management REST-API implementation.
|
||||||
* All end points support JSON, XMl with content negotiation.
|
* All end points support JSON, XMl with content negotiation.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "DeviceNotification")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
@Produces({"application/json", "application/xml"})
|
@Produces({"application/json", "application/xml"})
|
||||||
@Consumes({ "application/json", "application/xml" })
|
@Consumes({ "application/json", "application/xml" })
|
||||||
public class DeviceNotification {
|
public interface DeviceNotification {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Configuration.class);
|
@GET
|
||||||
|
Response getNotifications();
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
public Response getNotifications() {
|
@Path("{status}")
|
||||||
String msg;
|
Response getNotificationsByStatus(@PathParam("status") Notification.Status status);
|
||||||
try {
|
|
||||||
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications();
|
|
||||||
return Response.status(Response.Status.OK).entity(notifications).build();
|
|
||||||
} catch (NotificationManagementException e) {
|
|
||||||
msg = "Error occurred while retrieving the notification list.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@PUT
|
||||||
@Path("{status}")
|
@Path("{id}/{status}")
|
||||||
public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) {
|
Response updateNotificationStatus(@PathParam("id") int id,
|
||||||
String msg;
|
@PathParam("status") Notification.Status status);
|
||||||
try {
|
|
||||||
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status);
|
|
||||||
return Response.status(Response.Status.OK).entity(notifications).build();
|
|
||||||
} catch (NotificationManagementException e) {
|
|
||||||
msg = "Error occurred while retrieving the notification list.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@POST
|
||||||
@Path("{id}/{status}")
|
Response addNotification(Notification notification);
|
||||||
public Response updateNotificationStatus(@PathParam("id") int id,
|
|
||||||
@PathParam("status") Notification.Status status) {
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status);
|
|
||||||
responseMsg.setMessageFromServer("Notification status updated successfully.");
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED);
|
|
||||||
return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build();
|
|
||||||
} catch (NotificationManagementException e) {
|
|
||||||
String msg = "Error occurred while updating notification status.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
|
||||||
public Response addNotification(Notification notification) {
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification);
|
|
||||||
responseMsg.setMessageFromServer("Notification has added successfully.");
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (NotificationManagementException e) {
|
|
||||||
String msg = "Error occurred while updating notification status.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -16,40 +16,21 @@
|
|||||||
* under the License.
|
* under the License.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
|
|
||||||
import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
||||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
|
|
||||||
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
|
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Device search related operations such as getting device information.
|
||||||
|
*/
|
||||||
|
@Api(value = "DeviceSearch")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class DeviceSearch {
|
public interface DeviceSearch {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(DeviceSearch.class);
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
public Response getDeviceInfo(SearchContext searchContext) {
|
Response getDeviceInfo(SearchContext searchContext);
|
||||||
SearchManagerService searchManagerService;
|
|
||||||
List<DeviceWrapper> devices;
|
|
||||||
try {
|
|
||||||
searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
|
|
||||||
devices = searchManagerService.search(searchContext);
|
|
||||||
|
|
||||||
} catch (SearchMgtException e) {
|
|
||||||
String msg = "Error occurred while searching the device information.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(devices).build();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -18,11 +18,7 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@ -30,16 +26,15 @@ import javax.ws.rs.Path;
|
|||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Features
|
* Features
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "Feature")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
@Produces({"application/json", "application/xml"})
|
@Produces({"application/json", "application/xml"})
|
||||||
@Consumes({"application/json", "application/xml"})
|
@Consumes({"application/json", "application/xml"})
|
||||||
public class Feature {
|
public interface Feature {
|
||||||
private static Log log = LogFactory.getLog(Feature.class);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all features for Mobile Device Type
|
* Get all features for Mobile Device Type
|
||||||
@ -48,18 +43,6 @@ public class Feature {
|
|||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path("/{type}")
|
@Path("/{type}")
|
||||||
public Response getFeatures(@PathParam("type") String type) {
|
Response getFeatures(@PathParam("type") String type);
|
||||||
List<org.wso2.carbon.device.mgt.common.Feature> features;
|
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
try {
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
features = dmService.getFeatureManager(type).getFeatures();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of features";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(features).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,19 +18,9 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
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.DeviceIdentifier;
|
||||||
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.DeviceGroup;
|
||||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
|
|
||||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
|
|
||||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.DELETE;
|
import javax.ws.rs.DELETE;
|
||||||
@ -43,473 +33,144 @@ import javax.ws.rs.PathParam;
|
|||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Date;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
@Api(value = "Group")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class Group {
|
public interface Group {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Group.class);
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Consumes("application/json")
|
@Consumes("application/json")
|
||||||
public Response createGroup(DeviceGroup group) {
|
Response createGroup(DeviceGroup group);
|
||||||
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
|
|
||||||
if (group == null) {
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).build();
|
|
||||||
}
|
|
||||||
group.setOwner(owner);
|
|
||||||
group.setDateOfCreation(new Date().getTime());
|
|
||||||
group.setDateOfLastUpdate(new Date().getTime());
|
|
||||||
try {
|
|
||||||
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
|
|
||||||
groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS);
|
|
||||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
|
|
||||||
DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE,
|
|
||||||
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
|
||||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE,
|
|
||||||
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS);
|
|
||||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES,
|
|
||||||
DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS);
|
|
||||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES,
|
|
||||||
DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS);
|
|
||||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS,
|
|
||||||
DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS);
|
|
||||||
return Response.status(Response.Status.CREATED).build();
|
|
||||||
} catch (GroupAlreadyEixistException e) {
|
|
||||||
return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getErrorMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}")
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
@PUT
|
@PUT
|
||||||
@Consumes("application/json")
|
@Consumes("application/json")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
DeviceGroup deviceGroup) {
|
DeviceGroup deviceGroup);
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner);
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getErrorMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}")
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
@DELETE
|
@DELETE
|
||||||
public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner);
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage());
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length) {
|
Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length);
|
||||||
try {
|
|
||||||
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.getGroups(startIndex, length);
|
|
||||||
if (paginationResult.getRecordsTotal() > 0) {
|
|
||||||
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/all")
|
@Path("/all")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getAllGroups() {
|
Response getAllGroups();
|
||||||
try {
|
|
||||||
GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils
|
|
||||||
.getGroupManagementProviderService();
|
|
||||||
PaginationResult paginationResult = groupManagementProviderService
|
|
||||||
.getGroups(0, groupManagementProviderService.getGroupCount());
|
|
||||||
if (paginationResult.getRecordsTotal() > 0) {
|
|
||||||
return Response.status(Response.Status.OK).entity(paginationResult.getData()).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/user/{user}")
|
@Path("/user/{user}")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
|
Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
|
||||||
@QueryParam("length") int length) {
|
@QueryParam("length") int length);
|
||||||
try {
|
|
||||||
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.getGroups(userName, startIndex, length);
|
|
||||||
if (paginationResult.getRecordsTotal() > 0) {
|
|
||||||
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/user/{user}/all")
|
@Path("/user/{user}/all")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroups(@PathParam("user") String userName) {
|
Response getGroups(@PathParam("user") String userName);
|
||||||
try {
|
|
||||||
List<DeviceGroup> deviceGroups = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.getGroups(userName);
|
|
||||||
if (deviceGroups.size() > 0) {
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}")
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
|
||||||
try {
|
|
||||||
DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner);
|
|
||||||
if (deviceGroup != null) {
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceGroup).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/user/{user}/search")
|
@Path("/user/{user}/search")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response findGroups(@QueryParam("groupName") String groupName,
|
Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user);
|
||||||
@PathParam("user") String user) {
|
|
||||||
try {
|
|
||||||
List<DeviceGroup> groups = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.findInGroups(groupName, user);
|
|
||||||
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
|
|
||||||
groups.toArray(deviceGroups);
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/user/{user}/all")
|
@Path("/user/{user}/all")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroups(@PathParam("user") String userName,
|
Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission);
|
||||||
@QueryParam("permission") String permission) {
|
|
||||||
try {
|
|
||||||
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
|
|
||||||
List<DeviceGroup> groups;
|
|
||||||
if (permission != null) {
|
|
||||||
groups = groupManagementService.getGroups(userName, permission);
|
|
||||||
} else {
|
|
||||||
groups = groupManagementService.getGroups(userName);
|
|
||||||
}
|
|
||||||
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
|
|
||||||
groups.toArray(deviceGroups);
|
|
||||||
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/count")
|
@Path("/count")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getAllGroupCount() {
|
Response getAllGroupCount();
|
||||||
try {
|
|
||||||
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount();
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/user/{user}/count")
|
@Path("/user/{user}/count")
|
||||||
@GET
|
@GET
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getGroupCount(@PathParam("user") String userName) {
|
Response getGroupCount(@PathParam("user") String userName);
|
||||||
try {
|
|
||||||
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName);
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}/share")
|
@Path("/owner/{owner}/name/{groupName}/share")
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@FormParam("shareUser") String shareUser,
|
@FormParam("shareUser") String shareUser, @FormParam("roleName") String sharingRole);
|
||||||
@FormParam("roleName") String sharingRole) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup(
|
|
||||||
shareUser, groupName, owner, sharingRole);
|
|
||||||
if (isShared) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
|
|
||||||
}
|
|
||||||
} catch (UserDoesNotExistException e) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}/unshare")
|
@Path("/owner/{owner}/name/{groupName}/unshare")
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@FormParam("unShareUser") String unShareUser,
|
@FormParam("unShareUser") String unShareUser,
|
||||||
@FormParam("roleName") String sharingRole) {
|
@FormParam("roleName") String sharingRole);
|
||||||
try {
|
|
||||||
boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup(
|
|
||||||
unShareUser, groupName, owner, sharingRole);
|
|
||||||
if (isUnShared) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
|
|
||||||
}
|
|
||||||
} catch (UserDoesNotExistException e) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName,
|
Response addSharing(@QueryParam("shareUser") String shareUser, @PathParam("groupName") String groupName,
|
||||||
@PathParam("owner") String owner,
|
@PathParam("owner") String owner, @PathParam("roleName") String roleName,
|
||||||
@PathParam("roleName") String roleName,
|
@FormParam("permissions") String[] permissions);
|
||||||
@FormParam("permissions") String[] permissions) {
|
|
||||||
|
|
||||||
try {
|
|
||||||
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole(
|
|
||||||
shareUser, groupName, owner, roleName, permissions);
|
|
||||||
if (isAdded) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@DELETE
|
@DELETE
|
||||||
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName,
|
Response removeSharing(@QueryParam("userName") String userName, @PathParam("groupName") String groupName,
|
||||||
@PathParam("owner") String owner,
|
@PathParam("owner") String owner, @PathParam("roleName") String roleName);
|
||||||
@PathParam("roleName") String roleName) {
|
|
||||||
try {
|
|
||||||
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole(
|
|
||||||
groupName, owner, roleName);
|
|
||||||
if (isRemoved) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/owner/{owner}/name/{groupName}/share/roles")
|
@Path("/owner/{owner}/name/{groupName}/share/roles")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getRoles(@PathParam("groupName") String groupName,
|
Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@PathParam("owner") String owner, @QueryParam("userName") String userName) {
|
@QueryParam("userName") String userName);
|
||||||
try {
|
|
||||||
List<String> roles;
|
|
||||||
if (userName != null && !userName.isEmpty()) {
|
|
||||||
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner);
|
|
||||||
} else {
|
|
||||||
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
|
|
||||||
}
|
|
||||||
String[] rolesArray = new String[roles.size()];
|
|
||||||
roles.toArray(rolesArray);
|
|
||||||
return Response.status(Response.Status.OK).entity(rolesArray).build();
|
|
||||||
} catch (UserDoesNotExistException e) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
|
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response setRoles(@PathParam("groupName") String groupName,
|
Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@PathParam("owner") String owner, @PathParam("userName") String userName,
|
@PathParam("userName") String userName, List<String> selectedRoles);
|
||||||
List<String> selectedRoles) {
|
|
||||||
try {
|
|
||||||
List<String> allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
|
|
||||||
for (String role : allRoles) {
|
|
||||||
if (selectedRoles.contains(role)) {
|
|
||||||
DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.shareGroup(userName, groupName, owner, role);
|
|
||||||
} else {
|
|
||||||
DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.unshareGroup(userName, groupName, owner, role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} catch (UserDoesNotExistException e) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/owner/{owner}/name/{groupName}/users")
|
@Path("/owner/{owner}/name/{groupName}/users")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getUsers(@PathParam("groupName") String groupName,
|
Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
|
||||||
@PathParam("owner") String owner) {
|
|
||||||
try {
|
|
||||||
List<GroupUser> users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(
|
|
||||||
groupName, owner);
|
|
||||||
GroupUser[] usersArray = new GroupUser[users.size()];
|
|
||||||
users.toArray(usersArray);
|
|
||||||
return Response.status(Response.Status.OK).entity(usersArray).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/owner/{owner}/name/{groupName}/devices")
|
@Path("/owner/{owner}/name/{groupName}/devices")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
|
@QueryParam("start") int startIdx, @QueryParam("length") int length);
|
||||||
try {
|
|
||||||
PaginationResult paginationResult = DeviceMgtAPIUtils
|
|
||||||
.getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length);
|
|
||||||
if (paginationResult.getRecordsTotal() > 0) {
|
|
||||||
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/owner/{owner}/name/{groupName}/devices/count")
|
@Path("/owner/{owner}/name/{groupName}/devices/count")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getDeviceCount(@PathParam("groupName") String groupName,
|
Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner);
|
||||||
@PathParam("owner") String owner) {
|
|
||||||
try {
|
|
||||||
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner);
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("/owner/{owner}/name/{groupName}/devices")
|
@Path("/owner/{owner}/name/{groupName}/devices")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response addDevice(@PathParam("groupName") String groupName,
|
Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) {
|
DeviceIdentifier deviceIdentifier);
|
||||||
try {
|
|
||||||
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
|
|
||||||
deviceIdentifier, groupName, owner);
|
|
||||||
if (isAdded) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@DELETE
|
@DELETE
|
||||||
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
|
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response removeDevice(@PathParam("groupName") String groupName,
|
Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
@PathParam("owner") String owner, @PathParam("deviceId") String deviceId,
|
@PathParam("deviceId") String deviceId, @PathParam("deviceType") String deviceType);
|
||||||
@PathParam("deviceType") String deviceType) {
|
|
||||||
try {
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
|
|
||||||
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(
|
|
||||||
deviceIdentifier, groupName, owner);
|
|
||||||
if (isRemoved) {
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
} else {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions")
|
@Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response getPermissions(@PathParam("userName") String userName,
|
Response getPermissions(@PathParam("userName") String userName, @PathParam("groupName") String groupName,
|
||||||
@PathParam("groupName") String groupName,
|
@PathParam("owner") String owner);
|
||||||
@PathParam("owner") String owner) {
|
|
||||||
try {
|
|
||||||
String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
|
||||||
.getPermissions(userName, groupName, owner);
|
|
||||||
return Response.status(Response.Status.OK).entity(permissions).build();
|
|
||||||
} catch (UserDoesNotExistException e) {
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
|
||||||
} catch (GroupManagementException e) {
|
|
||||||
log.error(e.getMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,28 +18,18 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
|
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.*;
|
||||||
import javax.ws.rs.POST;
|
|
||||||
import javax.ws.rs.Path;
|
|
||||||
import javax.ws.rs.PathParam;
|
|
||||||
import javax.ws.rs.Produces;
|
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents license related operations.
|
* This class represents license related operations.
|
||||||
*/
|
*/
|
||||||
|
@Api(value = "License")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class License {
|
public interface License {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(License.class);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method returns the license text related to a given device type and language code.
|
* This method returns the license text related to a given device type and language code.
|
||||||
@ -49,29 +39,10 @@ public class License {
|
|||||||
* @return Returns the license text
|
* @return Returns the license text
|
||||||
*/
|
*/
|
||||||
@GET
|
@GET
|
||||||
@Path ("{deviceType}/{languageCode}")
|
@Path("{deviceType}/{languageCode}")
|
||||||
@Produces ({MediaType.APPLICATION_JSON})
|
@Produces({ MediaType.APPLICATION_JSON })
|
||||||
public Response getLicense(@PathParam ("deviceType") String deviceType,
|
Response getLicense(@PathParam("deviceType") String deviceType,
|
||||||
@PathParam("languageCode") String languageCode) {
|
@PathParam("languageCode") String languageCode);
|
||||||
|
|
||||||
org.wso2.carbon.device.mgt.common.license.mgt.License license;
|
|
||||||
ResponsePayload responsePayload;
|
|
||||||
try {
|
|
||||||
license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode);
|
|
||||||
if (license == null) {
|
|
||||||
return Response.status(HttpStatus.SC_NOT_FOUND).build();
|
|
||||||
}
|
|
||||||
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
|
|
||||||
messageFromServer("License for '" + deviceType + "' was retrieved successfully").
|
|
||||||
responseContent(license.getText()).
|
|
||||||
build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method is used to add license to a specific device type.
|
* This method is used to add license to a specific device type.
|
||||||
@ -81,21 +52,7 @@ public class License {
|
|||||||
* @return Returns the acknowledgement for the action
|
* @return Returns the acknowledgement for the action
|
||||||
*/
|
*/
|
||||||
@POST
|
@POST
|
||||||
@Path ("{deviceType}")
|
@Path("{deviceType}")
|
||||||
public Response addLicense(@PathParam ("deviceType") String deviceType,
|
Response addLicense(@PathParam("deviceType") String deviceType,
|
||||||
org.wso2.carbon.device.mgt.common.license.mgt.License license) {
|
org.wso2.carbon.device.mgt.common.license.mgt.License license);
|
||||||
|
|
||||||
ResponsePayload responsePayload;
|
|
||||||
try {
|
|
||||||
DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license);
|
|
||||||
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
|
|
||||||
messageFromServer("License added successfully for '" + deviceType + "' device type").
|
|
||||||
build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while adding license for '" + deviceType + "' device type";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,203 +18,52 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
|
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
|
||||||
import org.wso2.carbon.device.mgt.common.Platform;
|
|
||||||
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.ApplicationManager;
|
|
||||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
import javax.ws.rs.POST;
|
import javax.ws.rs.POST;
|
||||||
import javax.ws.rs.Path;
|
import javax.ws.rs.Path;
|
||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.Produces;
|
|
||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Operation related REST-API implementation.
|
*
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@Api(value = "Operation")
|
||||||
@Produces({"application/json", "application/xml"})
|
public interface Operation {
|
||||||
@Consumes({"application/json", "application/xml"})
|
|
||||||
public class Operation {
|
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Operation.class);
|
|
||||||
|
|
||||||
/* @deprecated */
|
/* @deprecated */
|
||||||
@GET
|
@GET
|
||||||
public Response getAllOperations() {
|
Response getAllOperations();
|
||||||
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
|
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
try {
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
operations = dmService.getOperations(null);
|
|
||||||
} catch (OperationManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the operations for the device.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(operations).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("paginate/{type}/{id}")
|
@Path("paginate/{type}/{id}")
|
||||||
public Response getDeviceOperations(
|
Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id,
|
||||||
@PathParam("type") String type, @PathParam("id") String id, @QueryParam("start") int startIdx,
|
@QueryParam("start") int startIdx, @QueryParam("length") int length,
|
||||||
@QueryParam("length") int length, @QueryParam("search") String search) {
|
@QueryParam("search") String search);
|
||||||
PaginationResult operations;
|
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
|
|
||||||
try {
|
|
||||||
deviceIdentifier.setType(type);
|
|
||||||
deviceIdentifier.setId(id);
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
operations = dmService.getOperations(deviceIdentifier, paginationRequest);
|
|
||||||
} catch (OperationManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the operations for the device.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(operations).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{type}/{id}")
|
@Path("{type}/{id}")
|
||||||
public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) {
|
Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
|
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
try {
|
|
||||||
deviceIdentifier.setType(type);
|
|
||||||
deviceIdentifier.setId(id);
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
operations = dmService.getOperations(deviceIdentifier);
|
|
||||||
} catch (OperationManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the operations for the device.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(operations).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/* @deprecated */
|
/* @deprecated */
|
||||||
@POST
|
@POST
|
||||||
public Response addOperation(DeviceOperationContext operationContext) {
|
Response addOperation(DeviceOperationContext operationContext);
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices());
|
|
||||||
if (operationId > 0) {
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responseMsg.setMessageFromServer("Operation has added successfully.");
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (OperationManagementException e) {
|
|
||||||
String msg = "Error occurred while saving the operation";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{type}/{id}/apps")
|
@Path("{type}/{id}/apps")
|
||||||
public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) {
|
Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
List<Application> applications;
|
|
||||||
ApplicationManagementProviderService appManagerConnector;
|
|
||||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
|
||||||
try {
|
|
||||||
deviceIdentifier.setType(type);
|
|
||||||
deviceIdentifier.setId(id);
|
|
||||||
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
|
||||||
applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier);
|
|
||||||
} catch (ApplicationManagementException e) {
|
|
||||||
String msg = "Error occurred while fetching the apps of the device.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.CREATED).entity(applications).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("installApp/{tenantDomain}")
|
@Path("installApp/{tenantDomain}")
|
||||||
public Response installApplication(ApplicationWrapper applicationWrapper,
|
Response installApplication(ApplicationWrapper applicationWrapper,
|
||||||
@PathParam("tenantDomain") String tenantDomain) {
|
@PathParam("tenantDomain") String tenantDomain);
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
ApplicationManager appManagerConnector;
|
|
||||||
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
|
|
||||||
try {
|
|
||||||
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
|
||||||
MobileApp mobileApp = applicationWrapper.getApplication();
|
|
||||||
|
|
||||||
if (applicationWrapper.getDeviceIdentifiers() != null) {
|
|
||||||
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
|
|
||||||
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
|
|
||||||
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
|
|
||||||
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
|
|
||||||
operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
|
|
||||||
}
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responseMsg.setMessageFromServer("Application installation request has been sent to the device.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (ApplicationManagementException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while saving the operation";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("uninstallApp/{tenantDomain}")
|
@Path("uninstallApp/{tenantDomain}")
|
||||||
public Response uninstallApplication(ApplicationWrapper applicationWrapper,
|
Response uninstallApplication(ApplicationWrapper applicationWrapper,
|
||||||
@PathParam("tenantDomain") String tenantDomain) {
|
@PathParam("tenantDomain") String tenantDomain);
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
ApplicationManager appManagerConnector;
|
|
||||||
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
|
|
||||||
try {
|
|
||||||
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
|
||||||
MobileApp mobileApp = applicationWrapper.getApplication();
|
|
||||||
|
|
||||||
if (applicationWrapper.getDeviceIdentifiers() != null) {
|
|
||||||
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
|
|
||||||
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
|
|
||||||
operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp);
|
|
||||||
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
|
|
||||||
operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
|
|
||||||
}
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responseMsg.setMessageFromServer("Application removal request has been sent to the device.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (ApplicationManagementException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while saving the operation";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@ -18,23 +18,10 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
|
||||||
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
|
||||||
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
|
||||||
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
|
|
||||||
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
|
|
||||||
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
|
|
||||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
|
||||||
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@ -45,386 +32,83 @@ import javax.ws.rs.PathParam;
|
|||||||
import javax.ws.rs.Produces;
|
import javax.ws.rs.Produces;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
/**
|
||||||
public class Policy {
|
*
|
||||||
private static Log log = LogFactory.getLog(Policy.class);
|
*/
|
||||||
|
@Api(value = "Policy")
|
||||||
|
public interface Policy {
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("inactive-policy")
|
@Path("inactive-policy")
|
||||||
public Response addPolicy(PolicyWrapper policyWrapper) {
|
Response addPolicy(PolicyWrapper policyWrapper);
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
|
||||||
policy.setPolicyName(policyWrapper.getPolicyName());
|
|
||||||
policy.setProfileId(policyWrapper.getProfileId());
|
|
||||||
policy.setDescription(policyWrapper.getDescription());
|
|
||||||
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
|
||||||
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
|
||||||
policy.setRoles(policyWrapper.getRoles());
|
|
||||||
policy.setUsers(policyWrapper.getUsers());
|
|
||||||
policy.setTenantId(policyWrapper.getTenantId());
|
|
||||||
policy.setCompliance(policyWrapper.getCompliance());
|
|
||||||
|
|
||||||
return addPolicy(policyManagementService, responseMsg, policy);
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("active-policy")
|
@Path("active-policy")
|
||||||
public Response addActivePolicy(PolicyWrapper policyWrapper) {
|
Response addActivePolicy(PolicyWrapper policyWrapper);
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
|
||||||
policy.setPolicyName(policyWrapper.getPolicyName());
|
|
||||||
policy.setProfileId(policyWrapper.getProfileId());
|
|
||||||
policy.setDescription(policyWrapper.getDescription());
|
|
||||||
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
|
||||||
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
|
||||||
policy.setRoles(policyWrapper.getRoles());
|
|
||||||
policy.setUsers(policyWrapper.getUsers());
|
|
||||||
policy.setTenantId(policyWrapper.getTenantId());
|
|
||||||
policy.setCompliance(policyWrapper.getCompliance());
|
|
||||||
policy.setActive(true);
|
|
||||||
|
|
||||||
return addPolicy(policyManagementService, responseMsg, policy);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg,
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy) {
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
pap.addPolicy(policy);
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responseMsg.setMessageFromServer("Policy has been added successfully.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({ MediaType.APPLICATION_JSON})
|
||||||
public Response getAllPolicies() {
|
Response getAllPolicies();
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
List<org.wso2.carbon.policy.mgt.common.Policy> policies;
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
|
||||||
policies = policyAdministratorPoint.getPolicies();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
|
|
||||||
responsePayload.setResponseContent(policies);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
@Path("{id}")
|
@Path("{id}")
|
||||||
public Response getPolicy(@PathParam("id") int policyId) {
|
Response getPolicy(@PathParam("id") int policyId);
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
final org.wso2.carbon.policy.mgt.common.Policy policy;
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
|
||||||
policy = policyAdministratorPoint.getPolicy(policyId);
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
if (policy == null){
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
|
|
||||||
responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found.");
|
|
||||||
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
|
|
||||||
responsePayload.setResponseContent(policy);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("count")
|
@Path("count")
|
||||||
public Response getPolicyCount() {
|
Response getPolicyCount();
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
|
||||||
Integer count = policyAdministratorPoint.getPolicyCount();
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Path("{id}")
|
@Path("{id}")
|
||||||
public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) {
|
Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId);
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
|
||||||
policy.setPolicyName(policyWrapper.getPolicyName());
|
|
||||||
policy.setId(policyId);
|
|
||||||
policy.setProfileId(policyWrapper.getProfileId());
|
|
||||||
policy.setDescription(policyWrapper.getDescription());
|
|
||||||
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
|
||||||
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
|
||||||
policy.setRoles(policyWrapper.getRoles());
|
|
||||||
policy.setUsers(policyWrapper.getUsers());
|
|
||||||
policy.setTenantId(policyWrapper.getTenantId());
|
|
||||||
policy.setCompliance(policyWrapper.getCompliance());
|
|
||||||
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
pap.updatePolicy(policy);
|
|
||||||
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responseMsg.setMessageFromServer("Policy has been updated successfully.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception in policy update.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Path("priorities")
|
@Path("priorities")
|
||||||
@Consumes({MediaType.APPLICATION_JSON})
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) {
|
Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies);
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
List<org.wso2.carbon.policy.mgt.common.Policy> policiesToUpdate =
|
|
||||||
new ArrayList<>(priorityUpdatedPolicies.size());
|
|
||||||
int i;
|
|
||||||
for (i = 0; i < priorityUpdatedPolicies.size(); i++) {
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy();
|
|
||||||
policyObj.setId(priorityUpdatedPolicies.get(i).getId());
|
|
||||||
policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority());
|
|
||||||
policiesToUpdate.add(policyObj);
|
|
||||||
}
|
|
||||||
boolean policiesUpdated;
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate);
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Exception in updating policy priorities.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
if (policiesUpdated) {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Policy Priorities successfully updated.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
|
||||||
responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
@Path("bulk-remove")
|
@Path("bulk-remove")
|
||||||
@Consumes("application/json")
|
@Consumes("application/json")
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
public Response bulkRemovePolicy(List<Integer> policyIds) {
|
Response bulkRemovePolicy(List<Integer> policyIds);
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
boolean policyDeleted = true;
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
for(int i : policyIds) {
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i);
|
|
||||||
if(!pap.deletePolicy(policy)){
|
|
||||||
policyDeleted = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Exception in deleting policies.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
if (policyDeleted) {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Policies have been successfully deleted.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
|
||||||
responsePayload.setMessageFromServer("Policy does not exist.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
@Path("activate")
|
@Path("activate")
|
||||||
public Response activatePolicy(List<Integer> policyIds) {
|
Response activatePolicy(List<Integer> policyIds);
|
||||||
try {
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
for(int i : policyIds) {
|
|
||||||
pap.activatePolicy(i);
|
|
||||||
}
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Exception in activating policies.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Selected policies have been successfully activated.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
@Path("inactivate")
|
@Path("inactivate")
|
||||||
public Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException {
|
Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException;
|
||||||
|
|
||||||
try {
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
for(int i : policyIds) {
|
|
||||||
pap.inactivatePolicy(i);
|
|
||||||
}
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Exception in inactivating policies.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Selected policies have been successfully inactivated.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@PUT
|
@PUT
|
||||||
@Produces("application/json")
|
@Produces("application/json")
|
||||||
@Path("apply-changes")
|
@Path("apply-changes")
|
||||||
public Response applyChanges() {
|
Response applyChanges();
|
||||||
|
|
||||||
try {
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
pap.publishChanges();
|
|
||||||
|
|
||||||
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Exception in applying changes.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Changes have been successfully updated.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("start-task/{milliseconds}")
|
@Path("start-task/{milliseconds}")
|
||||||
public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) {
|
Response startTaskService(@PathParam("milliseconds") int monitoringFrequency);
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
try {
|
|
||||||
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
|
||||||
taskScheduleService.startTask(monitoringFrequency);
|
|
||||||
|
|
||||||
|
|
||||||
} catch (PolicyMonitoringTaskException e) {
|
|
||||||
String msg = "Policy Management related exception.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Policy monitoring service started successfully.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("update-task/{milliseconds}")
|
@Path("update-task/{milliseconds}")
|
||||||
public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) {
|
Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency);
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
try {
|
|
||||||
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
|
||||||
taskScheduleService.updateTask(monitoringFrequency);
|
|
||||||
|
|
||||||
} catch (PolicyMonitoringTaskException e) {
|
|
||||||
String msg = "Policy Management related exception.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Policy monitoring service updated successfully.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("stop-task")
|
@Path("stop-task")
|
||||||
public Response stopTaskService() {
|
Response stopTaskService();
|
||||||
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
try {
|
|
||||||
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
|
||||||
taskScheduleService.stopTask();
|
|
||||||
|
|
||||||
} catch (PolicyMonitoringTaskException e) {
|
|
||||||
String msg = "Policy Management related exception.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Policy monitoring service stopped successfully.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{type}/{id}")
|
@Path("{type}/{id}")
|
||||||
public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) {
|
Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
try {
|
|
||||||
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier);
|
|
||||||
return Response.status(Response.Status.OK).entity(complianceData).build();
|
|
||||||
} catch (PolicyComplianceException e) {
|
|
||||||
String msg = "Error occurred while getting the compliance data.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{type}/{id}/active-policy")
|
@Path("{type}/{id}/active-policy")
|
||||||
public Response getDeviceActivePolicy(@PathParam("type") String type,
|
Response getDeviceActivePolicy(@PathParam("type") String type, @PathParam("id") String id);
|
||||||
@PathParam("id") String id) {
|
|
||||||
try {
|
|
||||||
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService
|
|
||||||
.getAppliedPolicyToDevice(deviceIdentifier);
|
|
||||||
return Response.status(Response.Status.OK).entity(policy).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Error occurred while getting the current policy.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,13 +18,7 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.logging.Log;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
|
|
||||||
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
|
||||||
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
|
||||||
|
|
||||||
import javax.ws.rs.DELETE;
|
import javax.ws.rs.DELETE;
|
||||||
import javax.ws.rs.POST;
|
import javax.ws.rs.POST;
|
||||||
@ -32,55 +26,22 @@ import javax.ws.rs.Path;
|
|||||||
import javax.ws.rs.PathParam;
|
import javax.ws.rs.PathParam;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* These end points provide profile related operations.
|
||||||
|
*/
|
||||||
|
@Api(value = "Profile")
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
public class Profile {
|
public interface Profile {
|
||||||
private static Log log = LogFactory.getLog(Profile.class);
|
|
||||||
|
|
||||||
@POST
|
@POST
|
||||||
public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) {
|
Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile);
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
try {
|
@POST
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
@Path("{id}")
|
||||||
profile = pap.addProfile(profile);
|
Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
|
||||||
return Response.status(Response.Status.OK).entity(profile).build();
|
@PathParam("id") String profileId);
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
@DELETE
|
||||||
log.error(msg, e);
|
@Path("{id}")
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
Response deleteProfile(@PathParam("id") int profileId);
|
||||||
}
|
|
||||||
}
|
|
||||||
@POST
|
|
||||||
@Path("{id}")
|
|
||||||
public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
|
|
||||||
@PathParam("id") String profileId) {
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
pap.updateProfile(profile);
|
|
||||||
responseMsg.setMessageFromServer("Profile has been updated successfully.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responseMsg).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@DELETE
|
|
||||||
@Path("{id}")
|
|
||||||
public Response deleteProfile(@PathParam("id") int profileId) {
|
|
||||||
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
|
||||||
ResponsePayload responseMsg = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
|
||||||
org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId);
|
|
||||||
pap.deleteProfile(profile);
|
|
||||||
responseMsg.setMessageFromServer("Profile has been deleted successfully.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responseMsg).build();
|
|
||||||
} catch (PolicyManagementException e) {
|
|
||||||
String msg = "Policy Management related exception";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,25 +18,8 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.httpclient.HttpStatus;
|
import io.swagger.annotations.Api;
|
||||||
import org.apache.commons.logging.Log;
|
|
||||||
import org.apache.commons.logging.LogFactory;
|
|
||||||
import org.wso2.carbon.CarbonConstants;
|
|
||||||
import org.wso2.carbon.base.MultitenantConstants;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
|
|
||||||
import org.wso2.carbon.user.api.AuthorizationManager;
|
|
||||||
import org.wso2.carbon.user.api.Permission;
|
|
||||||
import org.wso2.carbon.user.api.UserRealm;
|
|
||||||
import org.wso2.carbon.user.api.UserStoreException;
|
|
||||||
import org.wso2.carbon.user.api.UserStoreManager;
|
|
||||||
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
|
|
||||||
import org.wso2.carbon.user.mgt.UserRealmProxy;
|
|
||||||
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
|
|
||||||
import org.wso2.carbon.user.mgt.common.UserAdminException;
|
|
||||||
|
|
||||||
import javax.ws.rs.DELETE;
|
import javax.ws.rs.DELETE;
|
||||||
import javax.ws.rs.GET;
|
import javax.ws.rs.GET;
|
||||||
@ -48,393 +31,56 @@ import javax.ws.rs.Produces;
|
|||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
/**
|
||||||
public class Role {
|
*
|
||||||
|
*/
|
||||||
|
@Api(value = "Role")
|
||||||
|
public interface Role {
|
||||||
|
|
||||||
private static Log log = LogFactory.getLog(Role.class);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user roles (except all internal roles) from system.
|
|
||||||
*
|
|
||||||
* @return A list of users
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({ MediaType.APPLICATION_JSON})
|
||||||
public Response getRoles() {
|
Response getRoles();
|
||||||
List<String> filteredRoles;
|
|
||||||
try {
|
|
||||||
filteredRoles = getRolesFromUserStore();
|
|
||||||
} catch (MDMAPIException e) {
|
|
||||||
log.error(e.getErrorMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
|
||||||
responsePayload.setResponseContent(filteredRoles);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user roles by user store(except all internal roles) from system.
|
|
||||||
*
|
|
||||||
* @return A list of users
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{userStore}")
|
@Path("{userStore}")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getRoles(@PathParam("userStore") String userStore) {
|
Response getRoles(@PathParam("userStore") String userStore);
|
||||||
String[] roles;
|
|
||||||
try {
|
|
||||||
AbstractUserStoreManager abstractUserStoreManager =
|
|
||||||
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of user roles");
|
|
||||||
}
|
|
||||||
roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true);
|
|
||||||
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of user roles.";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
// removing all internal roles and roles created for Service-providers
|
|
||||||
List<String> filteredRoles = new ArrayList<>();
|
|
||||||
for (String role : roles) {
|
|
||||||
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
|
|
||||||
filteredRoles.add(role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
|
||||||
responsePayload.setResponseContent(filteredRoles);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user roles by providing a filtering criteria(except all internal roles & system roles) from system.
|
|
||||||
*
|
|
||||||
* @return A list of users
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("search")
|
@Path("search")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getMatchingRoles(@QueryParam("filter") String filter) {
|
Response getMatchingRoles(@QueryParam("filter") String filter);
|
||||||
String[] roles;
|
|
||||||
try {
|
|
||||||
AbstractUserStoreManager abstractUserStoreManager =
|
|
||||||
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of user roles using filter : " + filter);
|
|
||||||
}
|
|
||||||
roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true);
|
|
||||||
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
// removing all internal roles and roles created for Service-providers
|
|
||||||
List<String> filteredRoles = new ArrayList<>();
|
|
||||||
for (String role : roles) {
|
|
||||||
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
|
|
||||||
filteredRoles.add(role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("All matching user roles were successfully retrieved.");
|
|
||||||
responsePayload.setResponseContent(filteredRoles);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get role permissions.
|
|
||||||
*
|
|
||||||
* @return list of permissions
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("permissions")
|
@Path("permissions")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getPermissions(@QueryParam("rolename") String roleName) {
|
Response getPermissions(@QueryParam("rolename") String roleName);
|
||||||
try {
|
|
||||||
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
|
|
||||||
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
|
|
||||||
final UIPermissionNode rolePermissions;
|
|
||||||
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
|
|
||||||
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
|
|
||||||
}
|
|
||||||
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
|
|
||||||
rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("All permissions retrieved");
|
|
||||||
responsePayload.setResponseContent(rolePermissions);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} catch (UserAdminException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the user role";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user role of the system
|
|
||||||
*
|
|
||||||
* @return user role
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("role")
|
@Path("role")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getRole(@QueryParam("rolename") String roleName) {
|
Response getRole(@QueryParam("rolename") String roleName);
|
||||||
RoleWrapper roleWrapper = new RoleWrapper();
|
|
||||||
try {
|
|
||||||
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
|
|
||||||
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
|
|
||||||
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
|
|
||||||
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
|
|
||||||
}
|
|
||||||
|
|
||||||
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of user roles");
|
|
||||||
}
|
|
||||||
if (userStoreManager.isExistingRole(roleName)) {
|
|
||||||
roleWrapper.setRoleName(roleName);
|
|
||||||
roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName));
|
|
||||||
// Get the permission nodes and hand picking only device management and login perms
|
|
||||||
final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
|
|
||||||
ArrayList<String> permList = new ArrayList<>();
|
|
||||||
iteratePermissions(rolePermissions, permList);
|
|
||||||
roleWrapper.setPermissionList(rolePermissions);
|
|
||||||
String[] permListAr = new String[permList.size()];
|
|
||||||
roleWrapper.setPermissions(permList.toArray(permListAr));
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | UserAdminException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the user role";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
|
||||||
responsePayload.setResponseContent(roleWrapper);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy)
|
|
||||||
throws UserAdminException {
|
|
||||||
final UIPermissionNode rolePermissions =
|
|
||||||
userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
|
|
||||||
UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2];
|
|
||||||
|
|
||||||
for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) {
|
|
||||||
if (permissionNode.getResourcePath().equals("/permission/admin")) {
|
|
||||||
for (UIPermissionNode node : permissionNode.getNodeList()) {
|
|
||||||
if (node.getResourcePath().equals("/permission/admin/device-mgt")) {
|
|
||||||
deviceMgtPermissions[0] = node;
|
|
||||||
} else if (node.getResourcePath().equals("/permission/admin/login")) {
|
|
||||||
deviceMgtPermissions[1] = node;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rolePermissions.setNodeList(deviceMgtPermissions);
|
|
||||||
return rolePermissions;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API is used to persist a new Role
|
|
||||||
*
|
|
||||||
* @param roleWrapper for role
|
|
||||||
* @return response
|
|
||||||
*/
|
|
||||||
@POST
|
@POST
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response addRole(RoleWrapper roleWrapper) {
|
Response addRole(RoleWrapper roleWrapper);
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Persisting the role to user store");
|
|
||||||
}
|
|
||||||
Permission[] permissions = null;
|
|
||||||
if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) {
|
|
||||||
permissions = new Permission[roleWrapper.getPermissions().length];
|
|
||||||
|
|
||||||
for (int i = 0; i < permissions.length; i++) {
|
|
||||||
String permission = roleWrapper.getPermissions()[i];
|
|
||||||
permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = e.getMessage();
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API is used to update a role Role
|
|
||||||
*
|
|
||||||
* @param roleWrapper for role
|
|
||||||
* @return response
|
|
||||||
*/
|
|
||||||
@PUT
|
@PUT
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) {
|
Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper);
|
||||||
String newRoleName = roleWrapper.getRoleName();
|
|
||||||
try {
|
|
||||||
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Updating the role to user store");
|
|
||||||
}
|
|
||||||
if (newRoleName != null && !roleName.equals(newRoleName)) {
|
|
||||||
userStoreManager.updateRoleName(roleName, newRoleName);
|
|
||||||
}
|
|
||||||
if (roleWrapper.getUsers() != null) {
|
|
||||||
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
|
||||||
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)),
|
|
||||||
Arrays.asList(roleWrapper.getUsers()));
|
|
||||||
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
|
|
||||||
.getObjectsToAdd().size()]);
|
|
||||||
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
|
|
||||||
.getObjectsToRemove().size()]);
|
|
||||||
userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd);
|
|
||||||
}
|
|
||||||
if (roleWrapper.getPermissions() != null) {
|
|
||||||
// Delete all authorizations for the current role before authorizing the permission tree
|
|
||||||
authorizationManager.clearRoleAuthorization(roleName);
|
|
||||||
if (roleWrapper.getPermissions().length > 0) {
|
|
||||||
for (int i = 0; i < roleWrapper.getPermissions().length; i++) {
|
|
||||||
String permission = roleWrapper.getPermissions()[i];
|
|
||||||
authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = e.getMessage();
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API is used to delete a role and authorizations
|
|
||||||
*
|
|
||||||
* @param roleName to delete
|
|
||||||
* @return response
|
|
||||||
*/
|
|
||||||
@DELETE
|
@DELETE
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response deleteRole(@QueryParam("rolename") String roleName) {
|
Response deleteRole(@QueryParam("rolename") String roleName);
|
||||||
try {
|
|
||||||
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Deleting the role in user store");
|
|
||||||
}
|
|
||||||
userStoreManager.deleteRole(roleName);
|
|
||||||
// Delete all authorizations for the current role before deleting
|
|
||||||
authorizationManager.clearRoleAuthorization(roleName);
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while deleting the role: " + roleName;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API is used to update users of a role
|
|
||||||
*
|
|
||||||
* @param roleName to update
|
|
||||||
* @param userList of the users
|
|
||||||
* @return response
|
|
||||||
*/
|
|
||||||
@PUT
|
@PUT
|
||||||
@Path("users")
|
@Path("users")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response updateUsers(@QueryParam("rolename") String roleName, List<String> userList) {
|
Response updateUsers(@QueryParam("rolename") String roleName, List<String> userList);
|
||||||
try {
|
|
||||||
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Updating the users of a role");
|
|
||||||
}
|
|
||||||
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
|
||||||
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)),
|
|
||||||
userList);
|
|
||||||
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
|
|
||||||
.getObjectsToAdd().size()]);
|
|
||||||
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
|
|
||||||
.getObjectsToRemove().size()]);
|
|
||||||
|
|
||||||
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while saving the users of the role: " + roleName;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
private ArrayList<String> iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList<String> list) {
|
|
||||||
for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) {
|
|
||||||
list.add(permissionNode.getResourcePath());
|
|
||||||
if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) {
|
|
||||||
iteratePermissions(permissionNode, list);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return list;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This method is used to retrieve the role count of the system.
|
|
||||||
*
|
|
||||||
* @return returns the count.
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("count")
|
@Path("count")
|
||||||
public Response getRoleCount() {
|
Response getRoleCount();
|
||||||
try {
|
|
||||||
List<String> filteredRoles = getRolesFromUserStore();
|
|
||||||
Integer count = filteredRoles.size();
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (MDMAPIException e) {
|
|
||||||
log.error(e.getErrorMessage(), e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> getRolesFromUserStore() throws MDMAPIException {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
String[] roles;
|
|
||||||
try {
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of user roles");
|
|
||||||
}
|
|
||||||
roles = userStoreManager.getRoleNames();
|
|
||||||
|
|
||||||
} catch (UserStoreException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of user roles.";
|
|
||||||
throw new MDMAPIException(msg, e);
|
|
||||||
}
|
|
||||||
// removing all internal roles and roles created for Service-providers
|
|
||||||
List<String> filteredRoles = new ArrayList<>();
|
|
||||||
for (String role : roles) {
|
|
||||||
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
|
|
||||||
filteredRoles.add(role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return filteredRoles;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -18,27 +18,9 @@
|
|||||||
|
|
||||||
package org.wso2.carbon.device.mgt.jaxrs.api;
|
package org.wso2.carbon.device.mgt.jaxrs.api;
|
||||||
|
|
||||||
import org.apache.commons.codec.binary.Base64;
|
import io.swagger.annotations.Api;
|
||||||
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.wso2.carbon.context.CarbonContext;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
|
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
|
||||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
|
||||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
|
||||||
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
|
||||||
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
|
|
||||||
import org.wso2.carbon.user.api.UserStoreException;
|
|
||||||
import org.wso2.carbon.user.api.UserStoreManager;
|
|
||||||
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
|
||||||
|
|
||||||
import javax.ws.rs.Consumes;
|
import javax.ws.rs.Consumes;
|
||||||
import javax.ws.rs.DELETE;
|
import javax.ws.rs.DELETE;
|
||||||
@ -51,707 +33,84 @@ import javax.ws.rs.Produces;
|
|||||||
import javax.ws.rs.QueryParam;
|
import javax.ws.rs.QueryParam;
|
||||||
import javax.ws.rs.core.MediaType;
|
import javax.ws.rs.core.MediaType;
|
||||||
import javax.ws.rs.core.Response;
|
import javax.ws.rs.core.Response;
|
||||||
import java.io.UnsupportedEncodingException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.HashMap;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
|
||||||
import java.util.Properties;
|
|
||||||
import java.util.Random;
|
|
||||||
import java.util.TreeSet;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents the JAX-RS services of User related functionality.
|
* This represents the JAX-RS services of User related functionality.
|
||||||
*/
|
*/
|
||||||
@SuppressWarnings("NonJaxWsWebServices")
|
@Api(value = "User")
|
||||||
public class User {
|
public interface User {
|
||||||
|
|
||||||
private static final String ROLE_EVERYONE = "Internal/everyone";
|
|
||||||
private static Log log = LogFactory.getLog(User.class);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to add user to emm-user-store.
|
|
||||||
*
|
|
||||||
* @param userWrapper Wrapper object representing input json payload
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object
|
|
||||||
*/
|
|
||||||
@POST
|
@POST
|
||||||
@Consumes({MediaType.APPLICATION_JSON})
|
@Consumes({ MediaType.APPLICATION_JSON})
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response addUser(UserWrapper userWrapper) {
|
Response addUser(UserWrapper userWrapper);
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
|
|
||||||
// if user already exists
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + userWrapper.getUsername() +
|
|
||||||
" already exists. Therefore, request made to add user was refused.");
|
|
||||||
}
|
|
||||||
// returning response with bad request state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
|
|
||||||
responsePayload.
|
|
||||||
setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
|
||||||
" already exists. Therefore, request made to add user was refused.");
|
|
||||||
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
String initialUserPassword = generateInitialUserPassword();
|
|
||||||
Map<String, String> defaultUserClaims =
|
|
||||||
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
|
|
||||||
userWrapper.getEmailAddress());
|
|
||||||
// calling addUser method of carbon user api
|
|
||||||
userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword,
|
|
||||||
userWrapper.getRoles(), defaultUserClaims, null);
|
|
||||||
// invite newly added user to enroll device
|
|
||||||
inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
|
|
||||||
// Outputting debug message upon successful addition of user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
|
|
||||||
}
|
|
||||||
// returning response with success state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
|
||||||
" was successfully added.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to get user information from emm-user-store.
|
|
||||||
*
|
|
||||||
* @param username User-name of the user
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("view")
|
@Path("view")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getUser(@QueryParam("username") String username) {
|
Response getUser(@QueryParam("username") String username);
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (userStoreManager.isExistingUser(username)) {
|
|
||||||
UserWrapper user = new UserWrapper();
|
|
||||||
user.setUsername(username);
|
|
||||||
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
|
||||||
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
|
||||||
// Outputting debug message upon successful retrieval of user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " was found.");
|
|
||||||
}
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("User information was retrieved successfully.");
|
|
||||||
responsePayload.setResponseContent(user);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
// Outputting debug message upon trying to remove non-existing user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " does not exist.");
|
|
||||||
}
|
|
||||||
// returning response with bad request state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
|
||||||
responsePayload.setMessageFromServer(
|
|
||||||
"User by username: " + username + " does not exist.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Exception in trying to retrieve user by username: " + username;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update user in user store
|
|
||||||
*
|
|
||||||
* @param userWrapper Wrapper object representing input json payload
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
*/
|
|
||||||
@PUT
|
@PUT
|
||||||
@Consumes({MediaType.APPLICATION_JSON})
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) {
|
Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username);
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
|
|
||||||
Map<String, String> defaultUserClaims =
|
|
||||||
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
|
|
||||||
userWrapper.getEmailAddress());
|
|
||||||
if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
|
|
||||||
// Decoding Base64 encoded password
|
|
||||||
byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
|
|
||||||
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
|
|
||||||
new String(decodedBytes, "UTF-8"));
|
|
||||||
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
|
|
||||||
}
|
|
||||||
List<String> listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
|
|
||||||
final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]);
|
|
||||||
|
|
||||||
/*
|
|
||||||
Use the Set theory to find the roles to delete and roles to add
|
|
||||||
The difference of roles in existingRolesSet and newRolesSet needed to be deleted
|
|
||||||
new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet
|
|
||||||
*/
|
|
||||||
final TreeSet<String> existingRolesSet = new TreeSet<>();
|
|
||||||
Collections.addAll(existingRolesSet, existingRoles);
|
|
||||||
final TreeSet<String> newRolesSet = new TreeSet<>();
|
|
||||||
Collections.addAll(newRolesSet, userWrapper.getRoles());
|
|
||||||
existingRolesSet.removeAll(newRolesSet);
|
|
||||||
// Now we have the roles to delete
|
|
||||||
String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]);
|
|
||||||
List<String> roles = new ArrayList<>(Arrays.asList(rolesToDelete));
|
|
||||||
roles.remove(ROLE_EVERYONE);
|
|
||||||
rolesToDelete = new String[0];
|
|
||||||
// Clearing and re-initializing the set
|
|
||||||
existingRolesSet.clear();
|
|
||||||
Collections.addAll(existingRolesSet, existingRoles);
|
|
||||||
newRolesSet.removeAll(existingRolesSet);
|
|
||||||
// Now we have the roles to add
|
|
||||||
String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]);
|
|
||||||
userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd);
|
|
||||||
userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
|
|
||||||
// Outputting debug message upon successful addition of user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
|
|
||||||
}
|
|
||||||
// returning response with success state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
|
||||||
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
|
||||||
" was successfully updated.");
|
|
||||||
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + userWrapper.getUsername() +
|
|
||||||
" doesn't exists. Therefore, request made to update user was refused.");
|
|
||||||
}
|
|
||||||
// returning response with bad request state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
|
|
||||||
responsePayload.
|
|
||||||
setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
|
||||||
" doesn't exists. Therefore, request made to update user was refused.");
|
|
||||||
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) {
|
|
||||||
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Private method to be used by addUser() to
|
|
||||||
* generate an initial user password for a user.
|
|
||||||
* This will be the password used by a user for his initial login to the system.
|
|
||||||
*
|
|
||||||
* @return {string} Initial User Password
|
|
||||||
*/
|
|
||||||
private String generateInitialUserPassword() {
|
|
||||||
int passwordLength = 6;
|
|
||||||
//defining the pool of characters to be used for initial password generation
|
|
||||||
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
|
|
||||||
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
||||||
String numericCharset = "0123456789";
|
|
||||||
Random randomGenerator = new Random();
|
|
||||||
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
|
|
||||||
int totalCharsetLength = totalCharset.length();
|
|
||||||
StringBuilder initialUserPassword = new StringBuilder();
|
|
||||||
for (int i = 0; i < passwordLength; i++) {
|
|
||||||
initialUserPassword
|
|
||||||
.append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
|
|
||||||
}
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Initial user password is created for new user: " + initialUserPassword);
|
|
||||||
}
|
|
||||||
return initialUserPassword.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to build default user claims.
|
|
||||||
*
|
|
||||||
* @param firstname First name of the user
|
|
||||||
* @param lastname Last name of the user
|
|
||||||
* @param emailAddress Email address of the user
|
|
||||||
* @return {Object} Default user claims to be provided
|
|
||||||
*/
|
|
||||||
private Map<String, String> buildDefaultUserClaims(String firstname, String lastname, String emailAddress) {
|
|
||||||
Map<String, String> defaultUserClaims = new HashMap<>();
|
|
||||||
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname);
|
|
||||||
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname);
|
|
||||||
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
|
|
||||||
}
|
|
||||||
return defaultUserClaims;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to remove user from emm-user-store.
|
|
||||||
*
|
|
||||||
* @param username Username of the user
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
*/
|
|
||||||
@DELETE
|
@DELETE
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response removeUser(@QueryParam("username") String username) {
|
Response removeUser(@QueryParam("username") String username);
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (userStoreManager.isExistingUser(username)) {
|
|
||||||
// if user already exists, trying to remove user
|
|
||||||
userStoreManager.deleteUser(username);
|
|
||||||
// Outputting debug message upon successful removal of user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " was successfully removed.");
|
|
||||||
}
|
|
||||||
// returning response with success state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer(
|
|
||||||
"User by username: " + username + " was successfully removed.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
// Outputting debug message upon trying to remove non-existing user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " does not exist for removal.");
|
|
||||||
}
|
|
||||||
// returning response with bad request state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
|
||||||
responsePayload.setMessageFromServer(
|
|
||||||
"User by username: " + username + " does not exist for removal.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Exception in trying to remove user by username: " + username;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* get all the roles except for the internal/xxx and application/xxx
|
|
||||||
*
|
|
||||||
* @param userStoreManager User Store Manager associated with the currently logged in user
|
|
||||||
* @param username Username of the currently logged in user
|
|
||||||
* @return the list of filtered roles
|
|
||||||
*/
|
|
||||||
private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username) {
|
|
||||||
String[] roleListOfUser = new String[0];
|
|
||||||
try {
|
|
||||||
roleListOfUser = userStoreManager.getRoleListOfUser(username);
|
|
||||||
} catch (UserStoreException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
List<String> filteredRoles = new ArrayList<>();
|
|
||||||
for (String role : roleListOfUser) {
|
|
||||||
if (!(role.startsWith("Internal/") || role.startsWith("Application/"))) {
|
|
||||||
filteredRoles.add(role);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return filteredRoles;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user's roles by username
|
|
||||||
*
|
|
||||||
* @param username Username of the user
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("roles")
|
@Path("roles")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getRoles(@QueryParam("username") String username) {
|
Response getRoles(@QueryParam("username") String username);
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (userStoreManager.isExistingUser(username)) {
|
|
||||||
responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username)));
|
|
||||||
// Outputting debug message upon successful removal of user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " was successfully removed.");
|
|
||||||
}
|
|
||||||
// returning response with success state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer(
|
|
||||||
"User roles obtained for user " + username);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
} else {
|
|
||||||
// Outputting debug message upon trying to remove non-existing user
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("User by username: " + username + " does not exist for role retrieval.");
|
|
||||||
}
|
|
||||||
// returning response with bad request state
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
|
||||||
responsePayload.setMessageFromServer(
|
|
||||||
"User by username: " + username + " does not exist for role retrieval.");
|
|
||||||
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Exception in trying to retrieve roles for user by username: " + username;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the list of all users with all user-related info.
|
|
||||||
*
|
|
||||||
* @return A list of users
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getAllUsers() {
|
Response getAllUsers();
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of users with all user-related information");
|
|
||||||
}
|
|
||||||
List<UserWrapper> userList;
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
String[] users = userStoreManager.listUsers("*", -1);
|
|
||||||
userList = new ArrayList<>(users.length);
|
|
||||||
UserWrapper user;
|
|
||||||
for (String username : users) {
|
|
||||||
user = new UserWrapper();
|
|
||||||
user.setUsername(username);
|
|
||||||
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
|
||||||
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
|
||||||
userList.add(user);
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of users";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
int count;
|
|
||||||
count = userList.size();
|
|
||||||
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
|
|
||||||
"Obtained user count: " + count);
|
|
||||||
responsePayload.setResponseContent(userList);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the list of all users with all user-related info.
|
|
||||||
*
|
|
||||||
* @return A list of users
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("{filter}")
|
@Path("{filter}")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response getMatchingUsers(@PathParam("filter") String filter) {
|
Response getMatchingUsers(@PathParam("filter") String filter);
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of users with all user-related information using the filter : " + filter);
|
|
||||||
}
|
|
||||||
List<UserWrapper> userList;
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
String[] users = userStoreManager.listUsers(filter + "*", -1);
|
|
||||||
userList = new ArrayList<>(users.length);
|
|
||||||
UserWrapper user;
|
|
||||||
for (String username : users) {
|
|
||||||
user = new UserWrapper();
|
|
||||||
user.setUsername(username);
|
|
||||||
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
|
||||||
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
|
||||||
userList.add(user);
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
int count;
|
|
||||||
count = userList.size();
|
|
||||||
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
|
|
||||||
"Obtained user count: " + count);
|
|
||||||
responsePayload.setResponseContent(userList);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the list of user names in the system.
|
|
||||||
*
|
|
||||||
* @return A list of user names.
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("view-users")
|
@Path("view-users")
|
||||||
public Response getAllUsersByUsername(@QueryParam("username") String userName) {
|
Response getAllUsersByUsername(@QueryParam("username") String userName);
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of users by name");
|
|
||||||
}
|
|
||||||
List<UserWrapper> userList;
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
|
|
||||||
userList = new ArrayList<>(users.length);
|
|
||||||
UserWrapper user;
|
|
||||||
for (String username : users) {
|
|
||||||
user = new UserWrapper();
|
|
||||||
user.setUsername(username);
|
|
||||||
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
|
||||||
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
|
||||||
userList.add(user);
|
|
||||||
}
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of users";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
int count;
|
|
||||||
count = userList.size();
|
|
||||||
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
|
|
||||||
"Obtained user count: " + count);
|
|
||||||
responsePayload.setResponseContent(userList);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the list of user names in the system.
|
|
||||||
*
|
|
||||||
* @return A list of user names.
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("users-by-username")
|
@Path("users-by-username")
|
||||||
public Response getAllUserNamesByUsername(@QueryParam("username") String userName) {
|
Response getAllUserNamesByUsername(@QueryParam("username") String userName);
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Getting the list of users by name");
|
|
||||||
}
|
|
||||||
List<String> userList;
|
|
||||||
try {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
|
|
||||||
userList = new ArrayList<>(users.length);
|
|
||||||
Collections.addAll(userList, users);
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while retrieving the list of users";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
int count;
|
|
||||||
count = userList.size();
|
|
||||||
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
|
|
||||||
"Obtained user count: " + count);
|
|
||||||
responsePayload.setResponseContent(userList);
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets a claim-value from user-store.
|
|
||||||
*
|
|
||||||
* @param username Username of the user
|
|
||||||
* @param claimUri required ClaimUri
|
|
||||||
* @return claim value
|
|
||||||
*/
|
|
||||||
private String getClaimValue(String username, String claimUri) throws MDMAPIException {
|
|
||||||
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
try {
|
|
||||||
return userStoreManager.getUserClaimValue(username, claimUri, null);
|
|
||||||
} catch (UserStoreException e) {
|
|
||||||
throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" +
|
|
||||||
claimUri + "'", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method used to send an invitation email to a new user to enroll a device.
|
|
||||||
*
|
|
||||||
* @param username Username of the user
|
|
||||||
*/
|
|
||||||
private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException {
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Sending invitation mail to user by username: " + username);
|
|
||||||
}
|
|
||||||
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
|
||||||
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
|
|
||||||
tenantDomain = "";
|
|
||||||
}
|
|
||||||
if (!username.contains("/")) {
|
|
||||||
username = "/" + username;
|
|
||||||
}
|
|
||||||
String[] usernameBits = username.split("/");
|
|
||||||
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
|
|
||||||
Properties props = new Properties();
|
|
||||||
props.setProperty("username", usernameBits[1]);
|
|
||||||
props.setProperty("domain-name", tenantDomain);
|
|
||||||
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
props.setProperty("password", password);
|
|
||||||
|
|
||||||
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
|
|
||||||
|
|
||||||
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
|
|
||||||
try {
|
|
||||||
deviceManagementProviderService.sendRegistrationEmail(metaInfo);
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Error occurred while sending registration email to user '" + username + "'";
|
|
||||||
log.error(msg, e);
|
|
||||||
throw new MDMAPIException(msg, e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method used to send an invitation email to a existing user to enroll a device.
|
|
||||||
*
|
|
||||||
* @param usernames Username list of the users to be invited
|
|
||||||
*/
|
|
||||||
@POST
|
@POST
|
||||||
@Path("email-invitation")
|
@Path("email-invitation")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) {
|
Response inviteExistingUsersToEnrollDevice(List<String> usernames);
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Sending enrollment invitation mail to existing user.");
|
|
||||||
}
|
|
||||||
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
try {
|
|
||||||
for (String username : usernames) {
|
|
||||||
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
|
|
||||||
|
|
||||||
Properties props = new Properties();
|
|
||||||
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
|
||||||
props.setProperty("username", username);
|
|
||||||
|
|
||||||
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
|
|
||||||
deviceManagementProviderService.sendEnrolmentInvitation(metaInfo);
|
|
||||||
}
|
|
||||||
} catch (DeviceManagementException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while inviting user to enrol their device";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
ResponsePayload responsePayload = new ResponsePayload();
|
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
|
||||||
responsePayload.setMessageFromServer("Email invitation was successfully sent to user.");
|
|
||||||
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a list of devices based on the username.
|
|
||||||
*
|
|
||||||
* @param username Username of the device owner
|
|
||||||
* @return A list of devices
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
@Path("devices")
|
@Path("devices")
|
||||||
public Response getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx,
|
Response getAllDeviceOfUser(@QueryParam("username") String username, @QueryParam("start") int startIdx,
|
||||||
@QueryParam("length") int length) {
|
@QueryParam("length") int length);
|
||||||
DeviceManagementProviderService dmService;
|
|
||||||
try {
|
|
||||||
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
|
||||||
if (length > 0) {
|
|
||||||
PaginationRequest request = new PaginationRequest(startIdx, length);
|
|
||||||
request.setOwner(username);
|
|
||||||
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build();
|
|
||||||
} catch (DeviceManagementException e) {
|
|
||||||
String msg = "Device management error";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This method is used to retrieve the user count of the system.
|
|
||||||
*
|
|
||||||
* @return returns the count.
|
|
||||||
* @
|
|
||||||
*/
|
|
||||||
@GET
|
@GET
|
||||||
@Path("count")
|
@Path("count")
|
||||||
public Response getUserCount() {
|
Response getUserCount();
|
||||||
try {
|
|
||||||
String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1);
|
|
||||||
Integer count = 0;
|
|
||||||
if (users != null) {
|
|
||||||
count = users.length;
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).entity(count).build();
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg =
|
|
||||||
"Error occurred while retrieving the list of users that exist within the current tenant";
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API is used to update roles of a user
|
|
||||||
*
|
|
||||||
* @param username
|
|
||||||
* @param userList
|
|
||||||
* @return
|
|
||||||
* @
|
|
||||||
*/
|
|
||||||
@PUT
|
@PUT
|
||||||
@Path("{roleName}/users")
|
@Path("{roleName}/users")
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response updateRoles(@PathParam("username") String username, List<String> userList) {
|
Response updateRoles(@PathParam("username") String username, List<String> userList);
|
||||||
try {
|
|
||||||
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
|
||||||
if (log.isDebugEnabled()) {
|
|
||||||
log.debug("Updating the roles of a user");
|
|
||||||
}
|
|
||||||
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
|
||||||
transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)),
|
|
||||||
userList);
|
|
||||||
final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]);
|
|
||||||
final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
|
|
||||||
|
|
||||||
userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd);
|
|
||||||
} catch (UserStoreException | MDMAPIException e) {
|
|
||||||
String msg = "Error occurred while saving the roles for user: " + username;
|
|
||||||
log.error(msg, e);
|
|
||||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
|
||||||
}
|
|
||||||
return Response.status(Response.Status.OK).build();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to change the user password.
|
|
||||||
*
|
|
||||||
* @param credentials Wrapper object representing user credentials.
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
* @
|
|
||||||
*/
|
|
||||||
@POST
|
@POST
|
||||||
@Path("change-password")
|
@Path("change-password")
|
||||||
@Consumes({MediaType.APPLICATION_JSON})
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response resetPassword(UserCredentialWrapper credentials) {
|
Response resetPassword(UserCredentialWrapper credentials);
|
||||||
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Method to change the user password.
|
|
||||||
*
|
|
||||||
* @param credentials Wrapper object representing user credentials.
|
|
||||||
* @return {Response} Status of the request wrapped inside Response object.
|
|
||||||
* @
|
|
||||||
*/
|
|
||||||
@POST
|
@POST
|
||||||
@Path("reset-password")
|
@Path("reset-password")
|
||||||
@Consumes({MediaType.APPLICATION_JSON})
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
@Produces({MediaType.APPLICATION_JSON})
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
public Response resetPasswordByAdmin(UserCredentialWrapper credentials) {
|
Response resetPasswordByAdmin(UserCredentialWrapper credentials);
|
||||||
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Authentication related REST-API implementation.
|
||||||
|
*/
|
||||||
|
@Produces({ "application/json", "application/xml" })
|
||||||
|
@Consumes({ "application/json", "application/xml" })
|
||||||
|
public class AuthenticationImpl {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(AuthenticationImpl.class);
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,195 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException;
|
||||||
|
import org.wso2.carbon.certificate.mgt.core.dto.CertificateResponse;
|
||||||
|
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
|
||||||
|
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
|
||||||
|
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Certificate;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.EnrollmentCertificate;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.exception.Message;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.HeaderParam;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* All the certificate related tasks such as saving certificates, can be done through this endpoint.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
@Produces({"application/json", "application/xml"})
|
||||||
|
@Consumes({ "application/json", "application/xml" })
|
||||||
|
public class CertificateImpl implements Certificate{
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(OperationImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save a list of certificates and relevant information in the database.
|
||||||
|
*
|
||||||
|
* @param enrollmentCertificates List of all the certificates which includes the tenant id, certificate as
|
||||||
|
* a pem and a serial number.
|
||||||
|
* @return Status of the data persist operation.
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@Path("saveCertificate")
|
||||||
|
public Response saveCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
|
EnrollmentCertificate[] enrollmentCertificates) {
|
||||||
|
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
||||||
|
CertificateManagementService certificateService;
|
||||||
|
List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
|
||||||
|
org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate;
|
||||||
|
certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
||||||
|
try {
|
||||||
|
for (EnrollmentCertificate enrollmentCertificate : enrollmentCertificates) {
|
||||||
|
certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
|
||||||
|
certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
|
||||||
|
certificate.setSerial(enrollmentCertificate.getSerial());
|
||||||
|
certificate.setCertificate(certificateService.pemToX509Certificate(enrollmentCertificate.getPem()));
|
||||||
|
certificates.add(certificate);
|
||||||
|
}
|
||||||
|
certificateService.saveCertificate(certificates);
|
||||||
|
return Response.status(Response.Status.CREATED).entity("Added successfully.").
|
||||||
|
type(responseMediaType).build();
|
||||||
|
} catch (KeystoreException e) {
|
||||||
|
String msg = "Error occurred while converting PEM file to X509Certificate.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a certificate when the serial number is given.
|
||||||
|
*
|
||||||
|
* @param serialNumber serial of the certificate needed.
|
||||||
|
* @return certificate response.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("{serialNumber}")
|
||||||
|
public Response getCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
|
@PathParam("serialNumber") String serialNumber) {
|
||||||
|
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
||||||
|
Message message = new Message();
|
||||||
|
|
||||||
|
if (serialNumber == null || serialNumber.isEmpty()) {
|
||||||
|
message.setErrorMessage("Invalid serial number");
|
||||||
|
message.setDiscription("Serial number is missing or invalid.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
||||||
|
CertificateResponse certificateResponse;
|
||||||
|
try {
|
||||||
|
certificateResponse = certificateService.getCertificateBySerial(serialNumber);
|
||||||
|
if(certificateResponse != null) {
|
||||||
|
certificateResponse.setCertificate(null); //avoid sending byte array in response.
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(certificateResponse).type(responseMediaType).build();
|
||||||
|
} catch (KeystoreException e) {
|
||||||
|
String msg = "Error occurred while converting PEM file to X509Certificate";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all certificates in a paginated manner.
|
||||||
|
*
|
||||||
|
* @param startIndex index of the first record to be fetched
|
||||||
|
* @param length number of records to be fetched starting from the start index.
|
||||||
|
* @return paginated result of certificate.
|
||||||
|
* @throws MDMAPIException
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("paginate")
|
||||||
|
public Response getAllCertificates(@HeaderParam("Accept") String acceptHeader,
|
||||||
|
@QueryParam("start") int startIndex,
|
||||||
|
@QueryParam("length") int length)
|
||||||
|
throws MDMAPIException {
|
||||||
|
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
||||||
|
Message message = new Message();
|
||||||
|
|
||||||
|
if (startIndex < 0) {
|
||||||
|
message.setErrorMessage("Invalid start index.");
|
||||||
|
message.setDiscription("Start index cannot be less that 0.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
||||||
|
} else if (length <= 0) {
|
||||||
|
message.setErrorMessage("Invalid length value.");
|
||||||
|
message.setDiscription("Length should be a positive integer.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
||||||
|
PaginationRequest paginationRequest = new PaginationRequest(startIndex, length);
|
||||||
|
try {
|
||||||
|
PaginationResult certificates = certificateService.getAllCertificates(paginationRequest);
|
||||||
|
return Response.status(Response.Status.OK).entity(certificates).type(responseMediaType).build();
|
||||||
|
} catch (CertificateManagementDAOException e) {
|
||||||
|
String msg = "Error occurred while fetching all certificates.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@DELETE
|
||||||
|
@Path("{serialNumber}")
|
||||||
|
public Response removeCertificate(@HeaderParam("Accept") String acceptHeader,
|
||||||
|
@PathParam("serialNumber") String serialNumber) throws MDMAPIException {
|
||||||
|
MediaType responseMediaType = DeviceMgtAPIUtils.getResponseMediaType(acceptHeader);
|
||||||
|
Message message = new Message();
|
||||||
|
|
||||||
|
if (serialNumber == null || serialNumber.isEmpty()) {
|
||||||
|
message.setErrorMessage("Invalid serial number");
|
||||||
|
message.setDiscription("Serial number is missing or invalid.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(message).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
CertificateManagementService certificateService = DeviceMgtAPIUtils.getCertificateManagementService();
|
||||||
|
boolean deleted;
|
||||||
|
try {
|
||||||
|
deleted = certificateService.removeCertificate(serialNumber);
|
||||||
|
if(deleted){
|
||||||
|
return Response.status(Response.Status.OK).entity(deleted).type(responseMediaType).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.GONE).entity(deleted).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
} catch (CertificateManagementDAOException e) {
|
||||||
|
String msg = "Error occurred while converting PEM file to X509Certificate";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).type(responseMediaType).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,113 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
|
||||||
|
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Configuration;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAppConstants;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.policy.mgt.core.util.PolicyManagerUtil;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* General Tenant Configuration REST-API implementation.
|
||||||
|
* All end points support JSON, XMl with content negotiation.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
@Produces({"application/json", "application/xml"})
|
||||||
|
@Consumes({ "application/json", "application/xml" })
|
||||||
|
public class ConfigurationImpl implements Configuration{
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(ConfigurationImpl.class);
|
||||||
|
|
||||||
|
@POST
|
||||||
|
public Response saveTenantConfiguration(TenantConfiguration configuration) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
|
||||||
|
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
||||||
|
//Schedule the task service
|
||||||
|
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
|
||||||
|
responseMsg.setMessageFromServer("Tenant configuration saved successfully.");
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (ConfigurationManagementException e) {
|
||||||
|
String msg = "Error occurred while saving the tenant configuration.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public Response getConfiguration() {
|
||||||
|
String msg;
|
||||||
|
try {
|
||||||
|
TenantConfiguration tenantConfiguration = DeviceMgtAPIUtils.getTenantConfigurationManagementService().
|
||||||
|
getConfiguration(MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
||||||
|
ConfigurationEntry configurationEntry = new ConfigurationEntry();
|
||||||
|
configurationEntry.setContentType("text");
|
||||||
|
configurationEntry.setName("notifierFrequency");
|
||||||
|
configurationEntry.setValue(PolicyManagerUtil.getMonitoringFequency());
|
||||||
|
List<ConfigurationEntry> configList = tenantConfiguration.getConfiguration();
|
||||||
|
if (configList == null) {
|
||||||
|
configList = new ArrayList<>();
|
||||||
|
}
|
||||||
|
configList.add(configurationEntry);
|
||||||
|
tenantConfiguration.setConfiguration(configList);
|
||||||
|
return Response.status(Response.Status.OK).entity(tenantConfiguration).build();
|
||||||
|
} catch (ConfigurationManagementException e) {
|
||||||
|
msg = "Error occurred while retrieving the tenant configuration.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PUT
|
||||||
|
public Response updateConfiguration(TenantConfiguration configuration) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getTenantConfigurationManagementService().saveConfiguration(configuration,
|
||||||
|
MDMAppConstants.RegistryConstants.GENERAL_CONFIG_RESOURCE_PATH);
|
||||||
|
//Schedule the task service
|
||||||
|
DeviceMgtAPIUtils.scheduleTaskService(DeviceMgtAPIUtils.getNotifierFrequency(configuration));
|
||||||
|
responseMsg.setMessageFromServer("Tenant configuration updated successfully.");
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (ConfigurationManagementException e) {
|
||||||
|
String msg = "Error occurred while updating the tenant configuration.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,285 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Device;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||||
|
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||||
|
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Device related operations
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class DeviceImpl implements Device{
|
||||||
|
private static Log log = LogFactory.getLog(DeviceImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all devices. We have to use accept all the necessary query parameters sent by datatable.
|
||||||
|
* Hence had to put lot of query params here.
|
||||||
|
*
|
||||||
|
* @return Device List
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
public Response getAllDevices(@QueryParam("type") String type, @QueryParam("user") String user,
|
||||||
|
@QueryParam("role") String role, @QueryParam("status") EnrolmentInfo.Status status,
|
||||||
|
@QueryParam("start") int startIdx, @QueryParam("length") int length,
|
||||||
|
@QueryParam("device-name") String deviceName,
|
||||||
|
@QueryParam("ownership") EnrolmentInfo.OwnerShip ownership) {
|
||||||
|
try {
|
||||||
|
DeviceManagementProviderService service = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
//Length > 0 means this is a pagination request.
|
||||||
|
if (length > 0) {
|
||||||
|
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
|
||||||
|
paginationRequest.setDeviceName(deviceName);
|
||||||
|
paginationRequest.setOwner(user);
|
||||||
|
if (ownership != null) {
|
||||||
|
paginationRequest.setOwnership(ownership.toString());
|
||||||
|
}
|
||||||
|
if (status != null) {
|
||||||
|
paginationRequest.setStatus(status.toString());
|
||||||
|
}
|
||||||
|
paginationRequest.setDeviceType(type);
|
||||||
|
return Response.status(Response.Status.OK).entity(service.getAllDevices(paginationRequest)).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<org.wso2.carbon.device.mgt.common.Device> allDevices;
|
||||||
|
if ((type != null) && !type.isEmpty()) {
|
||||||
|
allDevices = service.getAllDevices(type);
|
||||||
|
} else if ((user != null) && !user.isEmpty()) {
|
||||||
|
allDevices = service.getDevicesOfUser(user);
|
||||||
|
} else if ((role != null) && !role.isEmpty()) {
|
||||||
|
allDevices = service.getAllDevicesOfRole(role);
|
||||||
|
} else if (status != null) {
|
||||||
|
allDevices = service.getDevicesByStatus(status);
|
||||||
|
} else if (deviceName != null) {
|
||||||
|
allDevices = service.getDevicesByName(deviceName);
|
||||||
|
} else {
|
||||||
|
allDevices = service.getAllDevices();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(allDevices).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the device list.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch device details for a given device type and device Id.
|
||||||
|
*
|
||||||
|
* @return Device wrapped inside Response
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("view")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getDevice(@QueryParam("type") String type,
|
||||||
|
@QueryParam("id") String id) {
|
||||||
|
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
||||||
|
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
org.wso2.carbon.device.mgt.common.Device device;
|
||||||
|
try {
|
||||||
|
device = deviceManagementProviderService.getDevice(deviceIdentifier);
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the device information.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
if (device == null) {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
|
||||||
|
responsePayload.setMessageFromServer("Requested device by type: " +
|
||||||
|
type + " and id: " + id + " does not exist.");
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Sending Requested device by type: " + type + " and id: " + id + ".");
|
||||||
|
responsePayload.setResponseContent(device);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch device details of a given user.
|
||||||
|
*
|
||||||
|
* @param user User Name
|
||||||
|
* @return Device
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("user/{user}")
|
||||||
|
public Response getDevice(@PathParam("user") String user) {
|
||||||
|
List<org.wso2.carbon.device.mgt.common.Device> devices;
|
||||||
|
try {
|
||||||
|
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesOfUser(user);
|
||||||
|
if (devices == null) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(devices).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the devices list of given user.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch device count of a given user.
|
||||||
|
*
|
||||||
|
* @param user User Name
|
||||||
|
* @return Device
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("user/{user}/count")
|
||||||
|
public Response getDeviceCount(@PathParam("user") String user) {
|
||||||
|
try {
|
||||||
|
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount(user);
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the devices list of given user.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get current device count
|
||||||
|
*
|
||||||
|
* @return device count
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("count")
|
||||||
|
public Response getDeviceCount() {
|
||||||
|
try {
|
||||||
|
Integer count = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceCount();
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the device count.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of devices that matches with the given name.
|
||||||
|
*
|
||||||
|
* @param deviceName Device name
|
||||||
|
* @param tenantDomain Callee tenant domain
|
||||||
|
* @return list of devices.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("name/{name}/{tenantDomain}")
|
||||||
|
public Response getDevicesByName(@PathParam("name") String deviceName,
|
||||||
|
@PathParam("tenantDomain") String tenantDomain) {
|
||||||
|
List<org.wso2.carbon.device.mgt.common.Device> devices;
|
||||||
|
try {
|
||||||
|
devices = DeviceMgtAPIUtils.getDeviceManagementService().getDevicesByName(deviceName);
|
||||||
|
return Response.status(Response.Status.OK).entity(devices).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the devices list of device name.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of available device types.
|
||||||
|
*
|
||||||
|
* @return list of device types.
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("types")
|
||||||
|
public Response getDeviceTypes() {
|
||||||
|
List<DeviceType> deviceTypes;
|
||||||
|
try {
|
||||||
|
deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getAvailableDeviceTypes();
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceTypes).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the list of device types.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update device.
|
||||||
|
*
|
||||||
|
* @return update status.
|
||||||
|
*/
|
||||||
|
@PUT
|
||||||
|
@Path("type/{type}/id/{deviceId}")
|
||||||
|
public Response updateDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId,
|
||||||
|
org.wso2.carbon.device.mgt.common.Device updatedDevice) {
|
||||||
|
try {
|
||||||
|
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
deviceIdentifier.setType(deviceType);
|
||||||
|
deviceIdentifier.setId(deviceId);
|
||||||
|
org.wso2.carbon.device.mgt.common.Device device = deviceManagementService.getDevice(deviceIdentifier);
|
||||||
|
device.setName(updatedDevice.getName());
|
||||||
|
device.setDescription(updatedDevice.getDescription());
|
||||||
|
Boolean response = deviceManagementService.modifyEnrollment(device);
|
||||||
|
return Response.status(Response.Status.OK).entity(response).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the list of device types.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* disenroll device.
|
||||||
|
*
|
||||||
|
* @return disenrollment status.
|
||||||
|
*/
|
||||||
|
@DELETE
|
||||||
|
@Path("type/{type}/id/{deviceId}")
|
||||||
|
public Response disenrollDevice(@PathParam("type") String deviceType, @PathParam("deviceId") String deviceId) {
|
||||||
|
try {
|
||||||
|
DeviceManagementProviderService deviceManagementService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
deviceIdentifier.setType(deviceType);
|
||||||
|
deviceIdentifier.setId(deviceId);
|
||||||
|
Boolean response = deviceManagementService.disenrollDevice(deviceIdentifier);
|
||||||
|
return Response.status(Response.Status.OK).entity(response).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the list of device types.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,81 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||||
|
import org.wso2.carbon.device.mgt.common.device.details.DeviceInfo;
|
||||||
|
import org.wso2.carbon.device.mgt.common.device.details.DeviceLocation;
|
||||||
|
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceDetailsMgtException;
|
||||||
|
import org.wso2.carbon.device.mgt.core.device.details.mgt.DeviceInformationManager;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class DeviceInformationImpl implements DeviceInformation {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(DeviceInformationImpl.class);
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{type}/{id}")
|
||||||
|
public Response getDeviceInfo(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
DeviceInformationManager informationManager;
|
||||||
|
DeviceInfo deviceInfo;
|
||||||
|
try {
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
deviceIdentifier.setId(id);
|
||||||
|
deviceIdentifier.setType(type);
|
||||||
|
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
|
||||||
|
deviceInfo = informationManager.getDeviceInfo(deviceIdentifier);
|
||||||
|
} catch (DeviceDetailsMgtException e) {
|
||||||
|
String msg = "Error occurred while getting the device information.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceInfo).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("location/{type}/{id}")
|
||||||
|
public Response getDeviceLocation(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
DeviceInformationManager informationManager;
|
||||||
|
DeviceLocation deviceLocation;
|
||||||
|
try {
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
deviceIdentifier.setId(id);
|
||||||
|
deviceIdentifier.setType(type);
|
||||||
|
informationManager = DeviceMgtAPIUtils.getDeviceInformationManagerService();
|
||||||
|
deviceLocation = informationManager.getDeviceLocation(deviceIdentifier);
|
||||||
|
} catch (DeviceDetailsMgtException e) {
|
||||||
|
String msg = "Error occurred while getting the device location.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceLocation).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,110 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceNotification;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.common.notification.mgt.Notification;
|
||||||
|
import org.wso2.carbon.device.mgt.common.notification.mgt.NotificationManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DeviceNotification management REST-API implementation.
|
||||||
|
* All end points support JSON, XMl with content negotiation.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
@Produces({"application/json", "application/xml"})
|
||||||
|
@Consumes({ "application/json", "application/xml" })
|
||||||
|
public class DeviceNotificationImpl implements DeviceNotification{
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(ConfigurationImpl.class);
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public Response getNotifications() {
|
||||||
|
String msg;
|
||||||
|
try {
|
||||||
|
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getAllNotifications();
|
||||||
|
return Response.status(Response.Status.OK).entity(notifications).build();
|
||||||
|
} catch (NotificationManagementException e) {
|
||||||
|
msg = "Error occurred while retrieving the notification list.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@GET
|
||||||
|
@Path("{status}")
|
||||||
|
public Response getNotificationsByStatus(@PathParam("status") Notification.Status status) {
|
||||||
|
String msg;
|
||||||
|
try {
|
||||||
|
List<Notification> notifications = DeviceMgtAPIUtils.getNotificationManagementService().getNotificationsByStatus(status);
|
||||||
|
return Response.status(Response.Status.OK).entity(notifications).build();
|
||||||
|
} catch (NotificationManagementException e) {
|
||||||
|
msg = "Error occurred while retrieving the notification list.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@PUT
|
||||||
|
@Path("{id}/{status}")
|
||||||
|
public Response updateNotificationStatus(@PathParam("id") int id,
|
||||||
|
@PathParam("status") Notification.Status status) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getNotificationManagementService().updateNotificationStatus(id, status);
|
||||||
|
responseMsg.setMessageFromServer("Notification status updated successfully.");
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_ACCEPTED);
|
||||||
|
return Response.status(Response.Status.ACCEPTED).entity(responseMsg).build();
|
||||||
|
} catch (NotificationManagementException e) {
|
||||||
|
String msg = "Error occurred while updating notification status.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@POST
|
||||||
|
public Response addNotification(Notification notification) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getNotificationManagementService().addNotification(notification);
|
||||||
|
responseMsg.setMessageFromServer("Notification has added successfully.");
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (NotificationManagementException e) {
|
||||||
|
String msg = "Error occurred while updating notification status.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.common.device.details.DeviceWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.common.search.SearchContext;
|
||||||
|
import org.wso2.carbon.device.mgt.core.search.mgt.SearchManagerService;
|
||||||
|
import org.wso2.carbon.device.mgt.core.search.mgt.SearchMgtException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.DeviceSearch;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class DeviceSearchImpl implements DeviceSearch {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(DeviceSearchImpl.class);
|
||||||
|
|
||||||
|
@GET
|
||||||
|
public Response getDeviceInfo(SearchContext searchContext) {
|
||||||
|
SearchManagerService searchManagerService;
|
||||||
|
List<DeviceWrapper> devices;
|
||||||
|
try {
|
||||||
|
searchManagerService = DeviceMgtAPIUtils.getSearchManagerService();
|
||||||
|
devices = searchManagerService.search(searchContext);
|
||||||
|
|
||||||
|
} catch (SearchMgtException e) {
|
||||||
|
String msg = "Error occurred while searching the device information.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(devices).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Feature;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Features
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
@Produces({"application/json", "application/xml"})
|
||||||
|
@Consumes({"application/json", "application/xml"})
|
||||||
|
public class FeatureImpl implements Feature{
|
||||||
|
private static Log log = LogFactory.getLog(FeatureImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all features for Mobile Device Type
|
||||||
|
*
|
||||||
|
* @return Feature
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path("/{type}")
|
||||||
|
public Response getFeatures(@PathParam("type") String type) {
|
||||||
|
List<org.wso2.carbon.device.mgt.common.Feature> features;
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
try {
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
features = dmService.getFeatureManager(type).getFeatures();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of features";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(features).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,533 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.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.DeviceIdentifier;
|
||||||
|
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.DeviceGroupConstants;
|
||||||
|
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Group;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.FormParam;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class GroupImpl implements Group {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(GroupImpl.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Consumes("application/json")
|
||||||
|
public Response createGroup(DeviceGroup group) {
|
||||||
|
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
|
||||||
|
if (group == null) {
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).build();
|
||||||
|
}
|
||||||
|
group.setOwner(owner);
|
||||||
|
group.setDateOfCreation(new Date().getTime());
|
||||||
|
group.setDateOfLastUpdate(new Date().getTime());
|
||||||
|
try {
|
||||||
|
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
|
||||||
|
groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS);
|
||||||
|
groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
|
||||||
|
DeviceGroupConstants.Roles.DEFAULT_OPERATOR_ROLE,
|
||||||
|
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||||
|
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_STATS_MONITOR_ROLE,
|
||||||
|
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS);
|
||||||
|
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_POLICIES,
|
||||||
|
DeviceGroupConstants.Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS);
|
||||||
|
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_MANAGE_POLICIES,
|
||||||
|
DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS);
|
||||||
|
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DeviceGroupConstants.Roles.DEFAULT_VIEW_EVENTS,
|
||||||
|
DeviceGroupConstants.Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS);
|
||||||
|
return Response.status(Response.Status.CREATED).build();
|
||||||
|
} catch (GroupAlreadyEixistException e) {
|
||||||
|
return Response.status(Response.Status.CONFLICT).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getErrorMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
|
@PUT
|
||||||
|
@Consumes("application/json")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response updateGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
DeviceGroup deviceGroup) {
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getGroupManagementProviderService().updateGroup(deviceGroup, groupName, owner);
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getErrorMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
|
@DELETE
|
||||||
|
public Response deleteGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getGroupManagementProviderService().deleteGroup(groupName, owner);
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage());
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length) {
|
||||||
|
try {
|
||||||
|
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.getGroups(startIndex, length);
|
||||||
|
if (paginationResult.getRecordsTotal() > 0) {
|
||||||
|
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/all")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getAllGroups() {
|
||||||
|
try {
|
||||||
|
GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils
|
||||||
|
.getGroupManagementProviderService();
|
||||||
|
PaginationResult paginationResult = groupManagementProviderService
|
||||||
|
.getGroups(0, groupManagementProviderService.getGroupCount());
|
||||||
|
if (paginationResult.getRecordsTotal() > 0) {
|
||||||
|
return Response.status(Response.Status.OK).entity(paginationResult.getData()).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/user/{user}")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
|
||||||
|
@QueryParam("length") int length) {
|
||||||
|
try {
|
||||||
|
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.getGroups(userName, startIndex, length);
|
||||||
|
if (paginationResult.getRecordsTotal() > 0) {
|
||||||
|
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/user/{user}/all")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroups(@PathParam("user") String userName) {
|
||||||
|
try {
|
||||||
|
List<DeviceGroup> deviceGroups = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.getGroups(userName);
|
||||||
|
if (deviceGroups.size() > 0) {
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
||||||
|
try {
|
||||||
|
DeviceGroup deviceGroup = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroup(groupName, owner);
|
||||||
|
if (deviceGroup != null) {
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceGroup).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/user/{user}/search")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response findGroups(@QueryParam("groupName") String groupName, @PathParam("user") String user) {
|
||||||
|
try {
|
||||||
|
List<DeviceGroup> groups = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.findInGroups(groupName, user);
|
||||||
|
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
|
||||||
|
groups.toArray(deviceGroups);
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/user/{user}/all")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroups(@PathParam("user") String userName, @QueryParam("permission") String permission) {
|
||||||
|
try {
|
||||||
|
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
|
||||||
|
List<DeviceGroup> groups;
|
||||||
|
if (permission != null) {
|
||||||
|
groups = groupManagementService.getGroups(userName, permission);
|
||||||
|
} else {
|
||||||
|
groups = groupManagementService.getGroups(userName);
|
||||||
|
}
|
||||||
|
DeviceGroup[] deviceGroups = new DeviceGroup[groups.size()];
|
||||||
|
groups.toArray(deviceGroups);
|
||||||
|
return Response.status(Response.Status.OK).entity(deviceGroups).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/count")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getAllGroupCount() {
|
||||||
|
try {
|
||||||
|
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount();
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/user/{user}/count")
|
||||||
|
@GET
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getGroupCount(@PathParam("user") String userName) {
|
||||||
|
try {
|
||||||
|
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getGroupCount(userName);
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/share")
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response shareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@FormParam("shareUser") String shareUser,
|
||||||
|
@FormParam("roleName") String sharingRole) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
boolean isShared = DeviceMgtAPIUtils.getGroupManagementProviderService().shareGroup(
|
||||||
|
shareUser, groupName, owner, sharingRole);
|
||||||
|
if (isShared) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
|
||||||
|
}
|
||||||
|
} catch (UserDoesNotExistException e) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/unshare")
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response unShareGroup(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@FormParam("unShareUser") String unShareUser,
|
||||||
|
@FormParam("roleName") String sharingRole) {
|
||||||
|
try {
|
||||||
|
boolean isUnShared = DeviceMgtAPIUtils.getGroupManagementProviderService().unshareGroup(
|
||||||
|
unShareUser, groupName, owner, sharingRole);
|
||||||
|
if (isUnShared) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity("Group not found").build();
|
||||||
|
}
|
||||||
|
} catch (UserDoesNotExistException e) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response addSharing(@QueryParam("shareUser") String shareUser,
|
||||||
|
@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@PathParam("roleName") String roleName,
|
||||||
|
@FormParam("permissions") String[] permissions) {
|
||||||
|
|
||||||
|
try {
|
||||||
|
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addGroupSharingRole(
|
||||||
|
shareUser, groupName, owner, roleName, permissions);
|
||||||
|
if (isAdded) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@DELETE
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/share/roles/{roleName}/permissions")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response removeSharing(@QueryParam("userName") String userName,
|
||||||
|
@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@PathParam("roleName") String roleName) {
|
||||||
|
try {
|
||||||
|
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeGroupSharingRole(
|
||||||
|
groupName, owner, roleName);
|
||||||
|
if (isRemoved) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/share/roles")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@QueryParam("userName") String userName) {
|
||||||
|
try {
|
||||||
|
List<String> roles;
|
||||||
|
if (userName != null && !userName.isEmpty()) {
|
||||||
|
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(userName, groupName, owner);
|
||||||
|
} else {
|
||||||
|
roles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
|
||||||
|
}
|
||||||
|
String[] rolesArray = new String[roles.size()];
|
||||||
|
roles.toArray(rolesArray);
|
||||||
|
return Response.status(Response.Status.OK).entity(rolesArray).build();
|
||||||
|
} catch (UserDoesNotExistException e) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/user/{userName}/share/roles")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response setRoles(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@PathParam("userName") String userName, List<String> selectedRoles) {
|
||||||
|
try {
|
||||||
|
List<String> allRoles = DeviceMgtAPIUtils.getGroupManagementProviderService().getRoles(groupName, owner);
|
||||||
|
for (String role : allRoles) {
|
||||||
|
if (selectedRoles.contains(role)) {
|
||||||
|
DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.shareGroup(userName, groupName, owner, role);
|
||||||
|
} else {
|
||||||
|
DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.unshareGroup(userName, groupName, owner, role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} catch (UserDoesNotExistException e) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/users")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getUsers(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
||||||
|
try {
|
||||||
|
List<GroupUser> users = DeviceMgtAPIUtils.getGroupManagementProviderService().getUsers(
|
||||||
|
groupName, owner);
|
||||||
|
GroupUser[] usersArray = new GroupUser[users.size()];
|
||||||
|
users.toArray(usersArray);
|
||||||
|
return Response.status(Response.Status.OK).entity(usersArray).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/devices")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
|
||||||
|
try {
|
||||||
|
PaginationResult paginationResult = DeviceMgtAPIUtils
|
||||||
|
.getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length);
|
||||||
|
if (paginationResult.getRecordsTotal() > 0) {
|
||||||
|
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/devices/count")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getDeviceCount(@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
||||||
|
try {
|
||||||
|
int count = DeviceMgtAPIUtils.getGroupManagementProviderService().getDeviceCount(groupName, owner);
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/devices")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response addDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
DeviceIdentifier deviceIdentifier) {
|
||||||
|
try {
|
||||||
|
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
|
||||||
|
deviceIdentifier, groupName, owner);
|
||||||
|
if (isAdded) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@DELETE
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response removeDevice(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
|
||||||
|
@PathParam("deviceId") String deviceId,
|
||||||
|
@PathParam("deviceType") String deviceType) {
|
||||||
|
try {
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
|
||||||
|
boolean isRemoved = DeviceMgtAPIUtils.getGroupManagementProviderService().removeDevice(
|
||||||
|
deviceIdentifier, groupName, owner);
|
||||||
|
if (isRemoved) {
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
} else {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("/owner/{owner}/name/{groupName}/users/{userName}/permissions")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response getPermissions(@PathParam("userName") String userName,
|
||||||
|
@PathParam("groupName") String groupName, @PathParam("owner") String owner) {
|
||||||
|
try {
|
||||||
|
String[] permissions = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||||
|
.getPermissions(userName, groupName, owner);
|
||||||
|
return Response.status(Response.Status.OK).entity(permissions).build();
|
||||||
|
} catch (UserDoesNotExistException e) {
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
|
||||||
|
} catch (GroupManagementException e) {
|
||||||
|
log.error(e.getMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -0,0 +1,102 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.License;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class represents license related operations.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class LicenseImpl implements License {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(LicenseImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method returns the license text related to a given device type and language code.
|
||||||
|
*
|
||||||
|
* @param deviceType Device type, ex: android, ios
|
||||||
|
* @param languageCode Language code, ex: en_US
|
||||||
|
* @return Returns the license text
|
||||||
|
*/
|
||||||
|
@GET
|
||||||
|
@Path ("{deviceType}/{languageCode}")
|
||||||
|
@Produces ({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getLicense(@PathParam ("deviceType") String deviceType,
|
||||||
|
@PathParam("languageCode") String languageCode) {
|
||||||
|
|
||||||
|
org.wso2.carbon.device.mgt.common.license.mgt.License license;
|
||||||
|
ResponsePayload responsePayload;
|
||||||
|
try {
|
||||||
|
license = DeviceMgtAPIUtils.getDeviceManagementService().getLicense(deviceType, languageCode);
|
||||||
|
if (license == null) {
|
||||||
|
return Response.status(HttpStatus.SC_NOT_FOUND).build();
|
||||||
|
}
|
||||||
|
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
|
||||||
|
messageFromServer("License for '" + deviceType + "' was retrieved successfully").
|
||||||
|
responseContent(license.getText()).
|
||||||
|
build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while retrieving the license configured for '" + deviceType + "' device type";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to add license to a specific device type.
|
||||||
|
*
|
||||||
|
* @param deviceType Device type, ex: android, ios
|
||||||
|
* @param license License object
|
||||||
|
* @return Returns the acknowledgement for the action
|
||||||
|
*/
|
||||||
|
@POST
|
||||||
|
@Path ("{deviceType}")
|
||||||
|
public Response addLicense(@PathParam ("deviceType") String deviceType,
|
||||||
|
org.wso2.carbon.device.mgt.common.license.mgt.License license) {
|
||||||
|
|
||||||
|
ResponsePayload responsePayload;
|
||||||
|
try {
|
||||||
|
DeviceMgtAPIUtils.getDeviceManagementService().addLicense(deviceType, license);
|
||||||
|
responsePayload = ResponsePayload.statusCode(HttpStatus.SC_OK).
|
||||||
|
messageFromServer("License added successfully for '" + deviceType + "' device type").
|
||||||
|
build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while adding license for '" + deviceType + "' device type";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,227 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.context.DeviceOperationContext;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMIOSOperationUtil;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.ApplicationWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.MobileApp;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||||
|
import org.wso2.carbon.device.mgt.common.Platform;
|
||||||
|
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.ApplicationManager;
|
||||||
|
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.core.app.mgt.ApplicationManagementProviderService;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.MDMAndroidOperationUtil;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Operation related REST-API implementation.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
@Produces({"application/json", "application/xml"})
|
||||||
|
@Consumes({"application/json", "application/xml"})
|
||||||
|
public class OperationImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Operation {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(OperationImpl.class);
|
||||||
|
|
||||||
|
/* @deprecated */
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
public Response getAllOperations() {
|
||||||
|
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
try {
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
operations = dmService.getOperations(null);
|
||||||
|
} catch (OperationManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the operations for the device.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(operations).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("paginate/{type}/{id}")
|
||||||
|
public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id,
|
||||||
|
@QueryParam("start") int startIdx, @QueryParam("length") int length,
|
||||||
|
@QueryParam("search") String search) {
|
||||||
|
PaginationResult operations;
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
PaginationRequest paginationRequest = new PaginationRequest(startIdx, length);
|
||||||
|
try {
|
||||||
|
deviceIdentifier.setType(type);
|
||||||
|
deviceIdentifier.setId(id);
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
operations = dmService.getOperations(deviceIdentifier, paginationRequest);
|
||||||
|
} catch (OperationManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the operations for the device.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(operations).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{type}/{id}")
|
||||||
|
public Response getDeviceOperations(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
List<? extends org.wso2.carbon.device.mgt.common.operation.mgt.Operation> operations;
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
try {
|
||||||
|
deviceIdentifier.setType(type);
|
||||||
|
deviceIdentifier.setId(id);
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
operations = dmService.getOperations(deviceIdentifier);
|
||||||
|
} catch (OperationManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the operations for the device.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(operations).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/* @deprecated */
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
public Response addOperation(DeviceOperationContext operationContext) {
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
int operationId = dmService.addOperation(operationContext.getOperation(), operationContext.getDevices());
|
||||||
|
if (operationId > 0) {
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responseMsg.setMessageFromServer("Operation has added successfully.");
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (OperationManagementException e) {
|
||||||
|
String msg = "Error occurred while saving the operation";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{type}/{id}/apps")
|
||||||
|
public Response getInstalledApps(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
List<Application> applications;
|
||||||
|
ApplicationManagementProviderService appManagerConnector;
|
||||||
|
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||||
|
try {
|
||||||
|
deviceIdentifier.setType(type);
|
||||||
|
deviceIdentifier.setId(id);
|
||||||
|
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
||||||
|
applications = appManagerConnector.getApplicationListForDevice(deviceIdentifier);
|
||||||
|
} catch (ApplicationManagementException e) {
|
||||||
|
String msg = "Error occurred while fetching the apps of the device.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.CREATED).entity(applications).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("installApp/{tenantDomain}")
|
||||||
|
public Response installApplication(ApplicationWrapper applicationWrapper,
|
||||||
|
@PathParam("tenantDomain") String tenantDomain) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
ApplicationManager appManagerConnector;
|
||||||
|
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
|
||||||
|
try {
|
||||||
|
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
||||||
|
MobileApp mobileApp = applicationWrapper.getApplication();
|
||||||
|
|
||||||
|
if (applicationWrapper.getDeviceIdentifiers() != null) {
|
||||||
|
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
|
||||||
|
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
|
||||||
|
operation = MDMAndroidOperationUtil.createInstallAppOperation(mobileApp);
|
||||||
|
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
|
||||||
|
operation = MDMIOSOperationUtil.createInstallAppOperation(mobileApp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
|
||||||
|
}
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responseMsg.setMessageFromServer("Authentication installation request has been sent to the device.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (ApplicationManagementException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while saving the operation";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("uninstallApp/{tenantDomain}")
|
||||||
|
public Response uninstallApplication(ApplicationWrapper applicationWrapper,
|
||||||
|
@PathParam("tenantDomain") String tenantDomain) {
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
ApplicationManager appManagerConnector;
|
||||||
|
org.wso2.carbon.device.mgt.common.operation.mgt.Operation operation = null;
|
||||||
|
try {
|
||||||
|
appManagerConnector = DeviceMgtAPIUtils.getAppManagementService();
|
||||||
|
MobileApp mobileApp = applicationWrapper.getApplication();
|
||||||
|
|
||||||
|
if (applicationWrapper.getDeviceIdentifiers() != null) {
|
||||||
|
for (DeviceIdentifier deviceIdentifier : applicationWrapper.getDeviceIdentifiers()) {
|
||||||
|
if (deviceIdentifier.getType().equals(Platform.android.toString())) {
|
||||||
|
operation = MDMAndroidOperationUtil.createAppUninstallOperation(mobileApp);
|
||||||
|
} else if (deviceIdentifier.getType().equals(Platform.ios.toString())) {
|
||||||
|
operation = MDMIOSOperationUtil.createAppUninstallOperation(mobileApp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
appManagerConnector.installApplicationForDevices(operation, applicationWrapper.getDeviceIdentifiers());
|
||||||
|
}
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responseMsg.setMessageFromServer("Authentication removal request has been sent to the device.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (ApplicationManagementException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while saving the operation";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,445 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.PriorityUpdatedPolicyWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtUtil;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.PolicyWrapper;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.PolicyMonitoringTaskException;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.monitor.ComplianceData;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.monitor.PolicyComplianceException;
|
||||||
|
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||||
|
import org.wso2.carbon.policy.mgt.core.task.TaskScheduleService;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class PolicyImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Policy {
|
||||||
|
private static Log log = LogFactory.getLog(PolicyImpl.class);
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("inactive-policy")
|
||||||
|
public Response addPolicy(PolicyWrapper policyWrapper) {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
||||||
|
policy.setPolicyName(policyWrapper.getPolicyName());
|
||||||
|
policy.setProfileId(policyWrapper.getProfileId());
|
||||||
|
policy.setDescription(policyWrapper.getDescription());
|
||||||
|
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
||||||
|
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
||||||
|
policy.setRoles(policyWrapper.getRoles());
|
||||||
|
policy.setUsers(policyWrapper.getUsers());
|
||||||
|
policy.setTenantId(policyWrapper.getTenantId());
|
||||||
|
policy.setCompliance(policyWrapper.getCompliance());
|
||||||
|
|
||||||
|
return addPolicy(policyManagementService, responseMsg, policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("active-policy")
|
||||||
|
public Response addActivePolicy(PolicyWrapper policyWrapper) {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
||||||
|
policy.setPolicyName(policyWrapper.getPolicyName());
|
||||||
|
policy.setProfileId(policyWrapper.getProfileId());
|
||||||
|
policy.setDescription(policyWrapper.getDescription());
|
||||||
|
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
||||||
|
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
||||||
|
policy.setRoles(policyWrapper.getRoles());
|
||||||
|
policy.setUsers(policyWrapper.getUsers());
|
||||||
|
policy.setTenantId(policyWrapper.getTenantId());
|
||||||
|
policy.setCompliance(policyWrapper.getCompliance());
|
||||||
|
policy.setActive(true);
|
||||||
|
|
||||||
|
return addPolicy(policyManagementService, responseMsg, policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Response addPolicy(PolicyManagerService policyManagementService, ResponsePayload responseMsg,
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy) {
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
pap.addPolicy(policy);
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responseMsg.setMessageFromServer("Policy has been added successfully.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getAllPolicies() {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
List<org.wso2.carbon.policy.mgt.common.Policy> policies;
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
||||||
|
policies = policyAdministratorPoint.getPolicies();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
|
||||||
|
responsePayload.setResponseContent(policies);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
@Path("{id}")
|
||||||
|
public Response getPolicy(@PathParam("id") int policyId) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
final org.wso2.carbon.policy.mgt.common.Policy policy;
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
||||||
|
policy = policyAdministratorPoint.getPolicy(policyId);
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
if (policy == null){
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_NOT_FOUND);
|
||||||
|
responsePayload.setMessageFromServer("Policy for ID " + policyId + " not found.");
|
||||||
|
return Response.status(Response.Status.NOT_FOUND).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Sending all retrieved device policies.");
|
||||||
|
responsePayload.setResponseContent(policy);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("count")
|
||||||
|
public Response getPolicyCount() {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint policyAdministratorPoint = policyManagementService.getPAP();
|
||||||
|
Integer count = policyAdministratorPoint.getPolicyCount();
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Path("{id}")
|
||||||
|
public Response updatePolicy(PolicyWrapper policyWrapper, @PathParam("id") int policyId) {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy = new org.wso2.carbon.policy.mgt.common.Policy();
|
||||||
|
policy.setPolicyName(policyWrapper.getPolicyName());
|
||||||
|
policy.setId(policyId);
|
||||||
|
policy.setProfileId(policyWrapper.getProfileId());
|
||||||
|
policy.setDescription(policyWrapper.getDescription());
|
||||||
|
policy.setProfile(DeviceMgtUtil.convertProfile(policyWrapper.getProfile()));
|
||||||
|
policy.setOwnershipType(policyWrapper.getOwnershipType());
|
||||||
|
policy.setRoles(policyWrapper.getRoles());
|
||||||
|
policy.setUsers(policyWrapper.getUsers());
|
||||||
|
policy.setTenantId(policyWrapper.getTenantId());
|
||||||
|
policy.setCompliance(policyWrapper.getCompliance());
|
||||||
|
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
pap.updatePolicy(policy);
|
||||||
|
responseMsg.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responseMsg.setMessageFromServer("Policy has been updated successfully.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responseMsg).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception in policy update.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Path("priorities")
|
||||||
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response updatePolicyPriorities(List<PriorityUpdatedPolicyWrapper> priorityUpdatedPolicies) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
List<org.wso2.carbon.policy.mgt.common.Policy> policiesToUpdate =
|
||||||
|
new ArrayList<>(priorityUpdatedPolicies.size());
|
||||||
|
int i;
|
||||||
|
for (i = 0; i < priorityUpdatedPolicies.size(); i++) {
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policyObj = new org.wso2.carbon.policy.mgt.common.Policy();
|
||||||
|
policyObj.setId(priorityUpdatedPolicies.get(i).getId());
|
||||||
|
policyObj.setPriorityId(priorityUpdatedPolicies.get(i).getPriority());
|
||||||
|
policiesToUpdate.add(policyObj);
|
||||||
|
}
|
||||||
|
boolean policiesUpdated;
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
policiesUpdated = pap.updatePolicyPriorities(policiesToUpdate);
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Exception in updating policy priorities.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
if (policiesUpdated) {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Policy Priorities successfully updated.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
||||||
|
responsePayload.setMessageFromServer("Policy priorities did not update. Bad Request.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("bulk-remove")
|
||||||
|
@Consumes("application/json")
|
||||||
|
@Produces("application/json")
|
||||||
|
public Response bulkRemovePolicy(List<Integer> policyIds) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
boolean policyDeleted = true;
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
for(int i : policyIds) {
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy = pap.getPolicy(i);
|
||||||
|
if(!pap.deletePolicy(policy)){
|
||||||
|
policyDeleted = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Exception in deleting policies.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
if (policyDeleted) {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Policies have been successfully deleted.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
||||||
|
responsePayload.setMessageFromServer("Policy does not exist.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
@Path("activate")
|
||||||
|
public Response activatePolicy(List<Integer> policyIds) {
|
||||||
|
try {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
for(int i : policyIds) {
|
||||||
|
pap.activatePolicy(i);
|
||||||
|
}
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Exception in activating policies.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Selected policies have been successfully activated.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
@Path("inactivate")
|
||||||
|
public Response inactivatePolicy(List<Integer> policyIds) throws MDMAPIException {
|
||||||
|
|
||||||
|
try {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
for(int i : policyIds) {
|
||||||
|
pap.inactivatePolicy(i);
|
||||||
|
}
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Exception in inactivating policies.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Selected policies have been successfully inactivated.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Produces("application/json")
|
||||||
|
@Path("apply-changes")
|
||||||
|
public Response applyChanges() {
|
||||||
|
|
||||||
|
try {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
pap.publishChanges();
|
||||||
|
|
||||||
|
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Exception in applying changes.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Changes have been successfully updated.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("start-task/{milliseconds}")
|
||||||
|
public Response startTaskService(@PathParam("milliseconds") int monitoringFrequency) {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
try {
|
||||||
|
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
||||||
|
taskScheduleService.startTask(monitoringFrequency);
|
||||||
|
|
||||||
|
|
||||||
|
} catch (PolicyMonitoringTaskException e) {
|
||||||
|
String msg = "Policy Management related exception.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Policy monitoring service started successfully.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("update-task/{milliseconds}")
|
||||||
|
public Response updateTaskService(@PathParam("milliseconds") int monitoringFrequency) {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
try {
|
||||||
|
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
||||||
|
taskScheduleService.updateTask(monitoringFrequency);
|
||||||
|
|
||||||
|
} catch (PolicyMonitoringTaskException e) {
|
||||||
|
String msg = "Policy Management related exception.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Policy monitoring service updated successfully.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("stop-task")
|
||||||
|
public Response stopTaskService() {
|
||||||
|
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
try {
|
||||||
|
TaskScheduleService taskScheduleService = policyManagementService.getTaskScheduleService();
|
||||||
|
taskScheduleService.stopTask();
|
||||||
|
|
||||||
|
} catch (PolicyMonitoringTaskException e) {
|
||||||
|
String msg = "Policy Management related exception.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Policy monitoring service stopped successfully.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{type}/{id}")
|
||||||
|
public Response getComplianceDataOfDevice(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
try {
|
||||||
|
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ComplianceData complianceData = policyManagementService.getDeviceCompliance(deviceIdentifier);
|
||||||
|
return Response.status(Response.Status.OK).entity(complianceData).build();
|
||||||
|
} catch (PolicyComplianceException e) {
|
||||||
|
String msg = "Error occurred while getting the compliance data.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{type}/{id}/active-policy")
|
||||||
|
public Response getDeviceActivePolicy(@PathParam("type") String type, @PathParam("id") String id) {
|
||||||
|
try {
|
||||||
|
DeviceIdentifier deviceIdentifier = DeviceMgtAPIUtils.instantiateDeviceIdentifier(type, id);
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
org.wso2.carbon.policy.mgt.common.Policy policy = policyManagementService
|
||||||
|
.getAppliedPolicyToDevice(deviceIdentifier);
|
||||||
|
return Response.status(Response.Status.OK).entity(policy).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Error occurred while getting the current policy.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.Profile;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.PolicyAdministratorPoint;
|
||||||
|
import org.wso2.carbon.policy.mgt.common.PolicyManagementException;
|
||||||
|
import org.wso2.carbon.policy.mgt.core.PolicyManagerService;
|
||||||
|
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class ProfileImpl implements Profile{
|
||||||
|
private static Log log = LogFactory.getLog(ProfileImpl.class);
|
||||||
|
|
||||||
|
@POST
|
||||||
|
public Response addProfile(org.wso2.carbon.policy.mgt.common.Profile profile) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
profile = pap.addProfile(profile);
|
||||||
|
return Response.status(Response.Status.OK).entity(profile).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@POST
|
||||||
|
@Path("{id}")
|
||||||
|
public Response updateProfile(org.wso2.carbon.policy.mgt.common.Profile profile,
|
||||||
|
@PathParam("id") String profileId) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
pap.updateProfile(profile);
|
||||||
|
responseMsg.setMessageFromServer("Profile has been updated successfully.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responseMsg).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@DELETE
|
||||||
|
@Path("{id}")
|
||||||
|
public Response deleteProfile(@PathParam("id") int profileId) {
|
||||||
|
PolicyManagerService policyManagementService = DeviceMgtAPIUtils.getPolicyManagementService();
|
||||||
|
ResponsePayload responseMsg = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
PolicyAdministratorPoint pap = policyManagementService.getPAP();
|
||||||
|
org.wso2.carbon.policy.mgt.common.Profile profile = pap.getProfile(profileId);
|
||||||
|
pap.deleteProfile(profile);
|
||||||
|
responseMsg.setMessageFromServer("Profile has been deleted successfully.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responseMsg).build();
|
||||||
|
} catch (PolicyManagementException e) {
|
||||||
|
String msg = "Policy Management related exception";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,450 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.httpclient.HttpStatus;
|
||||||
|
import org.apache.commons.logging.Log;
|
||||||
|
import org.apache.commons.logging.LogFactory;
|
||||||
|
import org.wso2.carbon.CarbonConstants;
|
||||||
|
import org.wso2.carbon.base.MultitenantConstants;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.RoleWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
|
||||||
|
import org.wso2.carbon.user.api.AuthorizationManager;
|
||||||
|
import org.wso2.carbon.user.api.Permission;
|
||||||
|
import org.wso2.carbon.user.api.UserRealm;
|
||||||
|
import org.wso2.carbon.user.api.UserStoreException;
|
||||||
|
import org.wso2.carbon.user.api.UserStoreManager;
|
||||||
|
import org.wso2.carbon.user.core.common.AbstractUserStoreManager;
|
||||||
|
import org.wso2.carbon.user.mgt.UserRealmProxy;
|
||||||
|
import org.wso2.carbon.user.mgt.common.UIPermissionNode;
|
||||||
|
import org.wso2.carbon.user.mgt.common.UserAdminException;
|
||||||
|
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class RoleImpl implements org.wso2.carbon.device.mgt.jaxrs.api.Role {
|
||||||
|
|
||||||
|
private static Log log = LogFactory.getLog(RoleImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user roles (except all internal roles) from system.
|
||||||
|
*
|
||||||
|
* @return A list of users
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getRoles() {
|
||||||
|
List<String> filteredRoles;
|
||||||
|
try {
|
||||||
|
filteredRoles = getRolesFromUserStore();
|
||||||
|
} catch (MDMAPIException e) {
|
||||||
|
log.error(e.getErrorMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
||||||
|
responsePayload.setResponseContent(filteredRoles);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user roles by user store(except all internal roles) from system.
|
||||||
|
*
|
||||||
|
* @return A list of users
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{userStore}")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getRoles(@PathParam("userStore") String userStore) {
|
||||||
|
String[] roles;
|
||||||
|
try {
|
||||||
|
AbstractUserStoreManager abstractUserStoreManager =
|
||||||
|
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of user roles");
|
||||||
|
}
|
||||||
|
roles = abstractUserStoreManager.getRoleNames(userStore + "/*", -1, false, true, true);
|
||||||
|
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of user roles.";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
// removing all internal roles and roles created for Service-providers
|
||||||
|
List<String> filteredRoles = new ArrayList<>();
|
||||||
|
for (String role : roles) {
|
||||||
|
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
|
||||||
|
filteredRoles.add(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
||||||
|
responsePayload.setResponseContent(filteredRoles);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user roles by providing a filtering criteria(except all internal roles & system roles) from system.
|
||||||
|
*
|
||||||
|
* @return A list of users
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("search")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getMatchingRoles(@QueryParam("filter") String filter) {
|
||||||
|
String[] roles;
|
||||||
|
try {
|
||||||
|
AbstractUserStoreManager abstractUserStoreManager =
|
||||||
|
(AbstractUserStoreManager) DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of user roles using filter : " + filter);
|
||||||
|
}
|
||||||
|
roles = abstractUserStoreManager.getRoleNames("*" + filter + "*", -1, true, true, true);
|
||||||
|
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of user roles using the filter : " + filter;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
// removing all internal roles and roles created for Service-providers
|
||||||
|
List<String> filteredRoles = new ArrayList<>();
|
||||||
|
for (String role : roles) {
|
||||||
|
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
|
||||||
|
filteredRoles.add(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("All matching user roles were successfully retrieved.");
|
||||||
|
responsePayload.setResponseContent(filteredRoles);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get role permissions.
|
||||||
|
*
|
||||||
|
* @return list of permissions
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("permissions")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getPermissions(@QueryParam("rolename") String roleName) {
|
||||||
|
try {
|
||||||
|
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
|
||||||
|
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
|
||||||
|
final UIPermissionNode rolePermissions;
|
||||||
|
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
|
||||||
|
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
|
||||||
|
}
|
||||||
|
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
|
||||||
|
rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("All permissions retrieved");
|
||||||
|
responsePayload.setResponseContent(rolePermissions);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} catch (UserAdminException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the user role";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user role of the system
|
||||||
|
*
|
||||||
|
* @return user role
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("role")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getRole(@QueryParam("rolename") String roleName) {
|
||||||
|
RoleWrapper roleWrapper = new RoleWrapper();
|
||||||
|
try {
|
||||||
|
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
final UserRealm userRealm = DeviceMgtAPIUtils.getUserRealm();
|
||||||
|
org.wso2.carbon.user.core.UserRealm userRealmCore = null;
|
||||||
|
if (userRealm instanceof org.wso2.carbon.user.core.UserRealm) {
|
||||||
|
userRealmCore = (org.wso2.carbon.user.core.UserRealm) userRealm;
|
||||||
|
}
|
||||||
|
|
||||||
|
final UserRealmProxy userRealmProxy = new UserRealmProxy(userRealmCore);
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of user roles");
|
||||||
|
}
|
||||||
|
if (userStoreManager.isExistingRole(roleName)) {
|
||||||
|
roleWrapper.setRoleName(roleName);
|
||||||
|
roleWrapper.setUsers(userStoreManager.getUserListOfRole(roleName));
|
||||||
|
// Get the permission nodes and hand picking only device management and login perms
|
||||||
|
final UIPermissionNode rolePermissions = getUIPermissionNode(roleName, userRealmProxy);
|
||||||
|
ArrayList<String> permList = new ArrayList<>();
|
||||||
|
iteratePermissions(rolePermissions, permList);
|
||||||
|
roleWrapper.setPermissionList(rolePermissions);
|
||||||
|
String[] permListAr = new String[permList.size()];
|
||||||
|
roleWrapper.setPermissions(permList.toArray(permListAr));
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | UserAdminException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the user role";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("All user roles were successfully retrieved.");
|
||||||
|
responsePayload.setResponseContent(roleWrapper);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private UIPermissionNode getUIPermissionNode(String roleName, UserRealmProxy userRealmProxy)
|
||||||
|
throws UserAdminException {
|
||||||
|
final UIPermissionNode rolePermissions =
|
||||||
|
userRealmProxy.getRolePermissions(roleName, MultitenantConstants.SUPER_TENANT_ID);
|
||||||
|
UIPermissionNode[] deviceMgtPermissions = new UIPermissionNode[2];
|
||||||
|
|
||||||
|
for (UIPermissionNode permissionNode : rolePermissions.getNodeList()) {
|
||||||
|
if (permissionNode.getResourcePath().equals("/permission/admin")) {
|
||||||
|
for (UIPermissionNode node : permissionNode.getNodeList()) {
|
||||||
|
if (node.getResourcePath().equals("/permission/admin/device-mgt")) {
|
||||||
|
deviceMgtPermissions[0] = node;
|
||||||
|
} else if (node.getResourcePath().equals("/permission/admin/login")) {
|
||||||
|
deviceMgtPermissions[1] = node;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rolePermissions.setNodeList(deviceMgtPermissions);
|
||||||
|
return rolePermissions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API is used to persist a new Role
|
||||||
|
*
|
||||||
|
* @param roleWrapper for role
|
||||||
|
* @return response
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response addRole(RoleWrapper roleWrapper) {
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Persisting the role to user store");
|
||||||
|
}
|
||||||
|
Permission[] permissions = null;
|
||||||
|
if (roleWrapper.getPermissions() != null && roleWrapper.getPermissions().length > 0) {
|
||||||
|
permissions = new Permission[roleWrapper.getPermissions().length];
|
||||||
|
|
||||||
|
for (int i = 0; i < permissions.length; i++) {
|
||||||
|
String permission = roleWrapper.getPermissions()[i];
|
||||||
|
permissions[i] = new Permission(permission, CarbonConstants.UI_PERMISSION_ACTION);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
userStoreManager.addRole(roleWrapper.getRoleName(), roleWrapper.getUsers(), permissions);
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = e.getMessage();
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API is used to update a role Role
|
||||||
|
*
|
||||||
|
* @param roleWrapper for role
|
||||||
|
* @return response
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response updateRole(@QueryParam("rolename") String roleName, RoleWrapper roleWrapper) {
|
||||||
|
String newRoleName = roleWrapper.getRoleName();
|
||||||
|
try {
|
||||||
|
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Updating the role to user store");
|
||||||
|
}
|
||||||
|
if (newRoleName != null && !roleName.equals(newRoleName)) {
|
||||||
|
userStoreManager.updateRoleName(roleName, newRoleName);
|
||||||
|
}
|
||||||
|
if (roleWrapper.getUsers() != null) {
|
||||||
|
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
||||||
|
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(newRoleName)),
|
||||||
|
Arrays.asList(roleWrapper.getUsers()));
|
||||||
|
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
|
||||||
|
.getObjectsToAdd().size()]);
|
||||||
|
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
|
||||||
|
.getObjectsToRemove().size()]);
|
||||||
|
userStoreManager.updateUserListOfRole(newRoleName, usersToDelete, usersToAdd);
|
||||||
|
}
|
||||||
|
if (roleWrapper.getPermissions() != null) {
|
||||||
|
// Delete all authorizations for the current role before authorizing the permission tree
|
||||||
|
authorizationManager.clearRoleAuthorization(roleName);
|
||||||
|
if (roleWrapper.getPermissions().length > 0) {
|
||||||
|
for (int i = 0; i < roleWrapper.getPermissions().length; i++) {
|
||||||
|
String permission = roleWrapper.getPermissions()[i];
|
||||||
|
authorizationManager.authorizeRole(roleName, permission, CarbonConstants.UI_PERMISSION_ACTION);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = e.getMessage();
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API is used to delete a role and authorizations
|
||||||
|
*
|
||||||
|
* @param roleName to delete
|
||||||
|
* @return response
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@DELETE
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response deleteRole(@QueryParam("rolename") String roleName) {
|
||||||
|
try {
|
||||||
|
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
final AuthorizationManager authorizationManager = DeviceMgtAPIUtils.getAuthorizationManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Deleting the role in user store");
|
||||||
|
}
|
||||||
|
userStoreManager.deleteRole(roleName);
|
||||||
|
// Delete all authorizations for the current role before deleting
|
||||||
|
authorizationManager.clearRoleAuthorization(roleName);
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while deleting the role: " + roleName;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API is used to update users of a role
|
||||||
|
*
|
||||||
|
* @param roleName to update
|
||||||
|
* @param userList of the users
|
||||||
|
* @return response
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Path("users")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response updateUsers(@QueryParam("rolename") String roleName, List<String> userList) {
|
||||||
|
try {
|
||||||
|
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Updating the users of a role");
|
||||||
|
}
|
||||||
|
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
||||||
|
transformer.transform(Arrays.asList(userStoreManager.getUserListOfRole(roleName)),
|
||||||
|
userList);
|
||||||
|
final String[] usersToAdd = transformer.getObjectsToAdd().toArray(new String[transformer
|
||||||
|
.getObjectsToAdd().size()]);
|
||||||
|
final String[] usersToDelete = transformer.getObjectsToRemove().toArray(new String[transformer
|
||||||
|
.getObjectsToRemove().size()]);
|
||||||
|
|
||||||
|
userStoreManager.updateUserListOfRole(roleName, usersToDelete, usersToAdd);
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while saving the users of the role: " + roleName;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private ArrayList<String> iteratePermissions(UIPermissionNode uiPermissionNode, ArrayList<String> list) {
|
||||||
|
for (UIPermissionNode permissionNode : uiPermissionNode.getNodeList()) {
|
||||||
|
list.add(permissionNode.getResourcePath());
|
||||||
|
if (permissionNode.getNodeList() != null && permissionNode.getNodeList().length > 0) {
|
||||||
|
iteratePermissions(permissionNode, list);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to retrieve the role count of the system.
|
||||||
|
*
|
||||||
|
* @return returns the count.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("count")
|
||||||
|
public Response getRoleCount() {
|
||||||
|
try {
|
||||||
|
List<String> filteredRoles = getRolesFromUserStore();
|
||||||
|
Integer count = filteredRoles.size();
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (MDMAPIException e) {
|
||||||
|
log.error(e.getErrorMessage(), e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getErrorMessage()).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<String> getRolesFromUserStore() throws MDMAPIException {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
String[] roles;
|
||||||
|
try {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of user roles");
|
||||||
|
}
|
||||||
|
roles = userStoreManager.getRoleNames();
|
||||||
|
|
||||||
|
} catch (UserStoreException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of user roles.";
|
||||||
|
throw new MDMAPIException(msg, e);
|
||||||
|
}
|
||||||
|
// removing all internal roles and roles created for Service-providers
|
||||||
|
List<String> filteredRoles = new ArrayList<>();
|
||||||
|
for (String role : roles) {
|
||||||
|
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
|
||||||
|
filteredRoles.add(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filteredRoles;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,772 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package org.wso2.carbon.device.mgt.jaxrs.api.impl;
|
||||||
|
|
||||||
|
import org.apache.commons.codec.binary.Base64;
|
||||||
|
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.wso2.carbon.context.CarbonContext;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.UserCredentialWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.beans.UserWrapper;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.util.Constants;
|
||||||
|
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||||
|
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||||
|
import org.wso2.carbon.device.mgt.core.service.EmailMetaInfo;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.CredentialManagementResponseBuilder;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.api.util.ResponsePayload;
|
||||||
|
import org.wso2.carbon.device.mgt.jaxrs.util.SetReferenceTransformer;
|
||||||
|
import org.wso2.carbon.user.api.UserStoreException;
|
||||||
|
import org.wso2.carbon.user.api.UserStoreManager;
|
||||||
|
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
|
||||||
|
|
||||||
|
import javax.ws.rs.Consumes;
|
||||||
|
import javax.ws.rs.DELETE;
|
||||||
|
import javax.ws.rs.GET;
|
||||||
|
import javax.ws.rs.POST;
|
||||||
|
import javax.ws.rs.PUT;
|
||||||
|
import javax.ws.rs.Path;
|
||||||
|
import javax.ws.rs.PathParam;
|
||||||
|
import javax.ws.rs.Produces;
|
||||||
|
import javax.ws.rs.QueryParam;
|
||||||
|
import javax.ws.rs.core.MediaType;
|
||||||
|
import javax.ws.rs.core.Response;
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Properties;
|
||||||
|
import java.util.Random;
|
||||||
|
import java.util.TreeSet;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This class represents the JAX-RS services of User related functionality.
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("NonJaxWsWebServices")
|
||||||
|
public class UserImpl implements org.wso2.carbon.device.mgt.jaxrs.api.User {
|
||||||
|
|
||||||
|
private static final String ROLE_EVERYONE = "Internal/everyone";
|
||||||
|
private static Log log = LogFactory.getLog(UserImpl.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to add user to emm-user-store.
|
||||||
|
*
|
||||||
|
* @param userWrapper Wrapper object representing input json payload
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response addUser(UserWrapper userWrapper) {
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
|
||||||
|
// if user already exists
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + userWrapper.getUsername() +
|
||||||
|
" already exists. Therefore, request made to add user was refused.");
|
||||||
|
}
|
||||||
|
// returning response with bad request state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
|
||||||
|
responsePayload.
|
||||||
|
setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
||||||
|
" already exists. Therefore, request made to add user was refused.");
|
||||||
|
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
String initialUserPassword = generateInitialUserPassword();
|
||||||
|
Map<String, String> defaultUserClaims =
|
||||||
|
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
|
||||||
|
userWrapper.getEmailAddress());
|
||||||
|
// calling addUser method of carbon user api
|
||||||
|
userStoreManager.addUser(userWrapper.getUsername(), initialUserPassword,
|
||||||
|
userWrapper.getRoles(), defaultUserClaims, null);
|
||||||
|
// invite newly added user to enroll device
|
||||||
|
inviteNewlyAddedUserToEnrollDevice(userWrapper.getUsername(), initialUserPassword);
|
||||||
|
// Outputting debug message upon successful addition of user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + userWrapper.getUsername() + " was successfully added.");
|
||||||
|
}
|
||||||
|
// returning response with success state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
||||||
|
" was successfully added.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Exception in trying to add user by username: " + userWrapper.getUsername();
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to get user information from emm-user-store.
|
||||||
|
*
|
||||||
|
* @param username User-name of the user
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("view")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getUser(@QueryParam("username") String username) {
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (userStoreManager.isExistingUser(username)) {
|
||||||
|
UserWrapper user = new UserWrapper();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
||||||
|
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
||||||
|
// Outputting debug message upon successful retrieval of user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " was found.");
|
||||||
|
}
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("User information was retrieved successfully.");
|
||||||
|
responsePayload.setResponseContent(user);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
// Outputting debug message upon trying to remove non-existing user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " does not exist.");
|
||||||
|
}
|
||||||
|
// returning response with bad request state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
||||||
|
responsePayload.setMessageFromServer(
|
||||||
|
"User by username: " + username + " does not exist.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Exception in trying to retrieve user by username: " + username;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update user in user store
|
||||||
|
*
|
||||||
|
* @param userWrapper Wrapper object representing input json payload
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response updateUser(UserWrapper userWrapper, @QueryParam("username") String username) {
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (userStoreManager.isExistingUser(userWrapper.getUsername())) {
|
||||||
|
Map<String, String> defaultUserClaims =
|
||||||
|
buildDefaultUserClaims(userWrapper.getFirstname(), userWrapper.getLastname(),
|
||||||
|
userWrapper.getEmailAddress());
|
||||||
|
if (StringUtils.isNotEmpty(userWrapper.getPassword())) {
|
||||||
|
// Decoding Base64 encoded password
|
||||||
|
byte[] decodedBytes = Base64.decodeBase64(userWrapper.getPassword());
|
||||||
|
userStoreManager.updateCredentialByAdmin(userWrapper.getUsername(),
|
||||||
|
new String(decodedBytes, "UTF-8"));
|
||||||
|
log.debug("User credential of username: " + userWrapper.getUsername() + " has been changed");
|
||||||
|
}
|
||||||
|
List<String> listofFilteredRoles = getFilteredRoles(userStoreManager, userWrapper.getUsername());
|
||||||
|
final String[] existingRoles = listofFilteredRoles.toArray(new String[listofFilteredRoles.size()]);
|
||||||
|
|
||||||
|
/*
|
||||||
|
Use the Set theory to find the roles to delete and roles to add
|
||||||
|
The difference of roles in existingRolesSet and newRolesSet needed to be deleted
|
||||||
|
new roles to add = newRolesSet - The intersection of roles in existingRolesSet and newRolesSet
|
||||||
|
*/
|
||||||
|
final TreeSet<String> existingRolesSet = new TreeSet<>();
|
||||||
|
Collections.addAll(existingRolesSet, existingRoles);
|
||||||
|
final TreeSet<String> newRolesSet = new TreeSet<>();
|
||||||
|
Collections.addAll(newRolesSet, userWrapper.getRoles());
|
||||||
|
existingRolesSet.removeAll(newRolesSet);
|
||||||
|
// Now we have the roles to delete
|
||||||
|
String[] rolesToDelete = existingRolesSet.toArray(new String[existingRolesSet.size()]);
|
||||||
|
List<String> roles = new ArrayList<>(Arrays.asList(rolesToDelete));
|
||||||
|
roles.remove(ROLE_EVERYONE);
|
||||||
|
rolesToDelete = new String[0];
|
||||||
|
// Clearing and re-initializing the set
|
||||||
|
existingRolesSet.clear();
|
||||||
|
Collections.addAll(existingRolesSet, existingRoles);
|
||||||
|
newRolesSet.removeAll(existingRolesSet);
|
||||||
|
// Now we have the roles to add
|
||||||
|
String[] rolesToAdd = newRolesSet.toArray(new String[newRolesSet.size()]);
|
||||||
|
userStoreManager.updateRoleListOfUser(userWrapper.getUsername(), rolesToDelete, rolesToAdd);
|
||||||
|
userStoreManager.setUserClaimValues(userWrapper.getUsername(), defaultUserClaims, null);
|
||||||
|
// Outputting debug message upon successful addition of user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + userWrapper.getUsername() + " was successfully updated.");
|
||||||
|
}
|
||||||
|
// returning response with success state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
|
responsePayload.setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
||||||
|
" was successfully updated.");
|
||||||
|
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + userWrapper.getUsername() +
|
||||||
|
" doesn't exists. Therefore, request made to update user was refused.");
|
||||||
|
}
|
||||||
|
// returning response with bad request state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_CONFLICT);
|
||||||
|
responsePayload.
|
||||||
|
setMessageFromServer("User by username: " + userWrapper.getUsername() +
|
||||||
|
" doesn't exists. Therefore, request made to update user was refused.");
|
||||||
|
return Response.status(Response.Status.CONFLICT).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | UnsupportedEncodingException | MDMAPIException e) {
|
||||||
|
String msg = "Exception in trying to update user by username: " + userWrapper.getUsername();
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Private method to be used by addUser() to
|
||||||
|
* generate an initial user password for a user.
|
||||||
|
* This will be the password used by a user for his initial login to the system.
|
||||||
|
*
|
||||||
|
* @return {string} Initial User Password
|
||||||
|
*/
|
||||||
|
private String generateInitialUserPassword() {
|
||||||
|
int passwordLength = 6;
|
||||||
|
//defining the pool of characters to be used for initial password generation
|
||||||
|
String lowerCaseCharset = "abcdefghijklmnopqrstuvwxyz";
|
||||||
|
String upperCaseCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||||
|
String numericCharset = "0123456789";
|
||||||
|
Random randomGenerator = new Random();
|
||||||
|
String totalCharset = lowerCaseCharset + upperCaseCharset + numericCharset;
|
||||||
|
int totalCharsetLength = totalCharset.length();
|
||||||
|
StringBuilder initialUserPassword = new StringBuilder();
|
||||||
|
for (int i = 0; i < passwordLength; i++) {
|
||||||
|
initialUserPassword
|
||||||
|
.append(totalCharset.charAt(randomGenerator.nextInt(totalCharsetLength)));
|
||||||
|
}
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Initial user password is created for new user: " + initialUserPassword);
|
||||||
|
}
|
||||||
|
return initialUserPassword.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to build default user claims.
|
||||||
|
*
|
||||||
|
* @param firstname First name of the user
|
||||||
|
* @param lastname Last name of the user
|
||||||
|
* @param emailAddress Email address of the user
|
||||||
|
* @return {Object} Default user claims to be provided
|
||||||
|
*/
|
||||||
|
private Map<String, String> buildDefaultUserClaims(String firstname, String lastname, String emailAddress) {
|
||||||
|
Map<String, String> defaultUserClaims = new HashMap<>();
|
||||||
|
defaultUserClaims.put(Constants.USER_CLAIM_FIRST_NAME, firstname);
|
||||||
|
defaultUserClaims.put(Constants.USER_CLAIM_LAST_NAME, lastname);
|
||||||
|
defaultUserClaims.put(Constants.USER_CLAIM_EMAIL_ADDRESS, emailAddress);
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Default claim map is created for new user: " + defaultUserClaims.toString());
|
||||||
|
}
|
||||||
|
return defaultUserClaims;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to remove user from emm-user-store.
|
||||||
|
*
|
||||||
|
* @param username Username of the user
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@DELETE
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response removeUser(@QueryParam("username") String username) {
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (userStoreManager.isExistingUser(username)) {
|
||||||
|
// if user already exists, trying to remove user
|
||||||
|
userStoreManager.deleteUser(username);
|
||||||
|
// Outputting debug message upon successful removal of user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " was successfully removed.");
|
||||||
|
}
|
||||||
|
// returning response with success state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer(
|
||||||
|
"User by username: " + username + " was successfully removed.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
// Outputting debug message upon trying to remove non-existing user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " does not exist for removal.");
|
||||||
|
}
|
||||||
|
// returning response with bad request state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
||||||
|
responsePayload.setMessageFromServer(
|
||||||
|
"User by username: " + username + " does not exist for removal.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Exception in trying to remove user by username: " + username;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* get all the roles except for the internal/xxx and application/xxx
|
||||||
|
*
|
||||||
|
* @param userStoreManager User Store Manager associated with the currently logged in user
|
||||||
|
* @param username Username of the currently logged in user
|
||||||
|
* @return the list of filtered roles
|
||||||
|
*/
|
||||||
|
private List<String> getFilteredRoles(UserStoreManager userStoreManager, String username) {
|
||||||
|
String[] roleListOfUser = new String[0];
|
||||||
|
try {
|
||||||
|
roleListOfUser = userStoreManager.getRoleListOfUser(username);
|
||||||
|
} catch (UserStoreException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
List<String> filteredRoles = new ArrayList<>();
|
||||||
|
for (String role : roleListOfUser) {
|
||||||
|
if (!(role.startsWith("Internal/") || role.startsWith("Authentication/"))) {
|
||||||
|
filteredRoles.add(role);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return filteredRoles;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get user's roles by username
|
||||||
|
*
|
||||||
|
* @param username Username of the user
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("roles")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getRoles(@QueryParam("username") String username) {
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (userStoreManager.isExistingUser(username)) {
|
||||||
|
responsePayload.setResponseContent(Collections.singletonList(getFilteredRoles(userStoreManager, username)));
|
||||||
|
// Outputting debug message upon successful removal of user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " was successfully removed.");
|
||||||
|
}
|
||||||
|
// returning response with success state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer(
|
||||||
|
"User roles obtained for user " + username);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
} else {
|
||||||
|
// Outputting debug message upon trying to remove non-existing user
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("User by username: " + username + " does not exist for role retrieval.");
|
||||||
|
}
|
||||||
|
// returning response with bad request state
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST);
|
||||||
|
responsePayload.setMessageFromServer(
|
||||||
|
"User by username: " + username + " does not exist for role retrieval.");
|
||||||
|
return Response.status(Response.Status.BAD_REQUEST).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Exception in trying to retrieve roles for user by username: " + username;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of all users with all user-related info.
|
||||||
|
*
|
||||||
|
* @return A list of users
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getAllUsers() {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of users with all user-related information");
|
||||||
|
}
|
||||||
|
List<UserWrapper> userList;
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
String[] users = userStoreManager.listUsers("*", -1);
|
||||||
|
userList = new ArrayList<>(users.length);
|
||||||
|
UserWrapper user;
|
||||||
|
for (String username : users) {
|
||||||
|
user = new UserWrapper();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
||||||
|
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
||||||
|
userList.add(user);
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of users";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
int count;
|
||||||
|
count = userList.size();
|
||||||
|
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
|
||||||
|
"Obtained user count: " + count);
|
||||||
|
responsePayload.setResponseContent(userList);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of all users with all user-related info.
|
||||||
|
*
|
||||||
|
* @return A list of users
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("{filter}")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response getMatchingUsers(@PathParam("filter") String filter) {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of users with all user-related information using the filter : " + filter);
|
||||||
|
}
|
||||||
|
List<UserWrapper> userList;
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
String[] users = userStoreManager.listUsers(filter + "*", -1);
|
||||||
|
userList = new ArrayList<>(users.length);
|
||||||
|
UserWrapper user;
|
||||||
|
for (String username : users) {
|
||||||
|
user = new UserWrapper();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
||||||
|
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
||||||
|
userList.add(user);
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of users using the filter : " + filter;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
int count;
|
||||||
|
count = userList.size();
|
||||||
|
responsePayload.setMessageFromServer("All users were successfully retrieved. " +
|
||||||
|
"Obtained user count: " + count);
|
||||||
|
responsePayload.setResponseContent(userList);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of user names in the system.
|
||||||
|
*
|
||||||
|
* @return A list of user names.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("view-users")
|
||||||
|
public Response getAllUsersByUsername(@QueryParam("username") String userName) {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of users by name");
|
||||||
|
}
|
||||||
|
List<UserWrapper> userList;
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
|
||||||
|
userList = new ArrayList<>(users.length);
|
||||||
|
UserWrapper user;
|
||||||
|
for (String username : users) {
|
||||||
|
user = new UserWrapper();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setEmailAddress(getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS));
|
||||||
|
user.setFirstname(getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
user.setLastname(getClaimValue(username, Constants.USER_CLAIM_LAST_NAME));
|
||||||
|
userList.add(user);
|
||||||
|
}
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of users";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
int count;
|
||||||
|
count = userList.size();
|
||||||
|
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
|
||||||
|
"Obtained user count: " + count);
|
||||||
|
responsePayload.setResponseContent(userList);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the list of user names in the system.
|
||||||
|
*
|
||||||
|
* @return A list of user names.
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("users-by-username")
|
||||||
|
public Response getAllUserNamesByUsername(@QueryParam("username") String userName) {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Getting the list of users by name");
|
||||||
|
}
|
||||||
|
List<String> userList;
|
||||||
|
try {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
String[] users = userStoreManager.listUsers("*" + userName + "*", -1);
|
||||||
|
userList = new ArrayList<>(users.length);
|
||||||
|
Collections.addAll(userList, users);
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while retrieving the list of users";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
int count;
|
||||||
|
count = userList.size();
|
||||||
|
responsePayload.setMessageFromServer("All users by username were successfully retrieved. " +
|
||||||
|
"Obtained user count: " + count);
|
||||||
|
responsePayload.setResponseContent(userList);
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a claim-value from user-store.
|
||||||
|
*
|
||||||
|
* @param username Username of the user
|
||||||
|
* @param claimUri required ClaimUri
|
||||||
|
* @return claim value
|
||||||
|
*/
|
||||||
|
private String getClaimValue(String username, String claimUri) throws MDMAPIException {
|
||||||
|
UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
try {
|
||||||
|
return userStoreManager.getUserClaimValue(username, claimUri, null);
|
||||||
|
} catch (UserStoreException e) {
|
||||||
|
throw new MDMAPIException("Error occurred while retrieving value assigned to the claim '" +
|
||||||
|
claimUri + "'", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method used to send an invitation email to a new user to enroll a device.
|
||||||
|
*
|
||||||
|
* @param username Username of the user
|
||||||
|
*/
|
||||||
|
private void inviteNewlyAddedUserToEnrollDevice(String username, String password) throws MDMAPIException {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Sending invitation mail to user by username: " + username);
|
||||||
|
}
|
||||||
|
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||||
|
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
|
||||||
|
tenantDomain = "";
|
||||||
|
}
|
||||||
|
if (!username.contains("/")) {
|
||||||
|
username = "/" + username;
|
||||||
|
}
|
||||||
|
String[] usernameBits = username.split("/");
|
||||||
|
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.setProperty("username", usernameBits[1]);
|
||||||
|
props.setProperty("domain-name", tenantDomain);
|
||||||
|
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
props.setProperty("password", password);
|
||||||
|
|
||||||
|
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
|
||||||
|
|
||||||
|
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
|
||||||
|
try {
|
||||||
|
deviceManagementProviderService.sendRegistrationEmail(metaInfo);
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Error occurred while sending registration email to user '" + username + "'";
|
||||||
|
log.error(msg, e);
|
||||||
|
throw new MDMAPIException(msg, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method used to send an invitation email to a existing user to enroll a device.
|
||||||
|
*
|
||||||
|
* @param usernames Username list of the users to be invited
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("email-invitation")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response inviteExistingUsersToEnrollDevice(List<String> usernames) {
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Sending enrollment invitation mail to existing user.");
|
||||||
|
}
|
||||||
|
DeviceManagementProviderService deviceManagementProviderService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
try {
|
||||||
|
for (String username : usernames) {
|
||||||
|
String recipient = getClaimValue(username, Constants.USER_CLAIM_EMAIL_ADDRESS);
|
||||||
|
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.setProperty("first-name", getClaimValue(username, Constants.USER_CLAIM_FIRST_NAME));
|
||||||
|
props.setProperty("username", username);
|
||||||
|
|
||||||
|
EmailMetaInfo metaInfo = new EmailMetaInfo(recipient, props);
|
||||||
|
deviceManagementProviderService.sendEnrolmentInvitation(metaInfo);
|
||||||
|
}
|
||||||
|
} catch (DeviceManagementException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while inviting user to enrol their device";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
ResponsePayload responsePayload = new ResponsePayload();
|
||||||
|
responsePayload.setStatusCode(HttpStatus.SC_OK);
|
||||||
|
responsePayload.setMessageFromServer("Email invitation was successfully sent to user.");
|
||||||
|
return Response.status(Response.Status.OK).entity(responsePayload).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a list of devices based on the username.
|
||||||
|
*
|
||||||
|
* @param username Username of the device owner
|
||||||
|
* @return A list of devices
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
@Path("devices")
|
||||||
|
public Response getAllDeviceOfUser(@QueryParam("username") String username,
|
||||||
|
@QueryParam("start") int startIdx, @QueryParam("length") int length) {
|
||||||
|
DeviceManagementProviderService dmService;
|
||||||
|
try {
|
||||||
|
dmService = DeviceMgtAPIUtils.getDeviceManagementService();
|
||||||
|
if (length > 0) {
|
||||||
|
PaginationRequest request = new PaginationRequest(startIdx, length);
|
||||||
|
request.setOwner(username);
|
||||||
|
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(request)).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(dmService.getDevicesOfUser(username)).build();
|
||||||
|
} catch (DeviceManagementException e) {
|
||||||
|
String msg = "Device management error";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method is used to retrieve the user count of the system.
|
||||||
|
*
|
||||||
|
* @return returns the count.
|
||||||
|
* @
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@GET
|
||||||
|
@Path("count")
|
||||||
|
public Response getUserCount() {
|
||||||
|
try {
|
||||||
|
String[] users = DeviceMgtAPIUtils.getUserStoreManager().listUsers("*", -1);
|
||||||
|
Integer count = 0;
|
||||||
|
if (users != null) {
|
||||||
|
count = users.length;
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).entity(count).build();
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg =
|
||||||
|
"Error occurred while retrieving the list of users that exist within the current tenant";
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API is used to update roles of a user
|
||||||
|
*
|
||||||
|
* @param username
|
||||||
|
* @param userList
|
||||||
|
* @return
|
||||||
|
* @
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@PUT
|
||||||
|
@Path("{roleName}/users")
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response updateRoles(@PathParam("username") String username, List<String> userList) {
|
||||||
|
try {
|
||||||
|
final UserStoreManager userStoreManager = DeviceMgtAPIUtils.getUserStoreManager();
|
||||||
|
if (log.isDebugEnabled()) {
|
||||||
|
log.debug("Updating the roles of a user");
|
||||||
|
}
|
||||||
|
SetReferenceTransformer<String> transformer = new SetReferenceTransformer<>();
|
||||||
|
transformer.transform(Arrays.asList(userStoreManager.getRoleListOfUser(username)),
|
||||||
|
userList);
|
||||||
|
final String[] rolesToAdd = transformer.getObjectsToAdd().toArray(new String[transformer.getObjectsToAdd().size()]);
|
||||||
|
final String[] rolesToDelete = transformer.getObjectsToRemove().toArray(new String[transformer.getObjectsToRemove().size()]);
|
||||||
|
|
||||||
|
userStoreManager.updateRoleListOfUser(username, rolesToDelete, rolesToAdd);
|
||||||
|
} catch (UserStoreException | MDMAPIException e) {
|
||||||
|
String msg = "Error occurred while saving the roles for user: " + username;
|
||||||
|
log.error(msg, e);
|
||||||
|
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build();
|
||||||
|
}
|
||||||
|
return Response.status(Response.Status.OK).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to change the user password.
|
||||||
|
*
|
||||||
|
* @param credentials Wrapper object representing user credentials.
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
* @
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("change-password")
|
||||||
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response resetPassword(UserCredentialWrapper credentials) {
|
||||||
|
return CredentialManagementResponseBuilder.buildChangePasswordResponse(credentials);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Method to change the user password.
|
||||||
|
*
|
||||||
|
* @param credentials Wrapper object representing user credentials.
|
||||||
|
* @return {Response} Status of the request wrapped inside Response object.
|
||||||
|
* @
|
||||||
|
*/
|
||||||
|
@Override
|
||||||
|
@POST
|
||||||
|
@Path("reset-password")
|
||||||
|
@Consumes({MediaType.APPLICATION_JSON})
|
||||||
|
@Produces({MediaType.APPLICATION_JSON})
|
||||||
|
public Response resetPasswordByAdmin(UserCredentialWrapper credentials) {
|
||||||
|
return CredentialManagementResponseBuilder.buildResetPasswordResponse(credentials);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@ -52,7 +52,7 @@ public class CredentialManagementResponseBuilder {
|
|||||||
userStoreManager.updateCredential(credentials.getUsername(), new String(
|
userStoreManager.updateCredential(credentials.getUsername(), new String(
|
||||||
decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8"));
|
decodedNewPassword, "UTF-8"), new String(decodedOldPassword, "UTF-8"));
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() +
|
responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() +
|
||||||
" was successfully changed.");
|
" was successfully changed.");
|
||||||
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
||||||
} catch (UserStoreException e) {
|
} catch (UserStoreException e) {
|
||||||
@ -84,7 +84,7 @@ public class CredentialManagementResponseBuilder {
|
|||||||
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String(
|
userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String(
|
||||||
decodedNewPassword, "UTF-8"));
|
decodedNewPassword, "UTF-8"));
|
||||||
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
responsePayload.setStatusCode(HttpStatus.SC_CREATED);
|
||||||
responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() +
|
responsePayload.setMessageFromServer("UserImpl password by username: " + credentials.getUsername() +
|
||||||
" was successfully changed.");
|
" was successfully changed.");
|
||||||
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
return Response.status(Response.Status.CREATED).entity(responsePayload).build();
|
||||||
} catch (UserStoreException e) {
|
} catch (UserStoreException e) {
|
||||||
|
|||||||
@ -87,7 +87,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
DeviceManagementProviderService deviceManagementProviderService =
|
DeviceManagementProviderService deviceManagementProviderService =
|
||||||
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
||||||
if (deviceManagementProviderService == null) {
|
if (deviceManagementProviderService == null) {
|
||||||
String msg = "Device Management provider service has not initialized.";
|
String msg = "DeviceImpl Management provider service has not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -99,7 +99,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
GroupManagementProviderService groupManagementProviderService =
|
GroupManagementProviderService groupManagementProviderService =
|
||||||
(GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null);
|
(GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null);
|
||||||
if (groupManagementProviderService == null) {
|
if (groupManagementProviderService == null) {
|
||||||
String msg = "Group Management service has not initialized.";
|
String msg = "GroupImpl Management service has not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -213,7 +213,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
ApplicationManagementProviderService applicationManagementProviderService =
|
ApplicationManagementProviderService applicationManagementProviderService =
|
||||||
(ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
|
(ApplicationManagementProviderService) ctx.getOSGiService(ApplicationManagementProviderService.class, null);
|
||||||
if (applicationManagementProviderService == null) {
|
if (applicationManagementProviderService == null) {
|
||||||
String msg = "Application management service has not initialized.";
|
String msg = "AuthenticationImpl management service has not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -226,7 +226,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
policyManagementService =
|
policyManagementService =
|
||||||
(PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
|
(PolicyManagerService) ctx.getOSGiService(PolicyManagerService.class, null);
|
||||||
if (policyManagementService == null) {
|
if (policyManagementService == null) {
|
||||||
String msg = "Policy Management service not initialized.";
|
String msg = "PolicyImpl Management service not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -274,7 +274,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
ctx.getOSGiService(CertificateManagementService.class, null);
|
ctx.getOSGiService(CertificateManagementService.class, null);
|
||||||
|
|
||||||
if (certificateManagementService == null) {
|
if (certificateManagementService == null) {
|
||||||
String msg = "Certificate Management service not initialized.";
|
String msg = "CertificateImpl Management service not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -299,7 +299,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
DeviceInformationManager deviceInformationManager =
|
DeviceInformationManager deviceInformationManager =
|
||||||
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
|
(DeviceInformationManager) ctx.getOSGiService(DeviceInformationManager.class, null);
|
||||||
if (deviceInformationManager == null) {
|
if (deviceInformationManager == null) {
|
||||||
String msg = "Device information Manager service has not initialized.";
|
String msg = "DeviceImpl information Manager service has not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
@ -313,7 +313,7 @@ public class DeviceMgtAPIUtils {
|
|||||||
SearchManagerService searchManagerService =
|
SearchManagerService searchManagerService =
|
||||||
(SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null);
|
(SearchManagerService) ctx.getOSGiService(SearchManagerService.class, null);
|
||||||
if (searchManagerService == null) {
|
if (searchManagerService == null) {
|
||||||
String msg = "Device search manager service has not initialized.";
|
String msg = "DeviceImpl search manager service has not initialized.";
|
||||||
log.error(msg);
|
log.error(msg);
|
||||||
throw new IllegalStateException(msg);
|
throw new IllegalStateException(msg);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -33,7 +33,7 @@ import org.wso2.carbon.device.mgt.jaxrs.beans.android.WebApplication;
|
|||||||
public class MDMAndroidOperationUtil {
|
public class MDMAndroidOperationUtil {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method is used to create Install Application operation.
|
* This method is used to create Install Authentication operation.
|
||||||
*
|
*
|
||||||
* @param application MobileApp application
|
* @param application MobileApp application
|
||||||
* @return operation
|
* @return operation
|
||||||
@ -76,7 +76,7 @@ public class MDMAndroidOperationUtil {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method is used to create Uninstall Application operation.
|
* This method is used to create Uninstall Authentication operation.
|
||||||
* @param application MobileApp application
|
* @param application MobileApp application
|
||||||
* @return operation
|
* @return operation
|
||||||
* @throws MDMAPIException
|
* @throws MDMAPIException
|
||||||
|
|||||||
@ -35,7 +35,7 @@ import java.util.Properties;
|
|||||||
public class MDMIOSOperationUtil {
|
public class MDMIOSOperationUtil {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This method is used to create Install Application operation.
|
* This method is used to create Install Authentication operation.
|
||||||
*
|
*
|
||||||
* @param application MobileApp application
|
* @param application MobileApp application
|
||||||
* @return operation
|
* @return operation
|
||||||
|
|||||||
@ -21,7 +21,7 @@ package org.wso2.carbon.device.mgt.jaxrs.beans;
|
|||||||
import java.util.Properties;
|
import java.util.Properties;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents the generic mobile Application information
|
* This class represents the generic mobile AuthenticationImpl information
|
||||||
* which is used by AppM.
|
* which is used by AppM.
|
||||||
*/
|
*/
|
||||||
public class MobileApp {
|
public class MobileApp {
|
||||||
|
|||||||
@ -53,11 +53,11 @@ public class Profile {
|
|||||||
this.tenantId = tenantId;
|
this.tenantId = tenantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* public List<Feature> getFeaturesList() {
|
/* public List<FeatureImpl> getFeaturesList() {
|
||||||
return featuresList;
|
return featuresList;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setFeaturesList(List<Feature> featuresList) {
|
public void setFeaturesList(List<FeatureImpl> featuresList) {
|
||||||
this.featuresList = featuresList;
|
this.featuresList = featuresList;
|
||||||
}*/
|
}*/
|
||||||
@XmlElement
|
@XmlElement
|
||||||
|
|||||||
@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents the Appstore Application information.
|
* This class represents the Appstore AuthenticationImpl information.
|
||||||
*/
|
*/
|
||||||
public class AppStoreApplication implements Serializable {
|
public class AppStoreApplication implements Serializable {
|
||||||
|
|
||||||
|
|||||||
@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents the Enterprise Application information.
|
* This class represents the Enterprise AuthenticationImpl information.
|
||||||
*/
|
*/
|
||||||
public class EnterpriseApplication implements Serializable {
|
public class EnterpriseApplication implements Serializable {
|
||||||
|
|
||||||
|
|||||||
@ -24,7 +24,7 @@ import org.wso2.carbon.device.mgt.jaxrs.api.common.MDMAPIException;
|
|||||||
import java.io.Serializable;
|
import java.io.Serializable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This class represents the Web Application information.
|
* This class represents the Web AuthenticationImpl information.
|
||||||
*/
|
*/
|
||||||
public class WebApplication implements Serializable {
|
public class WebApplication implements Serializable {
|
||||||
|
|
||||||
|
|||||||
@ -19,7 +19,7 @@
|
|||||||
package org.wso2.carbon.device.mgt.jaxrs.util;
|
package org.wso2.carbon.device.mgt.jaxrs.util;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Holds the constants used by Device Management Admin web application.
|
* Holds the constants used by DeviceImpl Management Admin web application.
|
||||||
*/
|
*/
|
||||||
public class Constants {
|
public class Constants {
|
||||||
|
|
||||||
|
|||||||
@ -163,23 +163,23 @@
|
|||||||
</jaxrs:providers>
|
</jaxrs:providers>
|
||||||
</jaxrs:server>
|
</jaxrs:server>
|
||||||
-->
|
-->
|
||||||
<bean id="operationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Operation"/>
|
<bean id="operationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.OperationImpl"/>
|
||||||
<bean id="deviceServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Device"/>
|
<bean id="deviceServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceImpl"/>
|
||||||
<bean id="groupServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Group"/>
|
<bean id="groupServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.GroupImpl"/>
|
||||||
<bean id="userServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.User"/>
|
<bean id="userServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.UserImpl"/>
|
||||||
<bean id="roleServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Role"/>
|
<bean id="roleServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.RoleImpl"/>
|
||||||
<bean id="featureServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Feature"/>
|
<bean id="featureServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.FeatureImpl"/>
|
||||||
<bean id="configurationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Configuration"/>
|
<bean id="configurationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.ConfigurationImpl"/>
|
||||||
<bean id="notificationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceNotification"/>
|
<bean id="notificationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceNotificationImpl"/>
|
||||||
<bean id="licenseServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.License"/>
|
<bean id="licenseServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.LicenseImpl"/>
|
||||||
<bean id="certificateServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Certificate"/>
|
<bean id="certificateServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.CertificateImpl"/>
|
||||||
<bean id="informationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceInformation"/>
|
<bean id="informationServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceInformationImpl"/>
|
||||||
<bean id="searchingServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.DeviceSearch"/>
|
<bean id="searchingServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.DeviceSearchImpl"/>
|
||||||
<!--
|
<!--
|
||||||
<bean id="authenticationServiceBean" class="Authentication"/>
|
<bean id="authenticationServiceBean" class="AuthenticationImpl"/>
|
||||||
-->
|
-->
|
||||||
<bean id="policyServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Policy"/>
|
<bean id="policyServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.PolicyImpl"/>
|
||||||
<bean id="profileServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.Profile"/>
|
<bean id="profileServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.api.impl.ProfileImpl"/>
|
||||||
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
|
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
|
||||||
<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.api.common.ErrorHandler"/>
|
<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.api.common.ErrorHandler"/>
|
||||||
|
|
||||||
|
|||||||
@ -97,7 +97,7 @@ public class DeviceManagementDAOFactory {
|
|||||||
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
|
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
|
||||||
|
|
||||||
public static DeviceDAO getDeviceDAO() {
|
public static DeviceDAO getDeviceDAO() {
|
||||||
if(databaseEngine != null) {
|
if (databaseEngine != null) {
|
||||||
switch (databaseEngine) {
|
switch (databaseEngine) {
|
||||||
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
|
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
|
||||||
return new OracleDeviceDAOImpl();
|
return new OracleDeviceDAOImpl();
|
||||||
@ -112,7 +112,7 @@ public class DeviceManagementDAOFactory {
|
|||||||
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
|
throw new UnsupportedDatabaseEngineException("Unsupported database engine : " + databaseEngine);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
throw new RuntimeException("Database engine has not initialized properly.");
|
throw new IllegalStateException("Database engine has not initialized properly.");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static DeviceTypeDAO getDeviceTypeDAO() {
|
public static DeviceTypeDAO getDeviceTypeDAO() {
|
||||||
|
|||||||
@ -1,13 +1,12 @@
|
|||||||
{{#zone "topCss"}}
|
{{#zone "topCss"}}
|
||||||
{{css "css/analytics.css"}}
|
{{css "css/analytics.css"}}
|
||||||
{{css "css/daterangepicker.css"}}
|
|
||||||
{{css "css/graph.css"}}
|
|
||||||
{{/zone}}
|
{{/zone}}
|
||||||
|
|
||||||
{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}}
|
{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}}
|
||||||
{{unit "cdmf.unit.ui.content.title" pageHeader=title}}
|
{{unit "cdmf.unit.ui.content.title" pageHeader=title}}
|
||||||
{{unit "cdmf.unit.lib.service-invoker-utility"}}
|
{{unit "cdmf.unit.lib.service-invoker-utility"}}
|
||||||
{{unit "cdmf.unit.lib.handlebars"}}
|
{{unit "cdmf.unit.lib.handlebars"}}
|
||||||
|
{{unit "cdmf.unit.lib.rickshaw-graph"}}
|
||||||
|
|
||||||
{{#zone "breadcrumbs"}}
|
{{#zone "breadcrumbs"}}
|
||||||
<li>
|
<li>
|
||||||
@ -15,29 +14,16 @@
|
|||||||
<i class="icon fw fw-home"></i>
|
<i class="icon fw fw-home"></i>
|
||||||
</a>
|
</a>
|
||||||
</li>
|
</li>
|
||||||
{{#if groupName}}
|
<li>
|
||||||
<li>
|
<a href="{{@app.context}}/devices">
|
||||||
<a href="{{@app.context}}/groups">
|
Devices
|
||||||
Groups
|
</a>
|
||||||
</a>
|
</li>
|
||||||
</li>
|
<li>
|
||||||
<li>
|
<a href="{{@app.context}}/device/{{deviceType}}?id={{deviceId}}">
|
||||||
<a href="{{@app.context}}/devices?groupId={{groupId}}&groupName={{groupName}}">
|
{{deviceName}}
|
||||||
{{groupName}}
|
</a>
|
||||||
</a>
|
</li>
|
||||||
</li>
|
|
||||||
{{else}}
|
|
||||||
<li>
|
|
||||||
<a href="{{@app.context}}/devices">
|
|
||||||
Devices
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="{{@app.context}}/device/{{deviceType}}?id={{deviceId}}">
|
|
||||||
{{deviceName}}
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
{{/if}}
|
|
||||||
<li>
|
<li>
|
||||||
<a href="#">
|
<a href="#">
|
||||||
Analytics
|
Analytics
|
||||||
@ -52,28 +38,7 @@
|
|||||||
<div class="col-lg-3 margin-top-double">
|
<div class="col-lg-3 margin-top-double">
|
||||||
<h1 class="grey ">{{deviceName}} Analytics</h1>
|
<h1 class="grey ">{{deviceName}} Analytics</h1>
|
||||||
</div>
|
</div>
|
||||||
<div id="rangeSliderWrapper" class="pull-right col-lg-9">
|
{{unit "cdmf.unit.analytics.date-range-picker"}}
|
||||||
<div id="dateRangePickerContainer">
|
|
||||||
<div class="btn-group" role="group">
|
|
||||||
<button id="hour-btn" type="button"
|
|
||||||
class="btn btn-default date-range">Hour
|
|
||||||
</button>
|
|
||||||
<button id="h12-btn" type="button"
|
|
||||||
class="btn btn-default date-range">12 Hours
|
|
||||||
</button>
|
|
||||||
<button id="h24-btn" type="button"
|
|
||||||
class="btn btn-default date-range">24 Hours
|
|
||||||
</button>
|
|
||||||
<button id="h48-btn" type="button"
|
|
||||||
class="btn btn-default date-range">48 Hours
|
|
||||||
</button>
|
|
||||||
<button id="date-range" type="button"
|
|
||||||
class="btn btn-default date-range last-child"
|
|
||||||
data-toggle="popup"
|
|
||||||
title="Click to set custom date range"></button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
<hr>
|
<hr>
|
||||||
<div class="clear"></div>
|
<div class="clear"></div>
|
||||||
@ -83,7 +48,3 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{/zone}}
|
{{/zone}}
|
||||||
{{#zone "bottomJs"}}
|
|
||||||
{{js "js/jquery.daterangepicker.js"}}
|
|
||||||
{{js "js/graph_util.js"}}
|
|
||||||
{{/zone}}
|
|
||||||
@ -18,33 +18,12 @@
|
|||||||
|
|
||||||
function onRequest(context) {
|
function onRequest(context) {
|
||||||
var utility = require("/app/modules/utility.js").utility;
|
var utility = require("/app/modules/utility.js").utility;
|
||||||
context.handlebars.registerHelper('equal', function (lvalue, rvalue, options) {
|
var deviceType = context.uriParams.deviceType;
|
||||||
if (arguments.length < 3) {
|
|
||||||
throw new Error("Handlebars Helper equal needs 2 parameters");
|
|
||||||
}
|
|
||||||
if (lvalue != rvalue) {
|
|
||||||
return options.inverse(this);
|
|
||||||
} else {
|
|
||||||
return options.fn(this);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
var groupName = request.getParameter("groupName");
|
|
||||||
var groupId = request.getParameter("groupId");
|
|
||||||
var deviceName = request.getParameter("deviceName");
|
var deviceName = request.getParameter("deviceName");
|
||||||
var deviceId = request.getParameter("deviceId");
|
var deviceId = request.getParameter("deviceId");
|
||||||
var deviceType = context.uriParams.deviceType;
|
|
||||||
var title = "Analytics";
|
|
||||||
if (groupName) {
|
|
||||||
title = "Group " + title;
|
|
||||||
} else {
|
|
||||||
title = "Device " + title;
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
"deviceAnalyticsViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "analytics-view"),
|
"deviceAnalyticsViewUnitName": utility.getTenantedDeviceUnitName(deviceType, "analytics-view"),
|
||||||
"deviceType": deviceType,
|
"deviceType": deviceType,
|
||||||
"title": title,
|
|
||||||
"groupName": groupName,
|
|
||||||
"groupId": groupId,
|
|
||||||
"deviceName": deviceName,
|
"deviceName": deviceName,
|
||||||
"deviceId": deviceId
|
"deviceId": deviceId
|
||||||
};
|
};
|
||||||
|
|||||||
@ -54,10 +54,3 @@
|
|||||||
margin-right: 20px;
|
margin-right: 20px;
|
||||||
margin-left: 20px;
|
margin-left: 20px;
|
||||||
}
|
}
|
||||||
.date-range{
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
}
|
|
||||||
|
|
||||||
#dateRangePickerContainer button.active{
|
|
||||||
background-color: #e6e6e6 !important;
|
|
||||||
}
|
|
||||||
@ -0,0 +1,52 @@
|
|||||||
|
{{#zone "topCss"}}
|
||||||
|
{{css "css/analytics.css"}}
|
||||||
|
{{/zone}}
|
||||||
|
|
||||||
|
{{unit "cdmf.unit.ui.title" pageTitle="Analytics"}}
|
||||||
|
{{unit "cdmf.unit.ui.content.title" pageHeader=title}}
|
||||||
|
{{unit "cdmf.unit.lib.service-invoker-utility"}}
|
||||||
|
{{unit "cdmf.unit.lib.handlebars"}}
|
||||||
|
{{unit "cdmf.unit.lib.rickshaw-graph"}}
|
||||||
|
|
||||||
|
{{#zone "breadcrumbs"}}
|
||||||
|
<li>
|
||||||
|
<a href="{{@app.context}}/">
|
||||||
|
<i class="icon fw fw-home"></i>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="{{@app.context}}/groups">
|
||||||
|
Groups
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="{{@app.context}}/devices?groupOwner={{groupOwner}}&groupName={{groupName}}">
|
||||||
|
{{groupName}}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<a href="#">
|
||||||
|
Analytics
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
{{/zone}}
|
||||||
|
|
||||||
|
{{#zone "content"}}
|
||||||
|
<div class="container container-bg white-bg">
|
||||||
|
<div class=" margin-top-double">
|
||||||
|
<div class="row padding-top-double padding-bottom-double margin-bottom-double">
|
||||||
|
<div class="col-lg-3 margin-top-double">
|
||||||
|
<h1 class="grey ">{{groupName}} Analytics</h1>
|
||||||
|
</div>
|
||||||
|
{{unit "cdmf.unit.analytics.date-range-picker" deviceTypes=deviceTypes}}
|
||||||
|
</div>
|
||||||
|
<hr>
|
||||||
|
<div class="clear"></div>
|
||||||
|
<div id="div-chart">
|
||||||
|
{{#each deviceTypes}}
|
||||||
|
{{unit deviceAnalyticsViewUnitName devices=devices}}
|
||||||
|
{{/each}}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{/zone}}
|
||||||
@ -0,0 +1,51 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function onRequest(context) {
|
||||||
|
var utility = require("/app/modules/utility.js").utility;
|
||||||
|
var groupModule = require("/app/modules/group.js").groupModule;
|
||||||
|
var groupName = context.uriParams.name;
|
||||||
|
var groupOwner = context.uriParams.owner;
|
||||||
|
var deviceTypes = [];
|
||||||
|
var devices = groupModule.getGroupDevices(groupName, groupOwner).data;
|
||||||
|
|
||||||
|
for (var i = 0; i < devices.length; i++) {
|
||||||
|
var hasDeviceType = false;
|
||||||
|
for (var j = 0; j < deviceTypes.length; j++) {
|
||||||
|
if (deviceTypes[j].type === devices[i].type) {
|
||||||
|
deviceTypes[j].devices.push(devices[i]);
|
||||||
|
hasDeviceType = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasDeviceType) {
|
||||||
|
var deviceType = {};
|
||||||
|
deviceType.type = devices[i].type;
|
||||||
|
deviceType.devices = [];
|
||||||
|
deviceType.devices.push(devices[i]);
|
||||||
|
deviceType.deviceAnalyticsViewUnitName = utility.getTenantedDeviceUnitName(deviceType.type, "analytics-view");
|
||||||
|
deviceTypes.push(deviceType);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"groupName": groupName,
|
||||||
|
"groupOwner": groupOwner,
|
||||||
|
"deviceTypes": deviceTypes
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"version": "1.0.0",
|
||||||
|
"uri": "/group/{owner}/{name}/analytics",
|
||||||
|
"layout": "cdmf.layout.default"
|
||||||
|
}
|
||||||
@ -0,0 +1,63 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#rangeSliderWrapper {
|
||||||
|
margin-top: 25px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chart {
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
#legend {
|
||||||
|
display: inline-block;
|
||||||
|
position: relative;
|
||||||
|
left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#legend_container {
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
bottom: 26px;
|
||||||
|
width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
#chart_container {
|
||||||
|
float: left;
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ast-container {
|
||||||
|
padding-bottom: 30px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.shrink {
|
||||||
|
margin-right: 20px;
|
||||||
|
margin-left: 20px;
|
||||||
|
}
|
||||||
|
.date-range{
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
}
|
||||||
|
|
||||||
|
#dateRangePickerContainer button.active{
|
||||||
|
background-color: #e6e6e6 !important;
|
||||||
|
}
|
||||||
@ -142,7 +142,7 @@ function loadGroups() {
|
|||||||
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-view fw-stack-1x"></i></span>' +
|
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-view fw-stack-1x"></i></span>' +
|
||||||
'<span class="hidden-xs hidden-on-grid-view">View Devices</span></a>';
|
'<span class="hidden-xs hidden-on-grid-view">View Devices</span></a>';
|
||||||
|
|
||||||
html += '<a href="analytics?groupName=' + row.name + '&groupOwner=' + row.owner + '" data-click-event="remove-form" class="btn padding-reduce-on-grid-view">' +
|
html += '<a href="group/' + row.owner + '/' + row.name + '/analytics" data-click-event="remove-form" class="btn padding-reduce-on-grid-view">' +
|
||||||
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-statistics fw-stack-1x"></i></span>' +
|
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-statistics fw-stack-1x"></i></span>' +
|
||||||
'<span class="hidden-xs hidden-on-grid-view">Analytics</span></a>';
|
'<span class="hidden-xs hidden-on-grid-view">Analytics</span></a>';
|
||||||
|
|
||||||
|
|||||||
@ -1,62 +0,0 @@
|
|||||||
{{#each groups}}
|
|
||||||
<tr data-type="selectable" data-group-name="{{name}}" data-group-owner="{{owner}}">
|
|
||||||
<td class="remove-padding icon-only content-fill">
|
|
||||||
<div class="thumbnail icon">
|
|
||||||
<img class="square-element text fw "
|
|
||||||
src="public/cdmf.page.groups/images/group-icon.png"/>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
<td class="fade-edge">
|
|
||||||
<h4>{{name}}</h4>
|
|
||||||
</td>
|
|
||||||
<td class="fade-edge remove-padding-top" data-search="{{owner}}"
|
|
||||||
data-display="{{owner}}"
|
|
||||||
data-grid-label="Owner">{{owner}}</td>
|
|
||||||
<td class="text-right content-fill text-left-on-grid-view no-wrap">
|
|
||||||
<a href="devices?groupName={{name}}&groupOwner={{owner}}"
|
|
||||||
data-click-event="remove-form" class="btn padding-reduce-on-grid-view">
|
|
||||||
<span class="fw-stack">
|
|
||||||
<i class="fw fw-ring fw-stack-2x"></i>
|
|
||||||
<i class="fw fw-view fw-stack-1x"></i>
|
|
||||||
</span>
|
|
||||||
<span class="hidden-xs hidden-on-grid-view">View Devices</span>
|
|
||||||
</a>
|
|
||||||
<a href="analytics?groupName={{name}}&groupOwner={{owner}}"
|
|
||||||
data-click-event="remove-form" class="btn padding-reduce-on-grid-view">
|
|
||||||
<span class="fw-stack">
|
|
||||||
<i class="fw fw-ring fw-stack-2x"></i>
|
|
||||||
<i class="fw fw-statistics fw-stack-1x"></i>
|
|
||||||
</span>
|
|
||||||
<span class="hidden-xs hidden-on-grid-view">Analytics</span>
|
|
||||||
</a>
|
|
||||||
<a href="#" data-click-event="remove-form"
|
|
||||||
class="btn padding-reduce-on-grid-view share-group-link"
|
|
||||||
data-group-name="{{name}}" data-group-owner="{{owner}}">
|
|
||||||
<span class="fw-stack">
|
|
||||||
<i class="fw fw-ring fw-stack-2x"></i>
|
|
||||||
<i class="fw fw-share fw-stack-1x"></i>
|
|
||||||
</span>
|
|
||||||
<span class="hidden-xs hidden-on-grid-view">Share</span>
|
|
||||||
</a>
|
|
||||||
<a href="#" data-click-event="remove-form"
|
|
||||||
class="btn padding-reduce-on-grid-view edit-group-link"
|
|
||||||
data-group-name="{{name}}" data-group-owner="{{owner}}"
|
|
||||||
data-group-description="{{description}}">
|
|
||||||
<span class="fw-stack">
|
|
||||||
<i class="fw fw-ring fw-stack-2x"></i>
|
|
||||||
<i class="fw fw-edit fw-stack-1x"></i>
|
|
||||||
</span>
|
|
||||||
<span class="hidden-xs hidden-on-grid-view">Edit</span>
|
|
||||||
</a>
|
|
||||||
<a href="#" data-click-event="remove-form"
|
|
||||||
class="btn padding-reduce-on-grid-view remove-group-link"
|
|
||||||
data-group-name="{{name}}" data-group-owner="{{owner}}">
|
|
||||||
<span class="fw-stack">
|
|
||||||
<i class="fw fw-ring fw-stack-2x"></i>
|
|
||||||
<i class="fw fw-delete fw-stack-1x"></i>
|
|
||||||
</span>
|
|
||||||
<span class="hidden-xs hidden-on-grid-view">Delete</span>
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{{/each}}
|
|
||||||
@ -0,0 +1,31 @@
|
|||||||
|
{{#zone "topCss"}}
|
||||||
|
{{css "css/daterangepicker.css"}}
|
||||||
|
{{/zone}}
|
||||||
|
<span id="device-type-details" data-devicetypes="{{deviceTypes}}"></span>
|
||||||
|
<div id="rangeSliderWrapper" class="pull-right col-lg-9">
|
||||||
|
<div id="dateRangePickerContainer">
|
||||||
|
<div class="btn-group" role="group">
|
||||||
|
<button id="hour-btn" type="button"
|
||||||
|
class="btn btn-default date-range">Hour
|
||||||
|
</button>
|
||||||
|
<button id="h12-btn" type="button"
|
||||||
|
class="btn btn-default date-range">12 Hours
|
||||||
|
</button>
|
||||||
|
<button id="h24-btn" type="button"
|
||||||
|
class="btn btn-default date-range">24 Hours
|
||||||
|
</button>
|
||||||
|
<button id="h48-btn" type="button"
|
||||||
|
class="btn btn-default date-range">48 Hours
|
||||||
|
</button>
|
||||||
|
<button id="date-range" type="button"
|
||||||
|
class="btn btn-default date-range last-child"
|
||||||
|
data-toggle="popup"
|
||||||
|
title="Click to set custom date range"></button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{{#zone "bottomJs"}}
|
||||||
|
{{js "js/moment.js"}}
|
||||||
|
{{js "js/jquery.daterangepicker.js"}}
|
||||||
|
{{js "js/date-picker.js"}}
|
||||||
|
{{/zone}}
|
||||||
@ -0,0 +1,32 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||||
|
*
|
||||||
|
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||||
|
* Version 2.0 (the "License"); you may not use this file except
|
||||||
|
* in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing,
|
||||||
|
* software distributed under the License is distributed on an
|
||||||
|
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||||
|
* KIND, either express or implied. See the License for the
|
||||||
|
* specific language governing permissions and limitations
|
||||||
|
* under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function onRequest(context) {
|
||||||
|
var deviceTypes = context.unit.params.deviceTypes;
|
||||||
|
var deviceType = context.uriParams.deviceType;
|
||||||
|
|
||||||
|
var deviceTypesList = [];
|
||||||
|
if (deviceTypes) {
|
||||||
|
for (var i = 0; i < deviceTypes.length; i++) {
|
||||||
|
deviceTypesList.push(deviceTypes[i].type);
|
||||||
|
}
|
||||||
|
} else if (deviceType) {
|
||||||
|
deviceTypesList.push(deviceType);
|
||||||
|
}
|
||||||
|
return {"deviceTypes": stringify(deviceTypesList)};
|
||||||
|
}
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
{
|
||||||
|
"version": "1.0.0"
|
||||||
|
}
|
||||||
@ -346,3 +346,16 @@ input.hour-range, input.minute-range {
|
|||||||
#dateRangePickerContainer {
|
#dateRangePickerContainer {
|
||||||
float: right;
|
float: right;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.date-range {
|
||||||
|
border: 1px solid #ccc;
|
||||||
|
}
|
||||||
|
|
||||||
|
#dateRangePickerContainer button.active {
|
||||||
|
background-color: #e6e6e6 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
#dateRangePickerContainer .btn-default:hover {
|
||||||
|
background-color: #b2b2b2;
|
||||||
|
border-color: #000000;
|
||||||
|
}
|
||||||
@ -28,9 +28,26 @@ var DateRange = convertDate(startDate) + " to " + convertDate(endDate);
|
|||||||
|
|
||||||
$(document).ready(function () {
|
$(document).ready(function () {
|
||||||
initDate();
|
initDate();
|
||||||
|
var configObject = {
|
||||||
|
startOfWeek: 'monday',
|
||||||
|
separator: ' to ',
|
||||||
|
format: 'YYYY-MM-DD HH:mm',
|
||||||
|
autoClose: false,
|
||||||
|
time: {
|
||||||
|
enabled: true
|
||||||
|
},
|
||||||
|
shortcuts: 'hide',
|
||||||
|
endDate: currentDay,
|
||||||
|
maxDays: 2,
|
||||||
|
getValue: function () {
|
||||||
|
return this.value;
|
||||||
|
},
|
||||||
|
setValue: function (s) {
|
||||||
|
this.value = s;
|
||||||
|
}
|
||||||
|
};
|
||||||
$('#date-range').html(DateRange);
|
$('#date-range').html(DateRange);
|
||||||
$('#date-range').dateRangePicker()
|
$('#date-range').dateRangePicker(configObject)
|
||||||
.bind('datepicker-apply', function (event, dateRange) {
|
.bind('datepicker-apply', function (event, dateRange) {
|
||||||
$(this).addClass('active');
|
$(this).addClass('active');
|
||||||
$(this).siblings().removeClass('active');
|
$(this).siblings().removeClass('active');
|
||||||
@ -83,8 +100,11 @@ function setDateTime(from, to) {
|
|||||||
from += tzOffset;
|
from += tzOffset;
|
||||||
to += tzOffset;
|
to += tzOffset;
|
||||||
|
|
||||||
// the relevant import units needs to implement this.
|
// Implement drawGraph_<device type name> method in your UI unit for analytics.
|
||||||
drawGraph(parseInt(from / 1000), parseInt(to / 1000));
|
var deviceTypes = $("#device-type-details").data("devicetypes");
|
||||||
|
for (var i = 0; i < deviceTypes.length; i++){
|
||||||
|
window["drawGraph_" + deviceTypes](parseInt(from / 1000), parseInt(to / 1000));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function convertDate(date) {
|
function convertDate(date) {
|
||||||
@ -1,20 +1,3 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
|
||||||
*
|
|
||||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
|
||||||
* Version 2.0 (the "License"); you may not use this file except
|
|
||||||
* in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing,
|
|
||||||
* software distributed under the License is distributed on an
|
|
||||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
||||||
* KIND, either express or implied. See the License for the
|
|
||||||
* specific language governing permissions and limitations
|
|
||||||
* under the License.
|
|
||||||
*/
|
|
||||||
(function ($) {
|
(function ($) {
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -1,21 +1,3 @@
|
|||||||
/*
|
|
||||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
|
||||||
*
|
|
||||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
|
||||||
* Version 2.0 (the "License"); you may not use this file except
|
|
||||||
* in compliance with the License.
|
|
||||||
* You may obtain a copy of the License at
|
|
||||||
*
|
|
||||||
* http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
*
|
|
||||||
* Unless required by applicable law or agreed to in writing,
|
|
||||||
* software distributed under the License is distributed on an
|
|
||||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
||||||
* KIND, either express or implied. See the License for the
|
|
||||||
* specific language governing permissions and limitations
|
|
||||||
* under the License.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// daterangepicker.js
|
// daterangepicker.js
|
||||||
// version : 0.0.5
|
// version : 0.0.5
|
||||||
// author : Chunlong Liu
|
// author : Chunlong Liu
|
||||||
File diff suppressed because it is too large
Load Diff
@ -232,6 +232,13 @@
|
|||||||
position: relative;
|
position: relative;
|
||||||
left: 40px;
|
left: 40px;
|
||||||
height: 30px;
|
height: 30px;
|
||||||
|
width: 97%;
|
||||||
|
top: 20px;
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chartWrapper {
|
||||||
|
padding-top: 50px;
|
||||||
}
|
}
|
||||||
|
|
||||||
/*detail*/
|
/*detail*/
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@ -0,0 +1,8 @@
|
|||||||
|
{{#zone "topCss"}}
|
||||||
|
{{css "css/graph.css"}}
|
||||||
|
{{/zone}}
|
||||||
|
|
||||||
|
{{#zone "bottomJs"}}
|
||||||
|
{{js "js/d3.min.js"}}
|
||||||
|
{{js "js/rickshaw.min.js"}}
|
||||||
|
{{/zone}}
|
||||||
@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"version": "1.0.0",
|
||||||
|
"index": 30
|
||||||
|
}
|
||||||
@ -28,6 +28,7 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
|||||||
private static final Log log = LogFactory.getLog(CertificateAuthenticator.class);
|
private static final Log log = LogFactory.getLog(CertificateAuthenticator.class);
|
||||||
private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth";
|
private static final String CERTIFICATE_AUTHENTICATOR = "CertificateAuth";
|
||||||
private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header";
|
private static final String MUTUAL_AUTH_HEADER = "mutual-auth-header";
|
||||||
|
private static final String PROXY_MUTUAL_AUTH_HEADER = "proxy-mutual-auth-header";
|
||||||
private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header";
|
private static final String CERTIFICATE_VERIFICATION_HEADER = "certificate-verification-header";
|
||||||
private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
|
private static final String CLIENT_CERTIFICATE_ATTRIBUTE = "javax.servlet.request.X509Certificate";
|
||||||
|
|
||||||
@ -38,8 +39,8 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public boolean canHandle(Request request) {
|
public boolean canHandle(Request request) {
|
||||||
if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null || request.getHeader(MUTUAL_AUTH_HEADER) !=
|
if (request.getHeader(CERTIFICATE_VERIFICATION_HEADER) != null || request.getHeader(MUTUAL_AUTH_HEADER) != null
|
||||||
null) {
|
|| request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
@ -56,35 +57,20 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
|||||||
|
|
||||||
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
|
String certVerificationHeader = request.getContext().findParameter(CERTIFICATE_VERIFICATION_HEADER);
|
||||||
try {
|
try {
|
||||||
|
// When there is a load balancer terminating mutual SSL, it should pass this header along and
|
||||||
if (request.getHeader(MUTUAL_AUTH_HEADER) != null) {
|
// as the value of this header, the client certificate subject dn should be passed.
|
||||||
|
if (request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) {
|
||||||
|
CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance().
|
||||||
|
getCertificateManagementService().verifySubjectDN(request.getHeader(PROXY_MUTUAL_AUTH_HEADER));
|
||||||
|
authenticationInfo = checkCertificateResponse(certificateResponse);
|
||||||
|
}
|
||||||
|
else if (request.getHeader(MUTUAL_AUTH_HEADER) != null) {
|
||||||
X509Certificate[] clientCertificate = (X509Certificate[]) request.
|
X509Certificate[] clientCertificate = (X509Certificate[]) request.
|
||||||
getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE);
|
getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE);
|
||||||
if (clientCertificate != null && clientCertificate[0] != null) {
|
if (clientCertificate != null && clientCertificate[0] != null) {
|
||||||
CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance().
|
CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance().
|
||||||
getCertificateManagementService().verifyPEMSignature(clientCertificate[0]);
|
getCertificateManagementService().verifyPEMSignature(clientCertificate[0]);
|
||||||
if (certificateResponse == null) {
|
authenticationInfo = checkCertificateResponse(certificateResponse);
|
||||||
authenticationInfo.setStatus(Status.FAILURE);
|
|
||||||
authenticationInfo.setMessage("Certificate sent doesn't match any certificate in the store." +
|
|
||||||
" Unauthorized access attempt.");
|
|
||||||
} else if (certificateResponse.getCommonName() != null && !certificateResponse.getCommonName().
|
|
||||||
isEmpty()) {
|
|
||||||
authenticationInfo.setTenantId(certificateResponse.getTenantId());
|
|
||||||
authenticationInfo.setStatus(Status.CONTINUE);
|
|
||||||
authenticationInfo.setUsername(certificateResponse.getCommonName());
|
|
||||||
try {
|
|
||||||
authenticationInfo.setTenantDomain(Utils.
|
|
||||||
getTenantDomain(
|
|
||||||
certificateResponse.getTenantId()));
|
|
||||||
} catch (AuthenticationException e) {
|
|
||||||
authenticationInfo.setStatus(Status.FAILURE);
|
|
||||||
authenticationInfo.setMessage("Could not identify tenant domain.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
authenticationInfo.setStatus(Status.FAILURE);
|
|
||||||
authenticationInfo.setMessage("A matching certificate is found, " +
|
|
||||||
"but the serial number is missing in the database.");
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
authenticationInfo.setStatus(Status.FAILURE);
|
authenticationInfo.setStatus(Status.FAILURE);
|
||||||
@ -133,6 +119,33 @@ public class CertificateAuthenticator implements WebappAuthenticator {
|
|||||||
return authenticationInfo;
|
return authenticationInfo;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private AuthenticationInfo checkCertificateResponse(CertificateResponse certificateResponse) {
|
||||||
|
AuthenticationInfo authenticationInfo = new AuthenticationInfo();
|
||||||
|
if (certificateResponse == null) {
|
||||||
|
authenticationInfo.setStatus(Status.FAILURE);
|
||||||
|
authenticationInfo.setMessage("Certificate sent doesn't match any certificate in the store." +
|
||||||
|
" Unauthorized access attempt.");
|
||||||
|
} else if (certificateResponse.getCommonName() != null && !certificateResponse.getCommonName().
|
||||||
|
isEmpty()) {
|
||||||
|
authenticationInfo.setTenantId(certificateResponse.getTenantId());
|
||||||
|
authenticationInfo.setStatus(Status.CONTINUE);
|
||||||
|
authenticationInfo.setUsername(certificateResponse.getCommonName());
|
||||||
|
try {
|
||||||
|
authenticationInfo.setTenantDomain(Utils.
|
||||||
|
getTenantDomain(
|
||||||
|
certificateResponse.getTenantId()));
|
||||||
|
} catch (AuthenticationException e) {
|
||||||
|
authenticationInfo.setStatus(Status.FAILURE);
|
||||||
|
authenticationInfo.setMessage("Could not identify tenant domain.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
authenticationInfo.setStatus(Status.FAILURE);
|
||||||
|
authenticationInfo.setMessage("A matching certificate is found, " +
|
||||||
|
"but the serial number is missing in the database.");
|
||||||
|
}
|
||||||
|
return authenticationInfo;
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String getName() {
|
public String getName() {
|
||||||
return CERTIFICATE_AUTHENTICATOR;
|
return CERTIFICATE_AUTHENTICATOR;
|
||||||
|
|||||||
@ -502,17 +502,20 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
|||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION,
|
ON UPDATE NO ACTION,
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
FOREIGN KEY (POLICY_ID)
|
||||||
REFERENCES DM_POLICY (ID , ID)
|
REFERENCES DM_POLICY (ID)
|
||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
-- END OF POLICY AND DEVICE GROUP MAPPING --
|
-- END OF POLICY AND DEVICE GROUP MAPPING --
|
||||||
|
|
||||||
|
-- DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
CREATE VIEW DEVICES_VIEW_1 AS
|
CREATE VIEW DEVICES_VIEW_1 AS
|
||||||
SELECT
|
SELECT
|
||||||
DEVICE_INFO.DEVICE_ID,
|
DEVICE_INFO.DEVICE_ID,
|
||||||
|
DEVICE_INFO.DEVICE_IDENTIFICATION,
|
||||||
DEVICE_INFO.PLATFORM,
|
DEVICE_INFO.PLATFORM,
|
||||||
DEVICE_INFO.OWNERSHIP,
|
DEVICE_INFO.OWNERSHIP,
|
||||||
DEVICE_INFO.CONNECTIVITY_STATUS,
|
DEVICE_INFO.CONNECTIVITY_STATUS,
|
||||||
@ -522,6 +525,7 @@ DEVICE_INFO.TENANT_ID
|
|||||||
FROM
|
FROM
|
||||||
(SELECT
|
(SELECT
|
||||||
DM_DEVICE.ID AS DEVICE_ID,
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
DM_ENROLMENT.OWNERSHIP,
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
@ -540,6 +544,7 @@ ORDER BY DEVICE_INFO.DEVICE_ID;
|
|||||||
CREATE VIEW DEVICES_VIEW_2 AS
|
CREATE VIEW DEVICES_VIEW_2 AS
|
||||||
SELECT
|
SELECT
|
||||||
DM_DEVICE.ID AS DEVICE_ID,
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||||
DM_DEVICE_DETAIL.VENDOR,
|
DM_DEVICE_DETAIL.VENDOR,
|
||||||
DM_DEVICE_DETAIL.OS_VERSION,
|
DM_DEVICE_DETAIL.OS_VERSION,
|
||||||
@ -560,3 +565,5 @@ DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
|||||||
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||||
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||||
ORDER BY TENANT_ID, DEVICE_ID;
|
ORDER BY TENANT_ID, DEVICE_ID;
|
||||||
|
|
||||||
|
-- END OF DASHBOARD RELATED VIEWS --
|
||||||
|
|||||||
@ -2,10 +2,21 @@ CREATE TABLE DM_DEVICE_TYPE (
|
|||||||
ID INTEGER IDENTITY NOT NULL,
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
NAME VARCHAR(300) DEFAULT NULL,
|
NAME VARCHAR(300) DEFAULT NULL,
|
||||||
PROVIDER_TENANT_ID INTEGER DEFAULT 0,
|
PROVIDER_TENANT_ID INTEGER DEFAULT 0,
|
||||||
SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE,
|
SHARED_WITH_ALL_TENANTS INTEGER NOT NULL DEFAULT 0,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE DM_GROUP (
|
||||||
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
|
GROUP_NAME VARCHAR(100) DEFAULT NULL,
|
||||||
|
DESCRIPTION VARCHAR(max) DEFAULT NULL,
|
||||||
|
DATE_OF_CREATE BIGINT DEFAULT NULL,
|
||||||
|
DATE_OF_LAST_UPDATE BIGINT DEFAULT NULL,
|
||||||
|
OWNER VARCHAR(45) DEFAULT NULL,
|
||||||
|
TENANT_ID INTEGER DEFAULT 0,
|
||||||
|
PRIMARY KEY (ID)
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_CERTIFICATE (
|
CREATE TABLE DM_DEVICE_CERTIFICATE (
|
||||||
ID INTEGER IDENTITY NOT NULL,
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
|
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
|
||||||
@ -18,7 +29,7 @@ CREATE TABLE DM_DEVICE (
|
|||||||
ID INTEGER identity NOT NULL,
|
ID INTEGER identity NOT NULL,
|
||||||
DESCRIPTION VARCHAR(max) DEFAULT NULL,
|
DESCRIPTION VARCHAR(max) DEFAULT NULL,
|
||||||
NAME VARCHAR(100) DEFAULT NULL,
|
NAME VARCHAR(100) DEFAULT NULL,
|
||||||
DEVICE_TYPE_ID INT DEFAULT NULL,
|
DEVICE_TYPE_ID INTEGER DEFAULT NULL,
|
||||||
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
|
DEVICE_IDENTIFICATION VARCHAR(300) DEFAULT NULL,
|
||||||
TENANT_ID INTEGER DEFAULT 0,
|
TENANT_ID INTEGER DEFAULT 0,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
@ -26,6 +37,18 @@ CREATE TABLE DM_DEVICE (
|
|||||||
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
REFERENCES DM_DEVICE_TYPE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE DM_DEVICE_GROUP_MAP (
|
||||||
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
|
DEVICE_ID INTEGER DEFAULT NULL,
|
||||||
|
GROUP_ID INTEGER DEFAULT NULL,
|
||||||
|
TENANT_ID INTEGER DEFAULT 0,
|
||||||
|
PRIMARY KEY (ID),
|
||||||
|
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_DEVICE2 FOREIGN KEY (DEVICE_ID)
|
||||||
|
REFERENCES DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION,
|
||||||
|
CONSTRAINT fk_DM_DEVICE_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
|
||||||
|
REFERENCES DM_GROUP (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||||
|
);
|
||||||
|
|
||||||
CREATE TABLE DM_OPERATION (
|
CREATE TABLE DM_OPERATION (
|
||||||
ID INTEGER IDENTITY NOT NULL,
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
TYPE VARCHAR(50) NOT NULL,
|
TYPE VARCHAR(50) NOT NULL,
|
||||||
@ -77,7 +100,7 @@ CREATE TABLE DM_ENROLMENT (
|
|||||||
STATUS VARCHAR(50) NULL,
|
STATUS VARCHAR(50) NULL,
|
||||||
DATE_OF_ENROLMENT DATETIME2(0) DEFAULT NULL,
|
DATE_OF_ENROLMENT DATETIME2(0) DEFAULT NULL,
|
||||||
DATE_OF_LAST_UPDATE DATETIME2(0) DEFAULT NULL,
|
DATE_OF_LAST_UPDATE DATETIME2(0) DEFAULT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
|
CONSTRAINT fk_dm_device_enrolment FOREIGN KEY (DEVICE_ID) REFERENCES
|
||||||
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
DM_DEVICE (ID) ON DELETE NO ACTION ON UPDATE NO ACTION
|
||||||
@ -113,10 +136,10 @@ CREATE TABLE DM_DEVICE_OPERATION_RESPONSE (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_PROFILE (
|
CREATE TABLE DM_PROFILE (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
PROFILE_NAME VARCHAR(45) NOT NULL ,
|
PROFILE_NAME VARCHAR(45) NOT NULL ,
|
||||||
TENANT_ID INT NOT NULL ,
|
TENANT_ID INTEGER NOT NULL ,
|
||||||
DEVICE_TYPE_ID INT NOT NULL ,
|
DEVICE_TYPE_ID INTEGER NOT NULL ,
|
||||||
CREATED_TIME DATETIME2(0) NOT NULL ,
|
CREATED_TIME DATETIME2(0) NOT NULL ,
|
||||||
UPDATED_TIME DATETIME2(0) NOT NULL ,
|
UPDATED_TIME DATETIME2(0) NOT NULL ,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
@ -132,16 +155,16 @@ CREATE TABLE DM_PROFILE (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY (
|
CREATE TABLE DM_POLICY (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
NAME VARCHAR(45) DEFAULT NULL ,
|
NAME VARCHAR(45) DEFAULT NULL ,
|
||||||
DESCRIPTION VARCHAR(1000) NULL,
|
DESCRIPTION VARCHAR(1000) NULL,
|
||||||
TENANT_ID INT NOT NULL ,
|
TENANT_ID INTEGER NOT NULL ,
|
||||||
PROFILE_ID INT NOT NULL ,
|
PROFILE_ID INTEGER NOT NULL ,
|
||||||
OWNERSHIP_TYPE VARCHAR(45) NULL,
|
OWNERSHIP_TYPE VARCHAR(45) NULL,
|
||||||
COMPLIANCE VARCHAR(100) NULL,
|
COMPLIANCE VARCHAR(100) NULL,
|
||||||
PRIORITY INT NOT NULL,
|
PRIORITY INTEGER NOT NULL,
|
||||||
ACTIVE INT NOT NULL,
|
ACTIVE INTEGER NOT NULL,
|
||||||
UPDATED INT NULL,
|
UPDATED INTEGER NULL,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
CONSTRAINT FK_DM_PROFILE_DM_POLICY
|
CONSTRAINT FK_DM_PROFILE_DM_POLICY
|
||||||
FOREIGN KEY (PROFILE_ID )
|
FOREIGN KEY (PROFILE_ID )
|
||||||
@ -154,11 +177,11 @@ CREATE TABLE DM_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_POLICY (
|
CREATE TABLE DM_DEVICE_POLICY (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
DEVICE_ID INT NOT NULL ,
|
DEVICE_ID INTEGER NOT NULL ,
|
||||||
ENROLMENT_ID INT NOT NULL,
|
ENROLMENT_ID INTEGER NOT NULL,
|
||||||
DEVICE VARBINARY(max) NOT NULL,
|
DEVICE VARBINARY(max) NOT NULL,
|
||||||
POLICY_ID INT NOT NULL ,
|
POLICY_ID INTEGER NOT NULL ,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
CONSTRAINT FK_POLICY_DEVICE_POLICY
|
CONSTRAINT FK_POLICY_DEVICE_POLICY
|
||||||
FOREIGN KEY (POLICY_ID )
|
FOREIGN KEY (POLICY_ID )
|
||||||
@ -176,9 +199,9 @@ CREATE TABLE DM_DEVICE_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_TYPE_POLICY (
|
CREATE TABLE DM_DEVICE_TYPE_POLICY (
|
||||||
ID INT NOT NULL ,
|
ID INTEGER NOT NULL ,
|
||||||
DEVICE_TYPE_ID INT NOT NULL ,
|
DEVICE_TYPE_ID INTEGER NOT NULL ,
|
||||||
POLICY_ID INT NOT NULL ,
|
POLICY_ID INTEGER NOT NULL ,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
CONSTRAINT FK_DEVICE_TYPE_POLICY
|
CONSTRAINT FK_DEVICE_TYPE_POLICY
|
||||||
FOREIGN KEY (POLICY_ID )
|
FOREIGN KEY (POLICY_ID )
|
||||||
@ -197,11 +220,11 @@ CREATE TABLE DM_DEVICE_TYPE_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_PROFILE_FEATURES (
|
CREATE TABLE DM_PROFILE_FEATURES (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
PROFILE_ID INT NOT NULL,
|
PROFILE_ID INTEGER NOT NULL,
|
||||||
FEATURE_CODE VARCHAR(100) NOT NULL,
|
FEATURE_CODE VARCHAR(100) NOT NULL,
|
||||||
DEVICE_TYPE_ID INT NOT NULL,
|
DEVICE_TYPE_ID INTEGER NOT NULL,
|
||||||
TENANT_ID INT NOT NULL ,
|
TENANT_ID INTEGER NOT NULL ,
|
||||||
CONTENT VARBINARY(max) NULL DEFAULT NULL,
|
CONTENT VARBINARY(max) NULL DEFAULT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES
|
CONSTRAINT FK_DM_PROFILE_DM_POLICY_FEATURES
|
||||||
@ -215,9 +238,9 @@ CREATE TABLE DM_PROFILE_FEATURES (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_ROLE_POLICY (
|
CREATE TABLE DM_ROLE_POLICY (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
ROLE_NAME VARCHAR(45) NOT NULL ,
|
ROLE_NAME VARCHAR(45) NOT NULL ,
|
||||||
POLICY_ID INT NOT NULL ,
|
POLICY_ID INTEGER NOT NULL ,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
CONSTRAINT FK_ROLE_POLICY_POLICY
|
CONSTRAINT FK_ROLE_POLICY_POLICY
|
||||||
FOREIGN KEY (POLICY_ID )
|
FOREIGN KEY (POLICY_ID )
|
||||||
@ -230,8 +253,8 @@ CREATE TABLE DM_ROLE_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_USER_POLICY (
|
CREATE TABLE DM_USER_POLICY (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
POLICY_ID INT NOT NULL ,
|
POLICY_ID INTEGER NOT NULL ,
|
||||||
USERNAME VARCHAR(45) NOT NULL ,
|
USERNAME VARCHAR(45) NOT NULL ,
|
||||||
PRIMARY KEY (ID) ,
|
PRIMARY KEY (ID) ,
|
||||||
CONSTRAINT DM_POLICY_USER_POLICY
|
CONSTRAINT DM_POLICY_USER_POLICY
|
||||||
@ -243,12 +266,12 @@ CREATE TABLE DM_USER_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_POLICY_APPLIED (
|
CREATE TABLE DM_DEVICE_POLICY_APPLIED (
|
||||||
ID INT NOT NULL IDENTITY ,
|
ID INTEGER NOT NULL IDENTITY ,
|
||||||
DEVICE_ID INT NOT NULL ,
|
DEVICE_ID INTEGER NOT NULL ,
|
||||||
ENROLMENT_ID INT NOT NULL,
|
ENROLMENT_ID INTEGER NOT NULL,
|
||||||
POLICY_ID INT NOT NULL ,
|
POLICY_ID INTEGER NOT NULL ,
|
||||||
POLICY_CONTENT VARBINARY(max) NULL ,
|
POLICY_CONTENT VARBINARY(max) NULL ,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
APPLIED SMALLINT NULL ,
|
APPLIED SMALLINT NULL ,
|
||||||
CREATED_TIME DATETIME2(0) NULL ,
|
CREATED_TIME DATETIME2(0) NULL ,
|
||||||
UPDATED_TIME DATETIME2(0) NULL ,
|
UPDATED_TIME DATETIME2(0) NULL ,
|
||||||
@ -264,8 +287,8 @@ CREATE TABLE DM_USER_POLICY (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_CRITERIA (
|
CREATE TABLE DM_CRITERIA (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
NAME VARCHAR(50) NULL,
|
NAME VARCHAR(50) NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
);
|
);
|
||||||
@ -273,9 +296,9 @@ CREATE TABLE DM_CRITERIA (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY_CRITERIA (
|
CREATE TABLE DM_POLICY_CRITERIA (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
CRITERIA_ID INT NOT NULL,
|
CRITERIA_ID INTEGER NOT NULL,
|
||||||
POLICY_ID INT NOT NULL,
|
POLICY_ID INTEGER NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_CRITERIA_POLICY_CRITERIA
|
CONSTRAINT FK_CRITERIA_POLICY_CRITERIA
|
||||||
FOREIGN KEY (CRITERIA_ID)
|
FOREIGN KEY (CRITERIA_ID)
|
||||||
@ -290,8 +313,8 @@ CREATE TABLE DM_POLICY_CRITERIA (
|
|||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY_CRITERIA_PROPERTIES (
|
CREATE TABLE DM_POLICY_CRITERIA_PROPERTIES (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
POLICY_CRITERION_ID INT NOT NULL,
|
POLICY_CRITERION_ID INTEGER NOT NULL,
|
||||||
PROP_KEY VARCHAR(45) NULL,
|
PROP_KEY VARCHAR(45) NULL,
|
||||||
PROP_VALUE VARCHAR(100) NULL,
|
PROP_VALUE VARCHAR(100) NULL,
|
||||||
CONTENT VARBINARY(max) NULL ,
|
CONTENT VARBINARY(max) NULL ,
|
||||||
@ -304,35 +327,35 @@ CREATE TABLE DM_POLICY_CRITERIA_PROPERTIES (
|
|||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY_COMPLIANCE_STATUS (
|
CREATE TABLE DM_POLICY_COMPLIANCE_STATUS (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
DEVICE_ID INT NOT NULL,
|
DEVICE_ID INTEGER NOT NULL,
|
||||||
ENROLMENT_ID INT NOT NULL,
|
ENROLMENT_ID INTEGER NOT NULL,
|
||||||
POLICY_ID INT NOT NULL,
|
POLICY_ID INTEGER NOT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
STATUS INT NULL,
|
STATUS INTEGER NULL,
|
||||||
LAST_SUCCESS_TIME DATETIME2(0) NULL,
|
LAST_SUCCESS_TIME DATETIME2(0) NULL,
|
||||||
LAST_REQUESTED_TIME DATETIME2(0) NULL,
|
LAST_REQUESTED_TIME DATETIME2(0) NULL,
|
||||||
LAST_FAILED_TIME DATETIME2(0) NULL,
|
LAST_FAILED_TIME DATETIME2(0) NULL,
|
||||||
ATTEMPTS INT NULL,
|
ATTEMPTS INTEGER NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY_CHANGE_MGT (
|
CREATE TABLE DM_POLICY_CHANGE_MGT (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
POLICY_ID INT NOT NULL,
|
POLICY_ID INTEGER NOT NULL,
|
||||||
DEVICE_TYPE_ID INT NOT NULL,
|
DEVICE_TYPE_ID INTEGER NOT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE DM_POLICY_COMPLIANCE_FEATURES (
|
CREATE TABLE DM_POLICY_COMPLIANCE_FEATURES (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
COMPLIANCE_STATUS_ID INT NOT NULL,
|
COMPLIANCE_STATUS_ID INTEGER NOT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
FEATURE_CODE VARCHAR(100) NOT NULL,
|
FEATURE_CODE VARCHAR(100) NOT NULL,
|
||||||
STATUS INT NULL,
|
STATUS INTEGER NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS
|
CONSTRAINT FK_COMPLIANCE_FEATURES_STATUS
|
||||||
FOREIGN KEY (COMPLIANCE_STATUS_ID)
|
FOREIGN KEY (COMPLIANCE_STATUS_ID)
|
||||||
@ -342,10 +365,10 @@ CREATE TABLE DM_POLICY_COMPLIANCE_FEATURES (
|
|||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_GROUP_POLICY (
|
CREATE TABLE DM_DEVICE_GROUP_POLICY (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
DEVICE_GROUP_ID INT NOT NULL,
|
DEVICE_GROUP_ID INTEGER NOT NULL,
|
||||||
POLICY_ID INT NOT NULL,
|
POLICY_ID INTEGER NOT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
|
||||||
FOREIGN KEY (DEVICE_GROUP_ID)
|
FOREIGN KEY (DEVICE_GROUP_ID)
|
||||||
@ -353,8 +376,8 @@ CREATE TABLE DM_DEVICE_GROUP_POLICY (
|
|||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION,
|
ON UPDATE NO ACTION,
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
FOREIGN KEY (POLICY_ID)
|
||||||
REFERENCES DM_POLICY (ID , ID)
|
REFERENCES DM_POLICY (ID)
|
||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
@ -370,7 +393,7 @@ CREATE TABLE DM_APPLICATION (
|
|||||||
LOCATION_URL VARCHAR(100) DEFAULT NULL,
|
LOCATION_URL VARCHAR(100) DEFAULT NULL,
|
||||||
IMAGE_URL VARCHAR(100) DEFAULT NULL,
|
IMAGE_URL VARCHAR(100) DEFAULT NULL,
|
||||||
APP_PROPERTIES VARBINARY(max) NULL,
|
APP_PROPERTIES VARBINARY(max) NULL,
|
||||||
MEMORY_USAGE INTEGER(10) NULL,
|
MEMORY_USAGE INTEGER NULL,
|
||||||
TENANT_ID INTEGER NOT NULL,
|
TENANT_ID INTEGER NOT NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
);
|
);
|
||||||
@ -405,12 +428,12 @@ CREATE TABLE DM_NOTIFICATION (
|
|||||||
);
|
);
|
||||||
-- NOTIFICATION TABLE END --
|
-- NOTIFICATION TABLE END --
|
||||||
|
|
||||||
|
IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_INFO' and type = 'u')
|
||||||
DROP TABLE IF EXISTS DM_DEVICE_INFO;
|
DROP TABLE DM_DEVICE_INFO;
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_INFO (
|
CREATE TABLE DM_DEVICE_INFO (
|
||||||
ID INTEGER IDENTITY NOT NULL,
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
DEVICE_ID INT NULL,
|
DEVICE_ID INTEGER NULL,
|
||||||
KEY_FIELD VARCHAR(45) NULL,
|
KEY_FIELD VARCHAR(45) NULL,
|
||||||
VALUE_FIELD VARCHAR(100) NULL,
|
VALUE_FIELD VARCHAR(100) NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
@ -423,11 +446,12 @@ CREATE TABLE DM_DEVICE_INFO (
|
|||||||
|
|
||||||
CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC);
|
CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC);
|
||||||
|
|
||||||
DROP TABLE IF EXISTS DM_DEVICE_LOCATION;
|
IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_LOCATION' and type = 'u')
|
||||||
|
DROP TABLE DM_DEVICE_LOCATION;
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_LOCATION (
|
CREATE TABLE DM_DEVICE_LOCATION (
|
||||||
ID INTEGER IDENTITY NOT NULL,
|
ID INTEGER IDENTITY NOT NULL,
|
||||||
DEVICE_ID INT NULL,
|
DEVICE_ID INTEGER NULL,
|
||||||
LATITUDE FLOAT NULL,
|
LATITUDE FLOAT NULL,
|
||||||
LONGITUDE FLOAT NULL,
|
LONGITUDE FLOAT NULL,
|
||||||
STREET1 VARCHAR(45) NULL,
|
STREET1 VARCHAR(45) NULL,
|
||||||
@ -447,11 +471,12 @@ CREATE TABLE DM_DEVICE_LOCATION (
|
|||||||
|
|
||||||
CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC);
|
CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC);
|
||||||
|
|
||||||
DROP TABLE IF EXISTS DM_DEVICE_DETAIL;
|
IF EXISTS (SELECT * FROM sys.objects WHERE name = 'DM_DEVICE_DETAIL' and type = 'u')
|
||||||
|
DROP TABLE DM_DEVICE_DETAIL;
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_DETAIL (
|
CREATE TABLE DM_DEVICE_DETAIL (
|
||||||
ID INT NOT NULL IDENTITY,
|
ID INTEGER NOT NULL IDENTITY,
|
||||||
DEVICE_ID INT NOT NULL,
|
DEVICE_ID INTEGER NOT NULL,
|
||||||
DEVICE_MODEL VARCHAR(45) NULL,
|
DEVICE_MODEL VARCHAR(45) NULL,
|
||||||
VENDOR VARCHAR(45) NULL,
|
VENDOR VARCHAR(45) NULL,
|
||||||
OS_VERSION VARCHAR(45) NULL,
|
OS_VERSION VARCHAR(45) NULL,
|
||||||
@ -465,7 +490,7 @@ CREATE TABLE DM_DEVICE_DETAIL (
|
|||||||
CPU_USAGE DECIMAL(5) NULL,
|
CPU_USAGE DECIMAL(5) NULL,
|
||||||
TOTAL_RAM_MEMORY DECIMAL(30,3) NULL,
|
TOTAL_RAM_MEMORY DECIMAL(30,3) NULL,
|
||||||
AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL,
|
AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL,
|
||||||
PLUGGED_IN INT NULL,
|
PLUGGED_IN INTEGER NULL,
|
||||||
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
||||||
@ -477,3 +502,67 @@ CREATE TABLE DM_DEVICE_DETAIL (
|
|||||||
|
|
||||||
CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC);
|
CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC);
|
||||||
|
|
||||||
|
-- DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_1 AS
|
||||||
|
SELECT TOP 100 PERCENT
|
||||||
|
DEVICE_INFO.DEVICE_ID,
|
||||||
|
DEVICE_INFO.DEVICE_IDENTIFICATION,
|
||||||
|
DEVICE_INFO.PLATFORM,
|
||||||
|
DEVICE_INFO.OWNERSHIP,
|
||||||
|
DEVICE_INFO.CONNECTIVITY_STATUS,
|
||||||
|
ISNULL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID,
|
||||||
|
ISNULL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS
|
||||||
|
IS_COMPLIANT,
|
||||||
|
DEVICE_INFO.TENANT_ID
|
||||||
|
FROM
|
||||||
|
(SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
|
||||||
|
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
|
||||||
|
LEFT JOIN
|
||||||
|
(SELECT
|
||||||
|
DEVICE_ID,
|
||||||
|
POLICY_ID,
|
||||||
|
STATUS AS IS_COMPLIANT
|
||||||
|
FROM
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
|
||||||
|
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
|
||||||
|
ORDER BY DEVICE_INFO.DEVICE_ID;
|
||||||
|
GO
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_2 AS
|
||||||
|
SELECT TOP 100 PERCENT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||||
|
DM_DEVICE_DETAIL.VENDOR,
|
||||||
|
DM_DEVICE_DETAIL.OS_VERSION,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.OWNER,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
|
||||||
|
DM_DEVICE_TYPE.NAME
|
||||||
|
AS PLATFORM,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
|
||||||
|
WHERE
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID =
|
||||||
|
DM_ENROLMENT.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
||||||
|
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||||
|
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||||
|
ORDER BY TENANT_ID, DEVICE_ID;
|
||||||
|
GO
|
||||||
|
|
||||||
|
-- END OF DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
|||||||
@ -423,8 +423,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
|||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION,
|
ON UPDATE NO ACTION,
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
FOREIGN KEY (POLICY_ID)
|
||||||
REFERENCES DM_POLICY (ID , ID)
|
REFERENCES DM_POLICY (ID)
|
||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
)ENGINE = InnoDB;
|
)ENGINE = InnoDB;
|
||||||
@ -493,8 +493,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
|||||||
)
|
)
|
||||||
ENGINE = InnoDB;
|
ENGINE = InnoDB;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
DROP TABLE IF EXISTS DM_DEVICE_DETAIL ;
|
DROP TABLE IF EXISTS DM_DEVICE_DETAIL ;
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
||||||
@ -524,3 +522,67 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
|||||||
ON UPDATE NO ACTION)
|
ON UPDATE NO ACTION)
|
||||||
ENGINE = InnoDB;
|
ENGINE = InnoDB;
|
||||||
|
|
||||||
|
-- DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
CREATE VIEW DEVICE_INFO_VIEW AS
|
||||||
|
SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
|
||||||
|
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID;
|
||||||
|
|
||||||
|
CREATE VIEW DEVICE_WITH_POLICY_INFO_VIEW AS
|
||||||
|
SELECT
|
||||||
|
DEVICE_ID,
|
||||||
|
POLICY_ID,
|
||||||
|
STATUS AS IS_COMPLIANT
|
||||||
|
FROM DM_POLICY_COMPLIANCE_STATUS;
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_1 AS
|
||||||
|
SELECT
|
||||||
|
DEVICE_INFO_VIEW.DEVICE_ID,
|
||||||
|
DEVICE_INFO_VIEW.DEVICE_IDENTIFICATION,
|
||||||
|
DEVICE_INFO_VIEW.PLATFORM,
|
||||||
|
DEVICE_INFO_VIEW.OWNERSHIP,
|
||||||
|
DEVICE_INFO_VIEW.CONNECTIVITY_STATUS,
|
||||||
|
IFNULL(DEVICE_WITH_POLICY_INFO_VIEW.POLICY_ID, -1) AS POLICY_ID,
|
||||||
|
IFNULL(DEVICE_WITH_POLICY_INFO_VIEW.IS_COMPLIANT, -1) AS IS_COMPLIANT,
|
||||||
|
DEVICE_INFO_VIEW.TENANT_ID
|
||||||
|
FROM
|
||||||
|
DEVICE_INFO_VIEW
|
||||||
|
LEFT JOIN
|
||||||
|
DEVICE_WITH_POLICY_INFO_VIEW
|
||||||
|
ON DEVICE_INFO_VIEW.DEVICE_ID = DEVICE_WITH_POLICY_INFO_VIEW.DEVICE_ID
|
||||||
|
ORDER BY DEVICE_INFO_VIEW.DEVICE_ID;
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_2 AS
|
||||||
|
SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||||
|
DM_DEVICE_DETAIL.VENDOR,
|
||||||
|
DM_DEVICE_DETAIL.OS_VERSION,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.OWNER,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
|
||||||
|
WHERE
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
||||||
|
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||||
|
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||||
|
ORDER BY TENANT_ID, DEVICE_ID;
|
||||||
|
|
||||||
|
-- END OF DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
|||||||
@ -2,7 +2,7 @@ CREATE TABLE DM_DEVICE_TYPE (
|
|||||||
ID NUMBER(10) NOT NULL,
|
ID NUMBER(10) NOT NULL,
|
||||||
NAME VARCHAR2(300) DEFAULT NULL,
|
NAME VARCHAR2(300) DEFAULT NULL,
|
||||||
PROVIDER_TENANT_ID INTEGER DEFAULT 0,
|
PROVIDER_TENANT_ID INTEGER DEFAULT 0,
|
||||||
SHARED_WITH_ALL_TENANTS BOOLEAN NOT NULL DEFAULT FALSE,
|
SHARED_WITH_ALL_TENANTS NUMBER(1) DEFAULT 0 NOT NULL,
|
||||||
CONSTRAINT PK_DM_DEVICE_TYPE PRIMARY KEY (ID)
|
CONSTRAINT PK_DM_DEVICE_TYPE PRIMARY KEY (ID)
|
||||||
)
|
)
|
||||||
/
|
/
|
||||||
@ -20,6 +20,31 @@ WHEN (NEW.ID IS NULL)
|
|||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
|
CREATE TABLE DM_GROUP (
|
||||||
|
ID NUMBER(10) NOT NULL,
|
||||||
|
DESCRIPTION CLOB DEFAULT NULL,
|
||||||
|
GROUP_NAME VARCHAR2(100) DEFAULT NULL,
|
||||||
|
DATE_OF_ENROLLMENT TIMESTAMP(0) DEFAULT NULL,
|
||||||
|
DATE_OF_LAST_UPDATE TIMESTAMP(0) DEFAULT NULL,
|
||||||
|
OWNER VARCHAR2(45) DEFAULT NULL,
|
||||||
|
TENANT_ID NUMBER(10) DEFAULT 0,
|
||||||
|
CONSTRAINT PK_DM_GROUP PRIMARY KEY (ID)
|
||||||
|
)
|
||||||
|
/
|
||||||
|
-- Generate ID using sequence and trigger
|
||||||
|
CREATE SEQUENCE DM_GROUP_seq START WITH 1 INCREMENT BY 1 NOCACHE
|
||||||
|
/
|
||||||
|
CREATE OR REPLACE TRIGGER DM_GROUP_seq_tr
|
||||||
|
BEFORE INSERT
|
||||||
|
ON DM_GROUP
|
||||||
|
REFERENCING NEW AS NEW
|
||||||
|
FOR EACH ROW
|
||||||
|
WHEN (NEW.ID IS NULL)
|
||||||
|
BEGIN
|
||||||
|
SELECT DM_GROUP_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
|
END;
|
||||||
|
/
|
||||||
|
|
||||||
CREATE TABLE DM_DEVICE_CERTIFICATE (
|
CREATE TABLE DM_DEVICE_CERTIFICATE (
|
||||||
ID NUMBER(10) NOT NULL,
|
ID NUMBER(10) NOT NULL,
|
||||||
SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL,
|
SERIAL_NUMBER VARCHAR2(500) DEFAULT NULL,
|
||||||
@ -65,6 +90,29 @@ WHEN (NEW.ID IS NULL)
|
|||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
|
CREATE TABLE DM_DEVICE_GROUP_MAP (
|
||||||
|
ID NUMBER(10) NOT NULL,
|
||||||
|
DEVICE_ID NUMBER(10) DEFAULT NULL,
|
||||||
|
GROUP_ID NUMBER(10) DEFAULT NULL,
|
||||||
|
TENANT_ID NUMBER(10) DEFAULT 0,
|
||||||
|
PRIMARY KEY (ID),
|
||||||
|
CONSTRAINT fk_DM_DEV_GROUP_MAP_DM_DEV2 FOREIGN KEY (DEVICE_ID)
|
||||||
|
REFERENCES DM_DEVICE (ID),
|
||||||
|
CONSTRAINT fk_DM_DEV_GROUP_MAP_DM_GROUP2 FOREIGN KEY (GROUP_ID)
|
||||||
|
REFERENCES DM_GROUP (ID)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Generate ID using sequence and trigger
|
||||||
|
CREATE SEQUENCE DM_DEVICE_GROUP_MAP_seq START WITH 1 INCREMENT BY 1;
|
||||||
|
|
||||||
|
CREATE OR REPLACE TRIGGER DM_DEVICE_GROUP_MAP_seq_tr
|
||||||
|
BEFORE INSERT ON DM_DEVICE_GROUP_MAP FOR EACH ROW
|
||||||
|
WHEN (NEW.ID IS NULL)
|
||||||
|
BEGIN
|
||||||
|
SELECT DM_DEVICE_GROUP_MAP_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
|
END;
|
||||||
|
/
|
||||||
|
|
||||||
CREATE TABLE DM_OPERATION (
|
CREATE TABLE DM_OPERATION (
|
||||||
ID NUMBER(10) NOT NULL,
|
ID NUMBER(10) NOT NULL,
|
||||||
TYPE VARCHAR2(50) NOT NULL,
|
TYPE VARCHAR2(50) NOT NULL,
|
||||||
@ -576,23 +624,23 @@ CREATE TABLE DM_DEVICE_GROUP_POLICY (
|
|||||||
TENANT_ID NUMBER(10) NOT NULL,
|
TENANT_ID NUMBER(10) NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_POLICY
|
||||||
FOREIGN KEY (DEVICE_GROUP_ID)
|
FOREIGN KEY (DEVICE_GROUP_ID)
|
||||||
REFERENCES DM_GROUP (ID)
|
REFERENCES DM_GROUP (ID)
|
||||||
,
|
,
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
FOREIGN KEY (POLICY_ID)
|
||||||
REFERENCES DM_POLICY (ID , ID)
|
REFERENCES DM_POLICY (ID)
|
||||||
) ;
|
) ;
|
||||||
|
|
||||||
-- Generate ID using sequence and trigger
|
-- Generate ID using sequence and trigger
|
||||||
CREATE SEQUENCE DM_DEVICE_GROUP_POLICY_seq START WITH 1 INCREMENT BY 1;
|
CREATE SEQUENCE DM_DEVICE_GROUP_POLICY_seq START WITH 1 INCREMENT BY 1;
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER DM_DEVICE_GROUP_POLICY_seq_tr
|
CREATE OR REPLACE TRIGGER DM_DEVICE_GROUP_POLICY_seq_tr
|
||||||
BEFORE INSERT ON DM_DEVICE_GROUP_POLICY FOR EACH ROW
|
BEFORE INSERT ON DM_DEVICE_GROUP_POLICY FOR EACH ROW
|
||||||
WHEN (NEW.ID IS NULL)
|
WHEN (NEW.ID IS NULL)
|
||||||
BEGIN
|
BEGIN
|
||||||
SELECT DM_DEVICE_GROUP_POLICY_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
SELECT DM_DEVICE_GROUP_POLICY_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
|
|
||||||
@ -690,9 +738,9 @@ WHEN (NEW.NOTIFICATION_ID IS NULL)
|
|||||||
-- Device Info and Search Table --
|
-- Device Info and Search Table --
|
||||||
|
|
||||||
BEGIN
|
BEGIN
|
||||||
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_INFO';
|
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_INFO';
|
||||||
EXCEPTION
|
EXCEPTION
|
||||||
WHEN OTHERS THEN NULL;
|
WHEN OTHERS THEN NULL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
@ -702,10 +750,10 @@ CREATE TABLE DM_DEVICE_INFO (
|
|||||||
KEY_FIELD VARCHAR2(45) NULL,
|
KEY_FIELD VARCHAR2(45) NULL,
|
||||||
VALUE_FIELD VARCHAR2(100) NULL,
|
VALUE_FIELD VARCHAR2(100) NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
,
|
,
|
||||||
CONSTRAINT DM_DEVICE_INFO_DEVICE
|
CONSTRAINT DM_DEVICE_INFO_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
)
|
)
|
||||||
;
|
;
|
||||||
|
|
||||||
@ -713,21 +761,17 @@ CREATE TABLE DM_DEVICE_INFO (
|
|||||||
CREATE SEQUENCE DM_DEVICE_INFO_seq START WITH 1 INCREMENT BY 1;
|
CREATE SEQUENCE DM_DEVICE_INFO_seq START WITH 1 INCREMENT BY 1;
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER DM_DEVICE_INFO_seq_tr
|
CREATE OR REPLACE TRIGGER DM_DEVICE_INFO_seq_tr
|
||||||
BEFORE INSERT ON DM_DEVICE_INFO FOR EACH ROW
|
BEFORE INSERT ON DM_DEVICE_INFO FOR EACH ROW
|
||||||
WHEN (NEW.ID IS NULL)
|
WHEN (NEW.ID IS NULL)
|
||||||
BEGIN
|
BEGIN
|
||||||
SELECT DM_DEVICE_INFO_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
SELECT DM_DEVICE_INFO_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
BEGIN
|
BEGIN
|
||||||
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_LOCATION';
|
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_LOCATION';
|
||||||
EXCEPTION
|
EXCEPTION
|
||||||
WHEN OTHERS THEN NULL;
|
WHEN OTHERS THEN NULL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
@ -744,10 +788,10 @@ CREATE TABLE DM_DEVICE_LOCATION (
|
|||||||
COUNTRY VARCHAR2(45) NULL,
|
COUNTRY VARCHAR2(45) NULL,
|
||||||
UPDATE_TIMESTAMP NUMBER(19) NOT NULL,
|
UPDATE_TIMESTAMP NUMBER(19) NOT NULL,
|
||||||
PRIMARY KEY (ID)
|
PRIMARY KEY (ID)
|
||||||
,
|
,
|
||||||
CONSTRAINT DM_DEVICE_LOCATION_DEVICE
|
CONSTRAINT DM_DEVICE_LOCATION_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
)
|
)
|
||||||
;
|
;
|
||||||
|
|
||||||
@ -755,21 +799,17 @@ CREATE TABLE DM_DEVICE_LOCATION (
|
|||||||
CREATE SEQUENCE DM_DEVICE_LOCATION_seq START WITH 1 INCREMENT BY 1;
|
CREATE SEQUENCE DM_DEVICE_LOCATION_seq START WITH 1 INCREMENT BY 1;
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER DM_DEVICE_LOCATION_seq_tr
|
CREATE OR REPLACE TRIGGER DM_DEVICE_LOCATION_seq_tr
|
||||||
BEFORE INSERT ON DM_DEVICE_LOCATION FOR EACH ROW
|
BEFORE INSERT ON DM_DEVICE_LOCATION FOR EACH ROW
|
||||||
WHEN (NEW.ID IS NULL)
|
WHEN (NEW.ID IS NULL)
|
||||||
BEGIN
|
BEGIN
|
||||||
SELECT DM_DEVICE_LOCATION_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
SELECT DM_DEVICE_LOCATION_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC);
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
BEGIN
|
BEGIN
|
||||||
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_DETAIL';
|
EXECUTE IMMEDIATE 'DROP TABLE DM_DEVICE_DETAIL';
|
||||||
EXCEPTION
|
EXCEPTION
|
||||||
WHEN OTHERS THEN NULL;
|
WHEN OTHERS THEN NULL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
@ -793,20 +833,76 @@ CREATE TABLE DM_DEVICE_DETAIL (
|
|||||||
UPDATE_TIMESTAMP NUMBER(19) NOT NULL,
|
UPDATE_TIMESTAMP NUMBER(19) NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
PRIMARY KEY (ID),
|
||||||
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
);
|
);
|
||||||
|
|
||||||
-- Generate ID using sequence and trigger
|
-- Generate ID using sequence and trigger
|
||||||
CREATE SEQUENCE DM_DEVICE_DETAIL_seq START WITH 1 INCREMENT BY 1;
|
CREATE SEQUENCE DM_DEVICE_DETAIL_seq START WITH 1 INCREMENT BY 1;
|
||||||
|
|
||||||
CREATE OR REPLACE TRIGGER DM_DEVICE_DETAIL_seq_tr
|
CREATE OR REPLACE TRIGGER DM_DEVICE_DETAIL_seq_tr
|
||||||
BEFORE INSERT ON DM_DEVICE_DETAIL FOR EACH ROW
|
BEFORE INSERT ON DM_DEVICE_DETAIL FOR EACH ROW
|
||||||
WHEN (NEW.ID IS NULL)
|
WHEN (NEW.ID IS NULL)
|
||||||
BEGIN
|
BEGIN
|
||||||
SELECT DM_DEVICE_DETAIL_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
SELECT DM_DEVICE_DETAIL_seq.NEXTVAL INTO :NEW.ID FROM DUAL;
|
||||||
END;
|
END;
|
||||||
/
|
/
|
||||||
|
|
||||||
CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC);
|
-- DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_1 AS
|
||||||
|
SELECT
|
||||||
|
DEVICE_INFO.DEVICE_ID,
|
||||||
|
DEVICE_INFO.DEVICE_IDENTIFICATION,
|
||||||
|
DEVICE_INFO.PLATFORM,
|
||||||
|
DEVICE_INFO.OWNERSHIP,
|
||||||
|
DEVICE_INFO.CONNECTIVITY_STATUS,
|
||||||
|
NVL(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID,
|
||||||
|
NVL(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT,
|
||||||
|
DEVICE_INFO.TENANT_ID
|
||||||
|
FROM
|
||||||
|
(SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
|
||||||
|
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
|
||||||
|
LEFT JOIN
|
||||||
|
(SELECT
|
||||||
|
DEVICE_ID,
|
||||||
|
POLICY_ID,
|
||||||
|
STATUS AS IS_COMPLIANT
|
||||||
|
FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
|
||||||
|
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
|
||||||
|
ORDER BY DEVICE_INFO.DEVICE_ID;
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_2 AS
|
||||||
|
SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||||
|
DM_DEVICE_DETAIL.VENDOR,
|
||||||
|
DM_DEVICE_DETAIL.OS_VERSION,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.OWNER,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
|
||||||
|
WHERE
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
||||||
|
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||||
|
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||||
|
ORDER BY TENANT_ID, DEVICE_ID;
|
||||||
|
|
||||||
|
-- END OF DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
|||||||
@ -8,8 +8,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_TYPE (
|
|||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_CERTIFICATE (
|
||||||
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
|
SERIAL_NUMBER VARCHAR(500) DEFAULT NULL,
|
||||||
CERTIFICATE BYTEA DEFAULT NULL
|
CERTIFICATE BYTEA DEFAULT NULL,
|
||||||
TENANT_ID INTEGER DEFAULT 0,
|
TENANT_ID INTEGER DEFAULT 0
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE (
|
||||||
@ -292,10 +292,9 @@ CREATE TABLE IF NOT EXISTS DM_POLICY_COMPLIANCE_FEATURES (
|
|||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE SEQUENCE DM_DEVICE_GROUP_POLICY_seq;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
||||||
ID INT NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_GROUP_POLICY_seq'),
|
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
DEVICE_GROUP_ID INT NOT NULL,
|
DEVICE_GROUP_ID INT NOT NULL,
|
||||||
POLICY_ID INT NOT NULL,
|
POLICY_ID INT NOT NULL,
|
||||||
TENANT_ID INT NOT NULL,
|
TENANT_ID INT NOT NULL,
|
||||||
@ -306,8 +305,8 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_GROUP_POLICY (
|
|||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION,
|
ON UPDATE NO ACTION,
|
||||||
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
CONSTRAINT FK_DM_DEVICE_GROUP_DM_POLICY
|
||||||
FOREIGN KEY (POLICY_ID , DEVICE_GROUP_ID)
|
FOREIGN KEY (POLICY_ID)
|
||||||
REFERENCES DM_POLICY (ID , ID)
|
REFERENCES DM_POLICY (ID)
|
||||||
ON DELETE NO ACTION
|
ON DELETE NO ACTION
|
||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
@ -373,11 +372,10 @@ CREATE TABLE IF NOT EXISTS DM_NOTIFICATION (
|
|||||||
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
|
||||||
ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_INFO_seq') NOT NULL,
|
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
DEVICE_ID INT NULL,
|
DEVICE_ID INT NULL,
|
||||||
KEY_FIELD VARCHAR(45) NULL,
|
KEY_FIELD VARCHAR(45) NULL,
|
||||||
VALUE_FIELD VARCHAR(100) NULL,
|
VALUE_FIELD VARCHAR(100) NULL,
|
||||||
PRIMARY KEY (ID) ,
|
|
||||||
CONSTRAINT DM_DEVICE_INFO_DEVICE
|
CONSTRAINT DM_DEVICE_INFO_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
@ -385,11 +383,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_INFO (
|
|||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX DM_DEVICE_INFO_DEVICE_idx ON DM_DEVICE_INFO (DEVICE_ID ASC);
|
|
||||||
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
||||||
ID INTEGER DEFAULT NEXTVAL ('DM_DEVICE_LOCATION_seq') NOT NULL,
|
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
DEVICE_ID INT NULL,
|
DEVICE_ID INT NULL,
|
||||||
LATITUDE DOUBLE PRECISION NULL,
|
LATITUDE DOUBLE PRECISION NULL,
|
||||||
LONGITUDE DOUBLE PRECISION NULL,
|
LONGITUDE DOUBLE PRECISION NULL,
|
||||||
@ -400,7 +396,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
|||||||
STATE VARCHAR(45) NULL,
|
STATE VARCHAR(45) NULL,
|
||||||
COUNTRY VARCHAR(45) NULL,
|
COUNTRY VARCHAR(45) NULL,
|
||||||
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
||||||
PRIMARY KEY (ID) ,
|
|
||||||
CONSTRAINT DM_DEVICE_LOCATION_DEVICE
|
CONSTRAINT DM_DEVICE_LOCATION_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
@ -408,13 +403,9 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_LOCATION (
|
|||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX DM_DEVICE_LOCATION_DEVICE_idx ON DM_DEVICE_LOCATION (DEVICE_ID ASC);
|
|
||||||
|
|
||||||
|
|
||||||
CREATE SEQUENCE DM_DEVICE_DETAIL_seq;
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
||||||
ID INT NOT NULL DEFAULT NEXTVAL ('DM_DEVICE_DETAIL_seq'),
|
ID BIGSERIAL NOT NULL PRIMARY KEY,
|
||||||
DEVICE_ID INT NOT NULL,
|
DEVICE_ID INT NOT NULL,
|
||||||
DEVICE_MODEL VARCHAR(45) NULL,
|
DEVICE_MODEL VARCHAR(45) NULL,
|
||||||
VENDOR VARCHAR(45) NULL,
|
VENDOR VARCHAR(45) NULL,
|
||||||
@ -431,7 +422,6 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
|||||||
AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL,
|
AVAILABLE_RAM_MEMORY DECIMAL(30,3) NULL,
|
||||||
PLUGGED_IN INT NULL,
|
PLUGGED_IN INT NULL,
|
||||||
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
UPDATE_TIMESTAMP BIGINT NOT NULL,
|
||||||
PRIMARY KEY (ID),
|
|
||||||
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
CONSTRAINT FK_DM_DEVICE_DETAILS_DEVICE
|
||||||
FOREIGN KEY (DEVICE_ID)
|
FOREIGN KEY (DEVICE_ID)
|
||||||
REFERENCES DM_DEVICE (ID)
|
REFERENCES DM_DEVICE (ID)
|
||||||
@ -439,5 +429,61 @@ CREATE TABLE IF NOT EXISTS DM_DEVICE_DETAIL (
|
|||||||
ON UPDATE NO ACTION
|
ON UPDATE NO ACTION
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX FK_DM_DEVICE_DETAILS_DEVICE_idx ON DM_DEVICE_DETAIL (DEVICE_ID ASC);
|
-- DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_1 AS
|
||||||
|
SELECT
|
||||||
|
DEVICE_INFO.DEVICE_ID,
|
||||||
|
DEVICE_INFO.DEVICE_IDENTIFICATION,
|
||||||
|
DEVICE_INFO.PLATFORM,
|
||||||
|
DEVICE_INFO.OWNERSHIP,
|
||||||
|
DEVICE_INFO.CONNECTIVITY_STATUS,
|
||||||
|
COALESCE(DEVICE_WITH_POLICY_INFO.POLICY_ID, -1) AS POLICY_ID,
|
||||||
|
COALESCE(DEVICE_WITH_POLICY_INFO.IS_COMPLIANT, -1) AS IS_COMPLIANT,
|
||||||
|
DEVICE_INFO.TENANT_ID
|
||||||
|
FROM
|
||||||
|
(SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM DM_DEVICE, DM_DEVICE_TYPE, DM_ENROLMENT
|
||||||
|
WHERE DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND DM_DEVICE.ID = DM_ENROLMENT.DEVICE_ID) DEVICE_INFO
|
||||||
|
LEFT JOIN
|
||||||
|
(SELECT
|
||||||
|
DEVICE_ID,
|
||||||
|
POLICY_ID,
|
||||||
|
STATUS AS IS_COMPLIANT
|
||||||
|
FROM DM_POLICY_COMPLIANCE_STATUS) DEVICE_WITH_POLICY_INFO
|
||||||
|
ON DEVICE_INFO.DEVICE_ID = DEVICE_WITH_POLICY_INFO.DEVICE_ID
|
||||||
|
ORDER BY DEVICE_INFO.DEVICE_ID;
|
||||||
|
|
||||||
|
CREATE VIEW DEVICES_VIEW_2 AS
|
||||||
|
SELECT
|
||||||
|
DM_DEVICE.ID AS DEVICE_ID,
|
||||||
|
DM_DEVICE.DEVICE_IDENTIFICATION,
|
||||||
|
DM_DEVICE_DETAIL.DEVICE_MODEL,
|
||||||
|
DM_DEVICE_DETAIL.VENDOR,
|
||||||
|
DM_DEVICE_DETAIL.OS_VERSION,
|
||||||
|
DM_ENROLMENT.OWNERSHIP,
|
||||||
|
DM_ENROLMENT.OWNER,
|
||||||
|
DM_ENROLMENT.STATUS AS CONNECTIVITY_STATUS,
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.POLICY_ID,
|
||||||
|
DM_DEVICE_TYPE.NAME AS PLATFORM,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.FEATURE_CODE,
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.STATUS AS IS_COMPLAINT,
|
||||||
|
DM_DEVICE.TENANT_ID
|
||||||
|
FROM
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES, DM_POLICY_COMPLIANCE_STATUS, DM_ENROLMENT, DM_DEVICE, DM_DEVICE_TYPE, DM_DEVICE_DETAIL
|
||||||
|
WHERE
|
||||||
|
DM_POLICY_COMPLIANCE_FEATURES.COMPLIANCE_STATUS_ID = DM_POLICY_COMPLIANCE_STATUS.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.ENROLMENT_ID = DM_ENROLMENT.ID AND
|
||||||
|
DM_POLICY_COMPLIANCE_STATUS.DEVICE_ID = DM_DEVICE.ID AND
|
||||||
|
DM_DEVICE.DEVICE_TYPE_ID = DM_DEVICE_TYPE.ID AND
|
||||||
|
DM_DEVICE.ID = DM_DEVICE_DETAIL.DEVICE_ID
|
||||||
|
ORDER BY TENANT_ID, DEVICE_ID;
|
||||||
|
|
||||||
|
-- END OF DASHBOARD RELATED VIEWS --
|
||||||
|
|
||||||
|
|||||||
12
pom.xml
12
pom.xml
@ -1451,6 +1451,11 @@
|
|||||||
<scope>provided</scope>
|
<scope>provided</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.swagger</groupId>
|
||||||
|
<artifactId>swagger-annotations</artifactId>
|
||||||
|
<version>${swagger.version}</version>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
|
|
||||||
@ -1496,6 +1501,11 @@
|
|||||||
<target>1.7</target>
|
<target>1.7</target>
|
||||||
</configuration>
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-war-plugin</artifactId>
|
||||||
|
<version>2.2</version>
|
||||||
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-release-plugin</artifactId>
|
<artifactId>maven-release-plugin</artifactId>
|
||||||
@ -1811,6 +1821,8 @@
|
|||||||
<!-- Nimbus Jose-->
|
<!-- Nimbus Jose-->
|
||||||
<nimbus.orbit.version>2.26.1.wso2v3</nimbus.orbit.version>
|
<nimbus.orbit.version>2.26.1.wso2v3</nimbus.orbit.version>
|
||||||
<nimbus.orbit.version.range>[2.26.1, 3.0.0)</nimbus.orbit.version.range>
|
<nimbus.orbit.version.range>[2.26.1, 3.0.0)</nimbus.orbit.version.range>
|
||||||
|
|
||||||
|
<swagger.version>1.5.8</swagger.version>
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user