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
This commit is contained in:
commit
db5dafa9e9
@ -58,10 +58,14 @@
|
||||
<Bundle-Description>Device Management Dashboard Analytics Bundle</Bundle-Description>
|
||||
<Private-Package>
|
||||
org.wso2.carbon.device.mgt.analytics.dashboard.dao,
|
||||
org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl,
|
||||
org.wso2.carbon.device.mgt.analytics.dashboard.impl,
|
||||
org.wso2.carbon.device.mgt.analytics.dashboard.internal
|
||||
</Private-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.bean
|
||||
</Export-Package>
|
||||
<Import-Package>
|
||||
org.osgi.framework,
|
||||
|
||||
@ -18,11 +18,12 @@
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
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 java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* To be updated...
|
||||
@ -30,61 +31,56 @@ import java.util.Map;
|
||||
public interface GadgetDataService {
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getTotalDeviceCount() throws GadgetDataServiceException;
|
||||
DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getActiveDeviceCount() throws GadgetDataServiceException;
|
||||
DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getInactiveDeviceCount() throws GadgetDataServiceException;
|
||||
DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getRemovedDeviceCount() throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getNonCompliantDeviceCount() throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getUnmonitoredDeviceCount() throws GadgetDataServiceException;
|
||||
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
|
||||
throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
||||
PaginationRequest paginationRequest) throws GadgetDataServiceException;
|
||||
PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceException;
|
||||
FilterSet filterSet, int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException;
|
||||
List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
}
|
||||
|
||||
@ -0,0 +1,638 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
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.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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class AbstractGadgetDataServiceDAO implements GadgetDataServiceDAO {
|
||||
|
||||
@Override
|
||||
public DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException {
|
||||
int totalDeviceCount;
|
||||
try {
|
||||
totalDeviceCount = this.getFilteredDeviceCount(null);
|
||||
} catch (InvalidParameterValueException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
|
||||
DeviceCountByGroupEntry deviceCountByGroupEntry = new DeviceCountByGroupEntry();
|
||||
deviceCountByGroupEntry.setGroup("total");
|
||||
deviceCountByGroupEntry.setDisplayNameForGroup("Total");
|
||||
deviceCountByGroupEntry.setDeviceCount(totalDeviceCount);
|
||||
|
||||
return deviceCountByGroupEntry;
|
||||
}
|
||||
|
||||
@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;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
int filteredDeviceCount = 0;
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
|
||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||
}
|
||||
|
||||
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
int filteredDeviceCount = 0;
|
||||
try {
|
||||
con = this.getConnection();
|
||||
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
|
||||
// [1] appending filter columns
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
|
||||
DeviceCountByGroupEntry deviceCountByGroupEntry = new DeviceCountByGroupEntry();
|
||||
deviceCountByGroupEntry.setGroup("feature-non-compliant-and-filtered");
|
||||
deviceCountByGroupEntry.setDisplayNameForGroup("Feature-non-compliant-and-filtered");
|
||||
deviceCountByGroupEntry.setDeviceCount(filteredDeviceCount);
|
||||
|
||||
return deviceCountByGroupEntry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
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 {
|
||||
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 PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
|
||||
advancedSqlFiltering + "GROUP BY PLATFORM";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
DeviceCountByGroupEntry filteredDeviceCountByPlatform;
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountByPlatform = new DeviceCountByGroupEntry();
|
||||
filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM"));
|
||||
filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase());
|
||||
filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||
filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry>
|
||||
getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
|
||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||
}
|
||||
|
||||
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 {
|
||||
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 PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
|
||||
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
DeviceCountByGroupEntry filteredDeviceCountByPlatform;
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountByPlatform = new DeviceCountByGroupEntry();
|
||||
filteredDeviceCountByPlatform.setGroup(rs.getString("PLATFORM"));
|
||||
filteredDeviceCountByPlatform.setDisplayNameForGroup(rs.getString("PLATFORM").toUpperCase());
|
||||
filteredDeviceCountByPlatform.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||
filteredDeviceCountsByPlatforms.add(filteredDeviceCountByPlatform);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(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> filteredDeviceCountsByOwnershipTypes = new ArrayList<>();
|
||||
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 OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
|
||||
advancedSqlFiltering + "GROUP BY OWNERSHIP";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
DeviceCountByGroupEntry filteredDeviceCountByOwnershipType;
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountByOwnershipType = new DeviceCountByGroupEntry();
|
||||
filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP"));
|
||||
filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP"));
|
||||
filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||
filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry>
|
||||
getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
|
||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||
}
|
||||
|
||||
Map<String, Object> filters = this.extractDatabaseFiltersFromBean(filterSet);
|
||||
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
List<DeviceCountByGroupEntry> filteredDeviceCountsByOwnershipTypes = new ArrayList<>();
|
||||
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 OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
|
||||
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY OWNERSHIP";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
DeviceCountByGroupEntry filteredDeviceCountByOwnershipType;
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountByOwnershipType = new DeviceCountByGroupEntry();
|
||||
filteredDeviceCountByOwnershipType.setGroup(rs.getString("OWNERSHIP"));
|
||||
filteredDeviceCountByOwnershipType.setDisplayNameForGroup(rs.getString("OWNERSHIP"));
|
||||
filteredDeviceCountByOwnershipType.setDeviceCount(rs.getInt("DEVICE_COUNT"));
|
||||
filteredDeviceCountsByOwnershipTypes.add(filteredDeviceCountByOwnershipType);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DetailedDeviceEntry> getDevicesWithDetails(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<DetailedDeviceEntry> filteredDevicesWithDetails = new ArrayList<>();
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql;
|
||||
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||
"DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns, if exist
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDevicesWithDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
|
||||
if (nonCompliantFeatureCode == null || "".equals(nonCompliantFeatureCode)) {
|
||||
throw new InvalidParameterValueException("Non-compliant feature code should not be either null or empty.");
|
||||
}
|
||||
|
||||
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<>();
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql;
|
||||
sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " +
|
||||
"DEVICES_VIEW_2 WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns, if exist
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDevicesWithDetails;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@ -18,83 +18,56 @@
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
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 java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface GadgetDataServiceDAO {
|
||||
|
||||
/**
|
||||
* Method to get total filtered device count from a particular tenant.
|
||||
*
|
||||
* @return Total filtered device count.
|
||||
*/
|
||||
int getTotalDeviceCount() throws GadgetDataServiceDAOException;
|
||||
DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
DeviceCountByGroupEntry getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, 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 GadgetDataServiceDAOException;
|
||||
DeviceCountByGroupEntry getTotalDeviceCount() throws SQLException;
|
||||
|
||||
/**
|
||||
* Method to get inactive device count from a particular tenant.
|
||||
*
|
||||
* @return inactive device count.
|
||||
*/
|
||||
int getInactiveDeviceCount() throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException;
|
||||
|
||||
/**
|
||||
* Method to get removed device count from a particular tenant.
|
||||
*
|
||||
* @return removed device count.
|
||||
*/
|
||||
int getRemovedDeviceCount() throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException;
|
||||
|
||||
/**
|
||||
* Method to get non-compliant device count from a particular tenant.
|
||||
*
|
||||
* @return Non-compliant device count.
|
||||
*/
|
||||
int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException;
|
||||
PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
/**
|
||||
* Method to get unmonitored device count from a particular tenant.
|
||||
*
|
||||
* @return Unmonitored device count.
|
||||
*/
|
||||
int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
|
||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
|
||||
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
|
||||
throws GadgetDataServiceDAOException;
|
||||
|
||||
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
|
||||
PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
||||
PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
|
||||
PaginationResult getDevicesWithDetails(FilterSet filterSet, int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
|
||||
FilterSet filterSet, int startIndex, int resultCount) throws InvalidParameterValueException, SQLException;
|
||||
|
||||
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException;
|
||||
|
||||
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException;
|
||||
List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
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(); }
|
||||
|
||||
}
|
||||
@ -1,82 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||
|
||||
/**
|
||||
* Custom exception class for GadgetDataServiceDAO layer.
|
||||
*/
|
||||
public class GadgetDataServiceDAOException extends Exception {
|
||||
|
||||
private String errorMessage;
|
||||
private static final long serialVersionUID = 2021891706072918864L;
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specific error message and nested exception.
|
||||
*
|
||||
* @param errorMessage specific error message.
|
||||
* @param nestedException Nested exception.
|
||||
*/
|
||||
public GadgetDataServiceDAOException(String errorMessage, Exception nestedException) {
|
||||
super(errorMessage, nestedException);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specific error message and cause.
|
||||
*
|
||||
* @param errorMessage Specific error message.
|
||||
* @param cause Cause of this exception.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceDAOException(String errorMessage, Throwable cause) {
|
||||
super(errorMessage, cause);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specific error message.
|
||||
*
|
||||
* @param errorMessage Specific error message.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceDAOException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new exception with the specific error message and cause.
|
||||
*
|
||||
* @param cause Cause of this exception.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceDAOException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
}
|
||||
@ -20,7 +20,13 @@ package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
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.UnsupportedDatabaseEngineException;
|
||||
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.dao.util.DeviceManagementDAOUtil;
|
||||
@ -40,7 +46,23 @@ public class GadgetDataServiceDAOFactory {
|
||||
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
|
||||
|
||||
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) {
|
||||
|
||||
@ -1,680 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao;
|
||||
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
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.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
|
||||
|
||||
@Override
|
||||
public int getTotalDeviceCount() throws GadgetDataServiceDAOException {
|
||||
return this.getDeviceCount(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getActiveDeviceCount() throws GadgetDataServiceDAOException {
|
||||
Map<String, Object> filters = new HashMap<>();
|
||||
filters.put("CONNECTIVITY_STATUS", "ACTIVE");
|
||||
return this.getDeviceCount(filters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getInactiveDeviceCount() throws GadgetDataServiceDAOException {
|
||||
Map<String, Object> filters = new HashMap<>();
|
||||
filters.put("CONNECTIVITY_STATUS", "INACTIVE");
|
||||
return this.getDeviceCount(filters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRemovedDeviceCount() throws GadgetDataServiceDAOException {
|
||||
Map<String, Object> filters = new HashMap<>();
|
||||
filters.put("CONNECTIVITY_STATUS", "REMOVED");
|
||||
return this.getDeviceCount(filters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException {
|
||||
Map<String, Object> filters = new HashMap<>();
|
||||
filters.put("IS_COMPLIANT", 0);
|
||||
return this.getDeviceCount(filters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException {
|
||||
Map<String, Object> filters = new HashMap<>();
|
||||
filters.put("POLICY_ID", -1);
|
||||
return this.getDeviceCount(filters);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
|
||||
throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
List<Map<String, Object>> 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, paginationRequest.getStartIndex());
|
||||
stmt.setInt(3, paginationRequest.getRowCount());
|
||||
|
||||
// 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");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting non compliant device counts by features.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
PaginationResult paginationResult = new PaginationResult();
|
||||
paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures);
|
||||
paginationResult.setRecordsTotal(totalRecordsCount);
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
int filteredDeviceCount = 0;
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered device count.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCount;
|
||||
}
|
||||
|
||||
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
int filteredDeviceCount = 0;
|
||||
try {
|
||||
con = this.getConnection();
|
||||
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
|
||||
// [1] appending filter columns
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCount = rs.getInt("DEVICE_COUNT");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered device count, " +
|
||||
"non compliant by a particular feature.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCount;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
|
||||
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 PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
|
||||
advancedSqlFiltering + "GROUP BY PLATFORM";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of device counts by platforms.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
Map<String, Integer> filteredDeviceCountsByPlatforms = new HashMap<>();
|
||||
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 PLATFORM, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
|
||||
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY PLATFORM";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountsByPlatforms.put(rs.getString("PLATFORM"), rs.getInt("DEVICE_COUNT"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a set of feature non-compliant device counts by platforms.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
|
||||
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 OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_1 WHERE TENANT_ID = ? " +
|
||||
advancedSqlFiltering + "GROUP BY OWNERSHIP";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of device counts by ownership types.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
Map<String, Integer> filteredDeviceCountsByOwnershipTypes = new HashMap<>();
|
||||
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 OWNERSHIP, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM DEVICES_VIEW_2 WHERE TENANT_ID = ? " +
|
||||
"AND FEATURE_CODE = ? " + advancedSqlFiltering + "GROUP BY OWNERSHIP";
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// executing query
|
||||
rs = stmt.executeQuery();
|
||||
// fetching query results
|
||||
while (rs.next()) {
|
||||
filteredDeviceCountsByOwnershipTypes.put(rs.getString("OWNERSHIP"), rs.getInt("DEVICE_COUNT"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of feature " +
|
||||
"non-compliant device counts by ownership types.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
||||
PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
|
||||
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_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, paginationRequest.getStartIndex());
|
||||
stmt.setInt(++i, paginationRequest.getRowCount());
|
||||
} else {
|
||||
stmt.setInt(2, paginationRequest.getStartIndex());
|
||||
stmt.setInt(3, paginationRequest.getRowCount());
|
||||
}
|
||||
// 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");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of devices " +
|
||||
"with details when pagination is enabled.", e);
|
||||
} 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, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException {
|
||||
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, paginationRequest.getStartIndex());
|
||||
stmt.setInt(++i, paginationRequest.getRowCount());
|
||||
} else {
|
||||
stmt.setInt(3, paginationRequest.getStartIndex());
|
||||
stmt.setInt(4, paginationRequest.getRowCount());
|
||||
}
|
||||
// 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");
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of feature non-compliant devices " +
|
||||
"with details when pagination is enabled.", e);
|
||||
} 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 GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql;
|
||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_1 WHERE TENANT_ID = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns, if exist
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting a filtered set of devices with details.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDevicesWithDetails;
|
||||
}
|
||||
|
||||
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceDAOException {
|
||||
Connection con;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet rs = null;
|
||||
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
|
||||
try {
|
||||
con = this.getConnection();
|
||||
String sql;
|
||||
sql = "SELECT DEVICE_ID, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM DEVICES_VIEW_2 " +
|
||||
"WHERE TENANT_ID = ? AND FEATURE_CODE = ?";
|
||||
// appending filters to support advanced filtering options
|
||||
// [1] appending filter columns, if exist
|
||||
if (filters != null && filters.size() > 0) {
|
||||
for (String column : filters.keySet()) {
|
||||
sql = sql + " AND " + column + " = ?";
|
||||
}
|
||||
}
|
||||
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++;
|
||||
}
|
||||
}
|
||||
// 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);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceDAOException("Error occurred @ GadgetDataServiceDAO layer while trying to " +
|
||||
"execute relevant SQL queries for getting filtered set of feature non-compliant devices with details.", e);
|
||||
} finally {
|
||||
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
|
||||
}
|
||||
return filteredDevicesWithDetails;
|
||||
}
|
||||
|
||||
private Connection getConnection() throws SQLException {
|
||||
return GadgetDataServiceDAOFactory.getConnection();
|
||||
}
|
||||
|
||||
}
|
||||
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -16,12 +16,13 @@
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard;
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception;
|
||||
|
||||
/**
|
||||
* Custom exception class for GadgetDataService layer.
|
||||
* Custom exception class for catching invalid parameter issues,
|
||||
* relevant to Gadget Data Service DAO layer.
|
||||
*/
|
||||
public class GadgetDataServiceException extends Exception {
|
||||
public class InvalidParameterValueException extends Exception {
|
||||
|
||||
private String errorMessage;
|
||||
private static final long serialVersionUID = 2021891706072918864L;
|
||||
@ -32,7 +33,8 @@ public class GadgetDataServiceException extends Exception {
|
||||
* @param errorMessage specific error message.
|
||||
* @param nestedException Nested exception.
|
||||
*/
|
||||
public GadgetDataServiceException(String errorMessage, Exception nestedException) {
|
||||
@SuppressWarnings("unused")
|
||||
public InvalidParameterValueException(String errorMessage, Exception nestedException) {
|
||||
super(errorMessage, nestedException);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
@ -44,7 +46,7 @@ public class GadgetDataServiceException extends Exception {
|
||||
* @param cause Cause of this exception.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceException(String errorMessage, Throwable cause) {
|
||||
public InvalidParameterValueException(String errorMessage, Throwable cause) {
|
||||
super(errorMessage, cause);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
@ -54,8 +56,7 @@ public class GadgetDataServiceException extends Exception {
|
||||
*
|
||||
* @param errorMessage Specific error message.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceException(String errorMessage) {
|
||||
public InvalidParameterValueException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
setErrorMessage(errorMessage);
|
||||
}
|
||||
@ -66,7 +67,7 @@ public class GadgetDataServiceException extends Exception {
|
||||
* @param cause Cause of this exception.
|
||||
*/
|
||||
@SuppressWarnings("unused")
|
||||
public GadgetDataServiceException(Throwable cause) {
|
||||
public InvalidParameterValueException(Throwable 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;
|
||||
}
|
||||
|
||||
}
|
||||
@ -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.analytics.dashboard.impl;
|
||||
|
||||
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.bean.*;
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.exception.InvalidParameterValueException;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* To be updated...
|
||||
*/
|
||||
public class GadgetDataServiceImpl implements GadgetDataService {
|
||||
|
||||
@Override
|
||||
public DeviceCountByGroupEntry getDeviceCount(FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
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 {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return totalDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByConnectivityStatuses() throws SQLException {
|
||||
List<DeviceCountByGroupEntry> deviceCountsByConnectivityStatuses;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByConnectivityStatuses = GadgetDataServiceDAOFactory.
|
||||
getGadgetDataServiceDAO().getDeviceCountsByConnectivityStatuses();
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByConnectivityStatuses;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByPotentialVulnerabilities() throws SQLException {
|
||||
List<DeviceCountByGroupEntry> deviceCountsByPotentialVulnerabilities;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByPotentialVulnerabilities = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDeviceCountsByPotentialVulnerabilities();
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByPotentialVulnerabilities;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount)
|
||||
throws SQLException, InvalidParameterValueException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getNonCompliantDeviceCountsByFeatures(startIndex, resultCount);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByPlatforms(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException {
|
||||
List<DeviceCountByGroupEntry> deviceCountsByPlatforms;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDeviceCountsByPlatforms(filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByPlatforms;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry> getDeviceCountsByOwnershipTypes(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException {
|
||||
List<DeviceCountByGroupEntry> deviceCountsByOwnershipTypes;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDeviceCountsByOwnershipTypes(filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DeviceCountByGroupEntry>
|
||||
getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws SQLException, InvalidParameterValueException {
|
||||
List<DeviceCountByGroupEntry> featureNonCompliantDeviceCountsByOwnershipTypes;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDeviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getDevicesWithDetails(FilterSet filterSet,
|
||||
int startIndex, int resultCount) throws InvalidParameterValueException, SQLException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDevicesWithDetails(filterSet, startIndex, resultCount);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet, int startIndex, int resultCount)
|
||||
throws InvalidParameterValueException, SQLException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet, startIndex, resultCount);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DetailedDeviceEntry> getDevicesWithDetails(FilterSet filterSet)
|
||||
throws InvalidParameterValueException, SQLException {
|
||||
List<DetailedDeviceEntry> devicesWithDetails;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
devicesWithDetails = GadgetDataServiceDAOFactory.
|
||||
getGadgetDataServiceDAO().getDevicesWithDetails(filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return devicesWithDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<DetailedDeviceEntry> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
FilterSet filterSet) throws InvalidParameterValueException, SQLException {
|
||||
List<DetailedDeviceEntry> featureNonCompliantDevicesWithDetails;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filterSet);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDevicesWithDetails;
|
||||
}
|
||||
|
||||
}
|
||||
@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
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.impl.GadgetDataServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig;
|
||||
import org.wso2.carbon.device.mgt.core.config.datasource.DataSourceConfig;
|
||||
@ -71,14 +72,14 @@ public class GadgetDataServiceComponent {
|
||||
//do nothing
|
||||
}
|
||||
|
||||
public void setDataSourceService(DataSourceService dataSourceService) {
|
||||
protected void setDataSourceService(DataSourceService dataSourceService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Binding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
||||
}
|
||||
//do nothing
|
||||
}
|
||||
|
||||
public void unsetDataSourceService(DataSourceService dataSourceService) {
|
||||
protected void unsetDataSourceService(DataSourceService dataSourceService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Unbinding org.wso2.carbon.ndatasource.core.DataSourceService...");
|
||||
}
|
||||
|
||||
@ -1,363 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.analytics.dashboard.internal;
|
||||
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataService;
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.GadgetDataServiceException;
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOException;
|
||||
import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationRequest;
|
||||
import org.wso2.carbon.device.mgt.common.PaginationResult;
|
||||
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* To be updated...
|
||||
*/
|
||||
class GadgetDataServiceImpl implements GadgetDataService {
|
||||
|
||||
@Override
|
||||
public int getTotalDeviceCount() throws GadgetDataServiceException {
|
||||
int totalDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
totalDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getTotalDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for total device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return totalDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getActiveDeviceCount() throws GadgetDataServiceException {
|
||||
int activeDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
activeDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getActiveDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for active device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return activeDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getInactiveDeviceCount() throws GadgetDataServiceException {
|
||||
int inactiveDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
inactiveDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getInactiveDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for inactive device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return inactiveDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getRemovedDeviceCount() throws GadgetDataServiceException {
|
||||
int removedDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
removedDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getRemovedDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for removed device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return removedDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getNonCompliantDeviceCount() throws GadgetDataServiceException {
|
||||
int nonCompliantDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
nonCompliantDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getNonCompliantDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for non-compliant device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return nonCompliantDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getUnmonitoredDeviceCount() throws GadgetDataServiceException {
|
||||
int unmonitoredDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
unmonitoredDeviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getUnmonitoredDeviceCount();
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for unmonitored device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return unmonitoredDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest)
|
||||
throws GadgetDataServiceException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getNonCompliantDeviceCountsByFeatures(paginationRequest);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for non-compliant device counts by features.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceException {
|
||||
int deviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCount = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDeviceCount(filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in calling DAO function for getting a filtered device count.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, Map<String, Object> filters)
|
||||
throws GadgetDataServiceException {
|
||||
int featureNonCompliantDeviceCount;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDeviceCount = GadgetDataServiceDAOFactory.
|
||||
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCount(nonCompliantFeatureCode, filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting a filtered device count, non compliant by a particular feature.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDeviceCount;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters)
|
||||
throws GadgetDataServiceException {
|
||||
Map<String, Integer> deviceCountsByPlatforms;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByPlatforms = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDeviceCountsByPlatforms(filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered device counts by platforms.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException {
|
||||
Map<String, Integer> featureNonCompliantDeviceCountsByPlatforms;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDeviceCountsByPlatforms = GadgetDataServiceDAOFactory.
|
||||
getGadgetDataServiceDAO().getFeatureNonCompliantDeviceCountsByPlatforms(nonCompliantFeatureCode, filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered device counts by platforms, non compliant by a particular feature.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDeviceCountsByPlatforms;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
|
||||
throws GadgetDataServiceException {
|
||||
Map<String, Integer> deviceCountsByOwnershipTypes;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
deviceCountsByOwnershipTypes = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDeviceCountsByOwnershipTypes(filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered device counts by ownership types.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return deviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException {
|
||||
Map<String, Integer> featureNonCompliantDeviceCountsByOwnershipTypes;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDeviceCountsByOwnershipTypes =
|
||||
GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDeviceCountsByOwnershipTypes(nonCompliantFeatureCode, filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection.", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered device counts by ownership types, non compliant by a particular feature.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDeviceCountsByOwnershipTypes;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getDevicesWithDetails(Map<String, Object> filters,
|
||||
PaginationRequest paginationRequest) throws GadgetDataServiceException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getDevicesWithDetails(filters, paginationRequest);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered devices with details when pagination is enabled.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceException {
|
||||
PaginationResult paginationResult;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
paginationResult = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters, paginationRequest);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered devices with details, non compliant by feature when pagination is enabled.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return paginationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters)
|
||||
throws GadgetDataServiceException {
|
||||
List<Map<String, Object>> devicesWithDetails;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered devices with details.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return devicesWithDetails;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
|
||||
Map<String, Object> filters) throws GadgetDataServiceException {
|
||||
List<Map<String, Object>> featureNonCompliantDevicesWithDetails;
|
||||
try {
|
||||
GadgetDataServiceDAOFactory.openConnection();
|
||||
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
|
||||
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters);
|
||||
} catch (SQLException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer " +
|
||||
"in opening database connection", e);
|
||||
} catch (GadgetDataServiceDAOException e) {
|
||||
throw new GadgetDataServiceException("Error occurred @ GadgetDataService layer in calling DAO function " +
|
||||
"for getting filtered devices with details, non compliant by feature.", e);
|
||||
} finally {
|
||||
GadgetDataServiceDAOFactory.closeConnection();
|
||||
}
|
||||
return featureNonCompliantDevicesWithDetails;
|
||||
}
|
||||
|
||||
}
|
||||
@ -43,11 +43,9 @@
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
<version>2.3.2</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-war-plugin</artifactId>
|
||||
<version>2.2</version>
|
||||
<configuration>
|
||||
<packagingExcludes>WEB-INF/lib/*cxf*.jar</packagingExcludes>
|
||||
<warName>devicemgt_admin</warName>
|
||||
@ -88,7 +86,6 @@
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
<profile>
|
||||
<id>client</id>
|
||||
<build>
|
||||
@ -207,6 +204,11 @@
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger</groupId>
|
||||
<artifactId>swagger-annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
||||
@ -22,14 +22,15 @@ 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.EnrolmentInfo;
|
||||
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.util.DeviceMgtAPIUtils;
|
||||
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
|
||||
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.DELETE;
|
||||
@ -42,26 +43,13 @@ import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Response;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
public class Group {
|
||||
|
||||
private static final String DEFAULT_ADMIN_ROLE = "admin";
|
||||
private static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations";
|
||||
private static final String DEFAULT_STATS_MONITOR_ROLE = "view-statistics";
|
||||
private static final String DEFAULT_VIEW_POLICIES = "view-policies";
|
||||
private static final String DEFAULT_MANAGE_POLICIES = "mange-policies";
|
||||
private static final String DEFAULT_VIEW_EVENTS = "view-events";
|
||||
private static final String[] DEFAULT_ADMIN_PERMISSIONS = {"/permission/device-mgt/admin/groups",
|
||||
"/permission/device-mgt/user/groups"};
|
||||
private static final String[] DEFAULT_OPERATOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_operation"};
|
||||
private static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS = {"/permission/device-mgt/user/groups/device_monitor"};
|
||||
private static final String[] DEFAULT_MANAGE_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/add"};
|
||||
private static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS = {"/permission/device-mgt/user/groups/device_policies/view"};
|
||||
private static final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS = {"/permission/device-mgt/user/groups/device_events"};
|
||||
|
||||
private static Log log = LogFactory.getLog(Group.class);
|
||||
|
||||
@POST
|
||||
@ -76,18 +64,18 @@ public class Group {
|
||||
group.setDateOfLastUpdate(new Date().getTime());
|
||||
try {
|
||||
GroupManagementProviderService groupManagementService = DeviceMgtAPIUtils.getGroupManagementProviderService();
|
||||
groupManagementService.createGroup(group, DEFAULT_ADMIN_ROLE, DEFAULT_ADMIN_PERMISSIONS);
|
||||
groupManagementService.createGroup(group, DeviceGroupConstants.Roles.DEFAULT_ADMIN_ROLE, DeviceGroupConstants.Permissions.DEFAULT_ADMIN_PERMISSIONS);
|
||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner,
|
||||
DEFAULT_OPERATOR_ROLE,
|
||||
DEFAULT_OPERATOR_PERMISSIONS);
|
||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_STATS_MONITOR_ROLE,
|
||||
DEFAULT_STATS_MONITOR_PERMISSIONS);
|
||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_POLICIES,
|
||||
DEFAULT_VIEW_POLICIES_PERMISSIONS);
|
||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_MANAGE_POLICIES,
|
||||
DEFAULT_MANAGE_POLICIES_PERMISSIONS);
|
||||
groupManagementService.addGroupSharingRole(owner, group.getName(), owner, DEFAULT_VIEW_EVENTS,
|
||||
DEFAULT_VIEW_EVENTS_PERMISSIONS);
|
||||
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();
|
||||
@ -126,10 +114,10 @@ public class Group {
|
||||
|
||||
@GET
|
||||
@Produces("application/json")
|
||||
public Response getGroups(@QueryParam("start") int startIndex, @PathParam("rowCount") int rowCount) {
|
||||
public Response getGroups(@QueryParam("start") int startIndex, @PathParam("length") int length) {
|
||||
try {
|
||||
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||
.getGroups(startIndex, rowCount);
|
||||
.getGroups(startIndex, length);
|
||||
if (paginationResult.getRecordsTotal() > 0) {
|
||||
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
||||
} else {
|
||||
@ -165,10 +153,10 @@ public class Group {
|
||||
@GET
|
||||
@Produces("application/json")
|
||||
public Response getGroups(@PathParam("user") String userName, @QueryParam("start") int startIndex,
|
||||
@QueryParam("rowCount") int rowCount) {
|
||||
@QueryParam("length") int length) {
|
||||
try {
|
||||
PaginationResult paginationResult = DeviceMgtAPIUtils.getGroupManagementProviderService()
|
||||
.getGroups(userName, startIndex, rowCount);
|
||||
.getGroups(userName, startIndex, length);
|
||||
if (paginationResult.getRecordsTotal() > 0) {
|
||||
return Response.status(Response.Status.OK).entity(paginationResult).build();
|
||||
} else {
|
||||
@ -180,6 +168,24 @@ public class Group {
|
||||
}
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
}
|
||||
|
||||
@Path("/owner/{owner}/name/{groupName}")
|
||||
@GET
|
||||
@Produces("application/json")
|
||||
@ -275,8 +281,10 @@ public class Group {
|
||||
if (isShared) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_FOUND).build();
|
||||
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();
|
||||
@ -295,8 +303,10 @@ public class Group {
|
||||
if (isUnShared) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
} else {
|
||||
return Response.status(Response.Status.NOT_FOUND).build();
|
||||
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();
|
||||
@ -360,6 +370,34 @@ public class Group {
|
||||
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
|
||||
@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();
|
||||
@ -466,6 +504,8 @@ public class Group {
|
||||
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();
|
||||
|
||||
@ -1035,6 +1035,13 @@
|
||||
<method>GET</method>
|
||||
</Permission>
|
||||
|
||||
<Permission>
|
||||
<name>Group Roles</name>
|
||||
<path>/device-mgt/user/groups/roles</path>
|
||||
<url>/groups/owner/*/name/*/user/*/share/roles</url>
|
||||
<method>PUT</method>
|
||||
</Permission>
|
||||
|
||||
<Permission>
|
||||
<name>Group Permissions</name>
|
||||
<path>/device-mgt/admin/groups/roles/permissions</path>
|
||||
|
||||
@ -28,7 +28,6 @@ import java.util.List;
|
||||
* accessing the device information and performing MDM operations on devices.
|
||||
*/
|
||||
public interface DeviceAccessAuthorizationService {
|
||||
|
||||
/**
|
||||
* This method will check whether the currently logged-in user has the access to the device identified by the given
|
||||
* DeviceIdentifier.
|
||||
@ -39,18 +38,71 @@ public interface DeviceAccessAuthorizationService {
|
||||
*/
|
||||
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the currently logged-in user has the access to the device identified by the given
|
||||
* DeviceIdentifier.
|
||||
*
|
||||
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
|
||||
* @param groupPermissions - Group Permissions.
|
||||
* @return Boolean authorization result.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the currently logged-in user has the access to the devices identified by the given
|
||||
* DeviceIdentifier list.
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices &
|
||||
* unauthorized devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
|
||||
DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the currently logged-in user has the access to the devices identified by the given
|
||||
* DeviceIdentifier list.
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param groupPermissions - Group Permissions
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the given user has the access to the device identified by the given
|
||||
* DeviceIdentifier.
|
||||
*
|
||||
* @param deviceIdentifier - DeviceIdentifier of the device to be checked.
|
||||
* @param username - Username of the user to be checked for authorization.
|
||||
* @param groupPermissions - Group Permissions
|
||||
* @return Boolean authorization result.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the given user has the access to the devices identified by the given
|
||||
* DeviceIdentifier list.
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param username - User name
|
||||
* @param groupPermissions - Group Permissions
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username,
|
||||
String[] groupPermissions) throws
|
||||
DeviceAccessAuthorizationException;
|
||||
|
||||
/**
|
||||
* This method will check whether the given user has the access to the device identified by the given
|
||||
* DeviceIdentifier.
|
||||
@ -69,11 +121,10 @@ public interface DeviceAccessAuthorizationService {
|
||||
*
|
||||
* @param deviceIdentifiers - List of DeviceIdentifiers to be checked for authorization.
|
||||
* @param username - Username of the user to be checked for authorization.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices &
|
||||
* unauthorized devices.
|
||||
* @return DeviceAuthorizationResult - Authorization result including the list of authorized devices & unauthorized
|
||||
* devices.
|
||||
* @throws DeviceAccessAuthorizationException if something goes wrong when checking the authorization.
|
||||
*/
|
||||
DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username) throws
|
||||
DeviceAccessAuthorizationException;
|
||||
|
||||
}
|
||||
@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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.common.group.mgt;
|
||||
|
||||
|
||||
/**
|
||||
* Holds Device Group constants and expose to external access
|
||||
*/
|
||||
public class DeviceGroupConstants {
|
||||
public enum RolePermissions {
|
||||
DEFAULT_ADMIN_ROLE(Roles.DEFAULT_ADMIN_ROLE),
|
||||
DEFAULT_OPERATOR_ROLE(Roles.DEFAULT_OPERATOR_ROLE),
|
||||
DEFAULT_STATS_MONITOR_ROLE(Roles.DEFAULT_STATS_MONITOR_ROLE),
|
||||
DEFAULT_VIEW_POLICIES(Roles.DEFAULT_VIEW_POLICIES),
|
||||
DEFAULT_MANAGE_POLICIES(Roles.DEFAULT_MANAGE_POLICIES),
|
||||
DEFAULT_VIEW_EVENTS(Roles.DEFAULT_VIEW_EVENTS);
|
||||
|
||||
private String value;
|
||||
private String[] permissions;
|
||||
|
||||
RolePermissions(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
static {
|
||||
DEFAULT_ADMIN_ROLE.permissions = Permissions.DEFAULT_ADMIN_PERMISSIONS;
|
||||
DEFAULT_OPERATOR_ROLE.permissions = Permissions.DEFAULT_OPERATOR_PERMISSIONS;
|
||||
DEFAULT_STATS_MONITOR_ROLE.permissions = Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS;
|
||||
DEFAULT_VIEW_POLICIES.permissions = Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS;
|
||||
DEFAULT_MANAGE_POLICIES.permissions = Permissions.DEFAULT_VIEW_POLICIES_PERMISSIONS;
|
||||
DEFAULT_VIEW_EVENTS.permissions = Permissions.DEFAULT_VIEW_EVENTS_PERMISSIONS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString(){
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public String[] getPermissions(){
|
||||
return permissions;
|
||||
}
|
||||
}
|
||||
|
||||
public static class Roles {
|
||||
public static final String DEFAULT_ADMIN_ROLE = "admin";
|
||||
public static final String DEFAULT_OPERATOR_ROLE = "invoke-device-operations";
|
||||
public static final String DEFAULT_STATS_MONITOR_ROLE = "view-statistics";
|
||||
public static final String DEFAULT_VIEW_POLICIES = "view-policies";
|
||||
public static final String DEFAULT_MANAGE_POLICIES = "mange-policies";
|
||||
public static final String DEFAULT_VIEW_EVENTS = "view-events";
|
||||
}
|
||||
|
||||
public static class Permissions {
|
||||
public static final String[] DEFAULT_ADMIN_PERMISSIONS =
|
||||
{"/permission/device-mgt/admin/groups", "/permission/device-mgt/user/groups"};
|
||||
public static final String[] DEFAULT_OPERATOR_PERMISSIONS =
|
||||
{"/permission/device-mgt/user/groups/device_operation"};
|
||||
public static final String[] DEFAULT_STATS_MONITOR_PERMISSIONS =
|
||||
{"/permission/device-mgt/user/groups/device_monitor"};
|
||||
public static final String[] DEFAULT_MANAGE_POLICIES_PERMISSIONS =
|
||||
{"/permission/device-mgt/user/groups/device_policies/add"};
|
||||
public static final String[] DEFAULT_VIEW_POLICIES_PERMISSIONS =
|
||||
{"/permission/device-mgt/user/groups/device_policies/view"};
|
||||
public static final String[] DEFAULT_VIEW_EVENTS_PERMISSIONS =
|
||||
{"/permission/device-mgt/user/groups/device_events"};
|
||||
}
|
||||
}
|
||||
@ -1,10 +1,10 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
@ -21,19 +21,24 @@ package org.wso2.carbon.device.mgt.core.authorization;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.*;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAuthorizationResult;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.permission.mgt.Permission;
|
||||
import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.internal.DeviceManagementDataHolder;
|
||||
import org.wso2.carbon.device.mgt.core.permission.mgt.PermissionUtils;
|
||||
import org.wso2.carbon.user.api.UserRealm;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@ -45,18 +50,6 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
|
||||
private final static String EMM_ADMIN_PERMISSION = "/device-mgt/admin-device-access";
|
||||
private static Log log = LogFactory.getLog(DeviceAccessAuthorizationServiceImpl.class);
|
||||
|
||||
public static final class PermissionMethod {
|
||||
private PermissionMethod() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
|
||||
public static final String READ = "read";
|
||||
public static final String WRITE = "write";
|
||||
public static final String DELETE = "delete";
|
||||
public static final String ACTION = "action";
|
||||
public static final String UI_EXECUTE = "ui.execute";
|
||||
}
|
||||
|
||||
public DeviceAccessAuthorizationServiceImpl() {
|
||||
try {
|
||||
this.addAdminPermissionToRegistry();
|
||||
@ -66,157 +59,169 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException {
|
||||
boolean status;
|
||||
String username = this.getUserName();
|
||||
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
int tenantId = this.getTenantId();
|
||||
if (username == null || username.isEmpty()) {
|
||||
return !DeviceManagementDataHolder.getInstance().requireDeviceAuthorization(deviceIdentifier.getType());
|
||||
return false;
|
||||
}
|
||||
//check for admin and ownership permissions
|
||||
if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) {
|
||||
return true;
|
||||
}
|
||||
//check for group permissions
|
||||
try {
|
||||
//Check for admin users. If the user is an admin user we authorize the access to that device.
|
||||
status = isAdminUser(username, tenantId);
|
||||
} catch (UserStoreException e) {
|
||||
if (groupPermissions == null || groupPermissions.length == 0) {
|
||||
return false;
|
||||
}
|
||||
for (String groupPermission : groupPermissions) {
|
||||
if (!isAuthorizedViaGroup(username, deviceIdentifier, groupPermission)) {
|
||||
//if at least one fails, authorization fails
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (GroupManagementException | UserStoreException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " + username, e);
|
||||
}
|
||||
//Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
if (!status) {
|
||||
try {
|
||||
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
getDevice(deviceIdentifier);
|
||||
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
|
||||
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
|
||||
status = true;
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " + username, e);
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers) throws
|
||||
DeviceAccessAuthorizationException {
|
||||
boolean status;
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
|
||||
String username = this.getUserName();
|
||||
int tenantId = this.getTenantId();
|
||||
if (username == null || username.isEmpty()) {
|
||||
return deviceAuthorizationResult;
|
||||
}
|
||||
try {
|
||||
//Check for admin users. If the user is an admin user we authorize the access to that device.
|
||||
status = isAdminUser(username, tenantId);
|
||||
} catch (UserStoreException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
|
||||
deviceIdentifier.getId() + " for the user : " +
|
||||
username, e);
|
||||
}
|
||||
//Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
if (!status) {
|
||||
try {
|
||||
//Get the list of devices of the user
|
||||
List<Device> devicesOfUser = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
getDevicesOfUser(username);
|
||||
//Convert device-list to a Map
|
||||
Map<String, String> ownershipData = this.getOwnershipOfDevices(devicesOfUser);
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
|
||||
if (ownershipData.containsKey(deviceIdentifier.getId())) {
|
||||
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
|
||||
} else {
|
||||
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
|
||||
}
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : "
|
||||
+ username, e);
|
||||
}
|
||||
} else {
|
||||
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
|
||||
}
|
||||
return deviceAuthorizationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String username)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
boolean status;
|
||||
return isUserAuthorized(deviceIdentifier, username, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
return isUserAuthorized(deviceIdentifier, this.getUserName(), groupPermissions);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isUserAuthorized(DeviceIdentifier deviceIdentifier) throws DeviceAccessAuthorizationException {
|
||||
return isUserAuthorized(deviceIdentifier, this.getUserName(), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username,
|
||||
String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
int tenantId = this.getTenantId();
|
||||
if (username == null || username.isEmpty()) {
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
|
||||
//check for admin and ownership permissions
|
||||
if (isAdminOrDeviceOwner(username, tenantId, deviceIdentifier)) {
|
||||
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
|
||||
} else {
|
||||
try {
|
||||
//Check for admin users. If the user is an admin user we authorize the access to that device.
|
||||
status = isAdminUser(username, tenantId);
|
||||
} catch (UserStoreException e) {
|
||||
if (groupPermissions == null || groupPermissions.length == 0) {
|
||||
return null;
|
||||
}
|
||||
//check for group permissions
|
||||
boolean isAuthorized = true;
|
||||
for (String groupPermission : groupPermissions) {
|
||||
if (!isAuthorizedViaGroup(username, deviceIdentifier, groupPermission)) {
|
||||
//if at least one failed, authorizations fails and break the loop
|
||||
isAuthorized = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (isAuthorized) {
|
||||
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
|
||||
} else {
|
||||
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
|
||||
}
|
||||
} catch (GroupManagementException | UserStoreException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " + username, e);
|
||||
}
|
||||
//Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
if (!status) {
|
||||
try {
|
||||
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
getDevice(deviceIdentifier);
|
||||
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
|
||||
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
|
||||
status = true;
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " + username, e);
|
||||
deviceIdentifier.getId() + " for the user : " +
|
||||
username, e);
|
||||
}
|
||||
}
|
||||
return status;
|
||||
}
|
||||
return deviceAuthorizationResult;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String username)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
boolean status;
|
||||
int tenantId = this.getTenantId();
|
||||
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
|
||||
if (username == null || username.isEmpty()) {
|
||||
return null;
|
||||
return isUserAuthorized(deviceIdentifiers, username, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
return isUserAuthorized(deviceIdentifiers, this.getUserName(), null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceAuthorizationResult isUserAuthorized(List<DeviceIdentifier> deviceIdentifiers, String[] groupPermissions)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
return isUserAuthorized(deviceIdentifiers, this.getUserName(), groupPermissions);
|
||||
}
|
||||
|
||||
private boolean isAdminOrDeviceOwner(String username, int tenantId, DeviceIdentifier deviceIdentifier)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
try {
|
||||
//Check for admin users. If the user is an admin user we authorize the access to that device.
|
||||
status = isAdminUser(username, tenantId);
|
||||
//First Check for admin users. If the user is an admin user we authorize the access to that device.
|
||||
//Secondly Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
return (isAdminUser(username, tenantId) || isDeviceOwner(deviceIdentifier, username));
|
||||
} catch (UserStoreException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : " +
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " +
|
||||
username, e);
|
||||
}
|
||||
//Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
if (!status) {
|
||||
try {
|
||||
Device device;
|
||||
EnrolmentInfo enrolmentInfo;
|
||||
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
|
||||
device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
getDevice(deviceIdentifier);
|
||||
enrolmentInfo = device.getEnrolmentInfo();
|
||||
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
|
||||
deviceAuthorizationResult.addAuthorizedDevice(deviceIdentifier);
|
||||
} else {
|
||||
deviceAuthorizationResult.addUnauthorizedDevice(deviceIdentifier);
|
||||
}
|
||||
|
||||
private boolean isAuthorizedViaGroup(String username, DeviceIdentifier deviceIdentifier, String groupPermission)
|
||||
throws GroupManagementException, UserStoreException {
|
||||
List<DeviceGroup> authorizedGroups =
|
||||
DeviceManagementDataHolder.getInstance().getGroupManagementProviderService()
|
||||
.getGroups(username, groupPermission);
|
||||
List<DeviceGroup> groupsWithDevice =
|
||||
DeviceManagementDataHolder.getInstance().getGroupManagementProviderService()
|
||||
.getGroups(deviceIdentifier);
|
||||
for (DeviceGroup group : authorizedGroups) {
|
||||
Iterator<DeviceGroup> groupsWithDeviceIterator = groupsWithDevice.iterator();
|
||||
while (groupsWithDeviceIterator.hasNext()) {
|
||||
DeviceGroup deviceGroup = groupsWithDeviceIterator.next();
|
||||
if (deviceGroup.getId() == group.getId()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isDeviceOwner(DeviceIdentifier deviceIdentifier, String username)
|
||||
throws DeviceAccessAuthorizationException {
|
||||
//Check for device ownership. If the user is the owner of the device we allow the access.
|
||||
try {
|
||||
Device device = DeviceManagementDataHolder.getInstance().getDeviceManagementProvider().
|
||||
getDevice(deviceIdentifier);
|
||||
EnrolmentInfo enrolmentInfo = device.getEnrolmentInfo();
|
||||
if (enrolmentInfo != null && username.equalsIgnoreCase(enrolmentInfo.getOwner())) {
|
||||
return true;
|
||||
}
|
||||
} catch (DeviceManagementException e) {
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to devices for the user : "
|
||||
+ username, e);
|
||||
throw new DeviceAccessAuthorizationException("Unable to authorize the access to device : " +
|
||||
deviceIdentifier.getId() + " for the user : " +
|
||||
username, e);
|
||||
}
|
||||
} else {
|
||||
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
|
||||
}
|
||||
return deviceAuthorizationResult;
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isAdminUser(String username, int tenantId) throws UserStoreException {
|
||||
UserRealm userRealm = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId);
|
||||
if (userRealm != null && userRealm.getAuthorizationManager() != null) {
|
||||
return userRealm.getAuthorizationManager()
|
||||
.isUserAuthorized(removeTenantDomain(username), PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION),
|
||||
.isUserAuthorized(removeTenantDomain(username),
|
||||
PermissionUtils.getAbsolutePermissionPath(EMM_ADMIN_PERMISSION),
|
||||
PermissionMethod.UI_EXECUTE);
|
||||
}
|
||||
return false;
|
||||
@ -263,4 +268,16 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
|
||||
}
|
||||
return ownershipData;
|
||||
}
|
||||
|
||||
public static final class PermissionMethod {
|
||||
public static final String READ = "read";
|
||||
public static final String WRITE = "write";
|
||||
public static final String DELETE = "delete";
|
||||
public static final String ACTION = "action";
|
||||
public static final String UI_EXECUTE = "ui.execute";
|
||||
|
||||
private PermissionMethod() {
|
||||
throw new AssertionError();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -97,7 +97,7 @@ public class DeviceManagementDAOFactory {
|
||||
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
|
||||
|
||||
public static DeviceDAO getDeviceDAO() {
|
||||
if(databaseEngine != null) {
|
||||
if (databaseEngine != null) {
|
||||
switch (databaseEngine) {
|
||||
case DeviceManagementConstants.DataBaseTypes.DB_TYPE_ORACLE:
|
||||
return new OracleDeviceDAOImpl();
|
||||
@ -112,7 +112,7 @@ public class DeviceManagementDAOFactory {
|
||||
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() {
|
||||
|
||||
@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
|
||||
import org.wso2.carbon.device.mgt.core.app.mgt.config.AppManagementConfig;
|
||||
import org.wso2.carbon.device.mgt.core.config.license.LicenseConfig;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
|
||||
import org.wso2.carbon.ntask.core.service.TaskService;
|
||||
import org.wso2.carbon.registry.core.service.RegistryService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
@ -47,6 +48,7 @@ public class DeviceManagementDataHolder {
|
||||
private ConfigurationContextService configurationContextService;
|
||||
private HashMap<String,Boolean> requireDeviceAuthorization = new HashMap<>();
|
||||
private DeviceAccessAuthorizationService deviceAccessAuthorizationService;
|
||||
private GroupManagementProviderService groupManagementProviderService;
|
||||
|
||||
private TaskService taskService;
|
||||
//private EmailSenderService emailSenderService;
|
||||
@ -91,6 +93,15 @@ public class DeviceManagementDataHolder {
|
||||
this.deviceManagerProvider = deviceManagerProvider;
|
||||
}
|
||||
|
||||
public GroupManagementProviderService getGroupManagementProviderService() {
|
||||
return groupManagementProviderService;
|
||||
}
|
||||
|
||||
public void setGroupManagementProviderService(
|
||||
GroupManagementProviderService groupManagementProviderService) {
|
||||
this.groupManagementProviderService = groupManagementProviderService;
|
||||
}
|
||||
|
||||
public RegistryService getRegistryService() {
|
||||
if (registryService == null) {
|
||||
throw new IllegalStateException("Registry service is not initialized properly");
|
||||
|
||||
@ -195,6 +195,7 @@ public class DeviceManagementServiceComponent {
|
||||
|
||||
/* Registering Group Management Service */
|
||||
GroupManagementProviderService groupManagementProvider = new GroupManagementProviderServiceImpl();
|
||||
DeviceManagementDataHolder.getInstance().setGroupManagementProviderService(groupManagementProvider);
|
||||
bundleContext.registerService(GroupManagementProviderService.class.getName(), groupManagementProvider, null);
|
||||
|
||||
/* Registering Tenant Configuration Management Service */
|
||||
|
||||
@ -72,8 +72,8 @@ public class DeviceTaskManagerServiceComponent {
|
||||
@SuppressWarnings("unused")
|
||||
protected void deactivate(ComponentContext componentContext) {
|
||||
try {
|
||||
DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl();
|
||||
taskManagerService.stopTask();
|
||||
// DeviceTaskManagerService taskManagerService = new DeviceTaskManagerServiceImpl();
|
||||
// taskManagerService.stopTask();
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while destroying the device details retrieving task manager service.", e);
|
||||
}
|
||||
|
||||
@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.*;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManager;
|
||||
@ -88,7 +89,8 @@ public class OperationManagerImpl implements OperationManager {
|
||||
authorizedDeviceList = deviceIds;
|
||||
} else {
|
||||
authorizedDeviceList = DeviceManagementDataHolder.getInstance().
|
||||
getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds).getAuthorizedDevices();
|
||||
getDeviceAccessAuthorizationService().isUserAuthorized(deviceIds, DeviceGroupConstants.
|
||||
Permissions.DEFAULT_OPERATOR_PERMISSIONS).getAuthorizedDevices();
|
||||
}
|
||||
if (authorizedDeviceList.size() > 0) {
|
||||
try {
|
||||
@ -146,7 +148,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
List<Operation> operations = new ArrayList<>();
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -202,7 +204,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
List<Operation> operations = new ArrayList<>();
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -266,7 +268,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
List<org.wso2.carbon.device.mgt.core.dto.operation.mgt.Operation> dtoOperationList = new ArrayList<>();
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -330,7 +332,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
int enrolmentId;
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -400,7 +402,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
int enrolmentId;
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -480,7 +482,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
}
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
@ -554,7 +556,7 @@ public class OperationManagerImpl implements OperationManager {
|
||||
int enrolmentId;
|
||||
try {
|
||||
boolean isUserAuthorized = DeviceManagementDataHolder.getInstance().getDeviceAccessAuthorizationService().
|
||||
isUserAuthorized(deviceId);
|
||||
isUserAuthorized(deviceId, DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS);
|
||||
if (isUserAuthorized) {
|
||||
try {
|
||||
try {
|
||||
|
||||
@ -25,7 +25,7 @@ import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
|
||||
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.group.mgt.DeviceGroupBuilder;
|
||||
import org.wso2.carbon.user.core.multiplecredentials.UserDoesNotExistException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ -77,6 +77,7 @@ public interface GroupManagementProviderService {
|
||||
|
||||
/**
|
||||
* Get the device group provided the device group id.
|
||||
*
|
||||
* @param groupId
|
||||
* @return
|
||||
* @throws GroupManagementException
|
||||
@ -148,10 +149,10 @@ public interface GroupManagementProviderService {
|
||||
* @param owner of the group
|
||||
* @param sharingRole to be shared
|
||||
* @return is group shared
|
||||
* @throws GroupManagementException
|
||||
* @throws GroupManagementException UserDoesNotExistException
|
||||
*/
|
||||
boolean shareGroup(String username, String groupName, String owner, String sharingRole)
|
||||
throws GroupManagementException;
|
||||
throws GroupManagementException, UserDoesNotExistException;
|
||||
|
||||
/**
|
||||
* Un share existing group sharing with user specified by role
|
||||
@ -161,10 +162,10 @@ public interface GroupManagementProviderService {
|
||||
* @param owner of the group
|
||||
* @param sharingRole to be un shared
|
||||
* @return is group un shared
|
||||
* @throws GroupManagementException
|
||||
* @throws GroupManagementException UserDoesNotExistException
|
||||
*/
|
||||
boolean unshareGroup(String userName, String groupName, String owner, String sharingRole)
|
||||
throws GroupManagementException;
|
||||
throws GroupManagementException, UserDoesNotExistException;
|
||||
|
||||
/**
|
||||
* Add new sharing role for device group
|
||||
@ -208,9 +209,10 @@ public interface GroupManagementProviderService {
|
||||
* @param groupName of the group
|
||||
* @param owner of the group
|
||||
* @return list of roles
|
||||
* @throws GroupManagementException
|
||||
* @throws GroupManagementException UserDoesNotExistException
|
||||
*/
|
||||
List<String> getRoles(String userName, String groupName, String owner) throws GroupManagementException;
|
||||
List<String> getRoles(String userName, String groupName, String owner)
|
||||
throws GroupManagementException, UserDoesNotExistException;
|
||||
|
||||
/**
|
||||
* Get device group users
|
||||
@ -284,9 +286,10 @@ public interface GroupManagementProviderService {
|
||||
* @param groupName of the group.
|
||||
* @param owner of the group.
|
||||
* @return array of permissions.
|
||||
* @throws GroupManagementException
|
||||
* @throws GroupManagementException UserDoesNotExistException
|
||||
*/
|
||||
String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException;
|
||||
String[] getPermissions(String username, String groupName, String owner)
|
||||
throws GroupManagementException, UserDoesNotExistException;
|
||||
|
||||
/**
|
||||
* Get device groups of user with permission.
|
||||
@ -300,6 +303,7 @@ public interface GroupManagementProviderService {
|
||||
|
||||
/**
|
||||
* Get the group of device.
|
||||
*
|
||||
* @param deviceIdentifier
|
||||
* @return
|
||||
* @throws GroupManagementException
|
||||
|
||||
@ -41,6 +41,7 @@ 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.multiplecredentials.UserDoesNotExistException;
|
||||
import org.wso2.carbon.user.core.util.UserCoreUtil;
|
||||
|
||||
import java.sql.SQLException;
|
||||
@ -379,7 +380,7 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
*/
|
||||
@Override
|
||||
public boolean shareGroup(String username, String groupName, String owner, String sharingRole)
|
||||
throws GroupManagementException {
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
int groupId = getGroupId(groupName, owner);
|
||||
return modifyGroupShare(username, groupId, sharingRole, true);
|
||||
}
|
||||
@ -389,14 +390,14 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
*/
|
||||
@Override
|
||||
public boolean unshareGroup(String username, String groupName, String owner, String sharingRole)
|
||||
throws GroupManagementException {
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
int groupId = getGroupId(groupName, owner);
|
||||
return modifyGroupShare(username, groupId, sharingRole, false);
|
||||
}
|
||||
|
||||
private boolean modifyGroupShare(String username, int groupId, String sharingRole,
|
||||
boolean isAddNew)
|
||||
throws GroupManagementException {
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
if (groupId == -1) {
|
||||
return false;
|
||||
}
|
||||
@ -407,14 +408,21 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
userStoreManager =
|
||||
DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(
|
||||
tenantId).getUserStoreManager();
|
||||
if (!userStoreManager.isExistingUser(username)) {
|
||||
throw new UserDoesNotExistException("User not exists with name " + username);
|
||||
}
|
||||
roles[0] = "Internal/group-" + groupId + "-" + sharingRole;
|
||||
if (isAddNew) {
|
||||
List<String> currentRoles = getRoles(username, groupId);
|
||||
if (isAddNew && !currentRoles.contains(sharingRole)) {
|
||||
userStoreManager.updateRoleListOfUser(username, null, roles);
|
||||
} else {
|
||||
} else if (!isAddNew && currentRoles.contains(sharingRole)) {
|
||||
userStoreManager.updateRoleListOfUser(username, roles, null);
|
||||
}
|
||||
return true;
|
||||
} catch (UserStoreException e) {
|
||||
if (e instanceof UserDoesNotExistException) {
|
||||
throw (UserDoesNotExistException) e;
|
||||
}
|
||||
throw new GroupManagementException("User store error in adding user " + username + " to group name:" +
|
||||
groupId, e);
|
||||
}
|
||||
@ -532,18 +540,23 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public List<String> getRoles(String username, String groupName, String owner) throws GroupManagementException {
|
||||
public List<String> getRoles(String username, String groupName, String owner)
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
int groupId = getGroupId(groupName, owner);
|
||||
return getRoles(username, groupId);
|
||||
}
|
||||
|
||||
private List<String> getRoles(String username, int groupId) throws GroupManagementException {
|
||||
private List<String> getRoles(String username, int groupId)
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
UserStoreManager userStoreManager;
|
||||
List<String> groupRoleList = new ArrayList<>();
|
||||
try {
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
userStoreManager = DeviceManagementDataHolder.getInstance().getRealmService().getTenantUserRealm(tenantId)
|
||||
.getUserStoreManager();
|
||||
if (!userStoreManager.isExistingUser(username)) {
|
||||
throw new UserDoesNotExistException("User not exists with name " + username);
|
||||
}
|
||||
String[] roleList = userStoreManager.getRoleListOfUser(username);
|
||||
for (String role : roleList) {
|
||||
if (role != null && role.contains("Internal/group-" + groupId)) {
|
||||
@ -553,6 +566,9 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
}
|
||||
return groupRoleList;
|
||||
} catch (UserStoreException e) {
|
||||
if (e instanceof UserDoesNotExistException) {
|
||||
throw (UserDoesNotExistException) e;
|
||||
}
|
||||
throw new GroupManagementException("Error occurred while getting user store manager.", e);
|
||||
}
|
||||
}
|
||||
@ -723,7 +739,8 @@ public class GroupManagementProviderServiceImpl implements GroupManagementProvid
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
@Override
|
||||
public String[] getPermissions(String username, String groupName, String owner) throws GroupManagementException {
|
||||
public String[] getPermissions(String username, String groupName, String owner)
|
||||
throws GroupManagementException, UserDoesNotExistException {
|
||||
UserRealm userRealm;
|
||||
int groupId = getGroupId(groupName, owner);
|
||||
List<String> roles = getRoles(username, groupId);
|
||||
|
||||
@ -1,228 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
|
||||
<parent>
|
||||
<artifactId>device-mgt</artifactId>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<version>1.1.0-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>org.wso2.carbon.device.mgt.etc</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>WSO2 Carbon - Common Application Admin</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<configuration>
|
||||
<source>1.7</source>
|
||||
<target>1.7</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project.artifactId}</Bundle-Name>
|
||||
<Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
|
||||
<Bundle-Description>CDMF Common API Impl Bundle</Bundle-Description>
|
||||
<Private-Package>org.wso2.carbon.device.mgt.etc.internal</Private-Package>
|
||||
<Import-Package>
|
||||
org.jivesoftware.smack.*,
|
||||
javax.xml.namespace;resolution:=optional,
|
||||
javax.xml.validation;resolution:=optional,
|
||||
org.apache.commons.codec.binary,
|
||||
org.apache.commons.collections.map,
|
||||
org.apache.http.*,
|
||||
org.apache.commons.io.*,
|
||||
org.apache.commons.logging.*,
|
||||
org.json;version="${commons-json.version}",
|
||||
org.wso2.carbon.base.*,
|
||||
org.wso2.carbon.databridge.*,
|
||||
org.wso2.carbon.user.api,
|
||||
org.wso2.carbon.user.core.service,
|
||||
org.osgi.framework,
|
||||
org.osgi.service.component,
|
||||
javax.xml.bind.*;resolution:=optional,
|
||||
javax.naming;resolution:=optional,
|
||||
javax.sql;resolution:=optional,
|
||||
javax.xml.bind.annotation.*;resolution:=optional,
|
||||
javax.xml.parsers.*;resolution:=optional,
|
||||
javax.net;resolution:=optional,
|
||||
javax.net.ssl;resolution:=optional,
|
||||
org.w3c.dom;resolution:=optional,
|
||||
org.wso2.carbon.core;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.utils.*;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.device.mgt.group.common.*,
|
||||
org.wso2.carbon.device.mgt.group.core.*,
|
||||
org.wso2.carbon.device.mgt.common.*,
|
||||
org.wso2.carbon.device.mgt.core.*,
|
||||
org.wso2.carbon.context.*;version="${carbon.kernel.version.range}",
|
||||
org.wso2.carbon.ndatasource.core;version="${carbon.kernel.version.range}",
|
||||
org.eclipse.paho.client.mqttv3.*;version="${eclipse.paho.version}",
|
||||
javax.xml,
|
||||
org.wso2.carbon.user.core;version="${carbon.kernel.version.range}"
|
||||
</Import-Package>
|
||||
<Export-Package>
|
||||
!org.wso2.carbon.device.mgt.etc.internal,
|
||||
org.wso2.carbon.device.mgt.etc.*;version="${project.version}"
|
||||
</Export-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!--<plugin>-->
|
||||
<!--<groupId>org.apache.maven.plugins</groupId>-->
|
||||
<!--<artifactId>maven-surefire-plugin</artifactId>-->
|
||||
<!--<version>2.18</version>-->
|
||||
<!--<configuration>-->
|
||||
<!--<systemPropertyVariables>-->
|
||||
<!--<log4j.configuration>file:src/test/resources/log4j.properties-->
|
||||
<!--</log4j.configuration>-->
|
||||
<!--</systemPropertyVariables>-->
|
||||
<!--<suiteXmlFiles>-->
|
||||
<!--<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>-->
|
||||
<!--</suiteXmlFiles>-->
|
||||
<!--</configuration>-->
|
||||
<!--</plugin>-->
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.policy.mgt.common</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>org.testng</groupId>-->
|
||||
<!--<artifactId>testng</artifactId>-->
|
||||
<!--</dependency>-->
|
||||
|
||||
<!--<dependency>-->
|
||||
<!--<groupId>com.h2database.wso2</groupId>-->
|
||||
<!--<artifactId>h2-database-engine</artifactId>-->
|
||||
<!--<scope>test</scope>-->
|
||||
<!--</dependency>-->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-collections.wso2</groupId>
|
||||
<artifactId>commons-collections</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-configuration</groupId>
|
||||
<artifactId>commons-configuration</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.agent</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.commons</groupId>
|
||||
<artifactId>org.wso2.carbon.databridge.commons</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--Dependencies on XMPP Client Library-->
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@ -1,61 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
public class AccessTokenInfo {
|
||||
|
||||
private String token_type;
|
||||
private int expires_in;
|
||||
private String refresh_token;
|
||||
private String access_token;
|
||||
|
||||
public String getToken_type() {
|
||||
return token_type;
|
||||
}
|
||||
|
||||
public void setToken_type(String token_type) {
|
||||
this.token_type = token_type;
|
||||
}
|
||||
|
||||
public int getExpires_in() {
|
||||
return expires_in;
|
||||
}
|
||||
|
||||
public void setExpires_in(int expres_in) {
|
||||
this.expires_in = expres_in;
|
||||
}
|
||||
|
||||
public String getRefresh_token() {
|
||||
return refresh_token;
|
||||
}
|
||||
|
||||
public void setRefresh_token(String refresh_token) {
|
||||
this.refresh_token = refresh_token;
|
||||
}
|
||||
|
||||
public String getAccess_token() {
|
||||
return access_token;
|
||||
}
|
||||
|
||||
public void setAccess_token(String access_token) {
|
||||
this.access_token = access_token;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -1,185 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ApiManagerConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.util.IoTUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class ApisAppClient {
|
||||
|
||||
private static ConcurrentHashMap<String, String> deviceTypeToApiAppMap = new ConcurrentHashMap<>();
|
||||
private static ApisAppClient instance =null;
|
||||
|
||||
private String loginEndpoint;
|
||||
private String subscriptionListEndpoint;
|
||||
private static Log log = LogFactory.getLog(ApisAppClient.class);
|
||||
private boolean isEnabled;
|
||||
|
||||
public static ApisAppClient getInstance(){
|
||||
|
||||
if(instance==null){
|
||||
instance= new ApisAppClient();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private ApisAppClient() {
|
||||
ApiManagerConfig apiManagerConfig =DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager();
|
||||
String serverUrl=apiManagerConfig.getServerURL();
|
||||
String serverPort=apiManagerConfig.getServerPort();
|
||||
isEnabled = apiManagerConfig.isEnabled();
|
||||
|
||||
String loginURL = serverUrl+":"+serverPort+apiManagerConfig.getLoginURL();
|
||||
loginEndpoint= loginURL+"?action=login&username="+apiManagerConfig.getUsername()
|
||||
+"&password="+apiManagerConfig.getPassword();
|
||||
|
||||
String subscriptionListUrl=serverUrl+":"+serverPort+apiManagerConfig.getSubscriptionListURL();
|
||||
subscriptionListEndpoint=subscriptionListUrl+"?action=getAllSubscriptions";
|
||||
}
|
||||
|
||||
public String getBase64EncodedConsumerKeyAndSecret(String deviceType) {
|
||||
if(!isEnabled) return null;
|
||||
String consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType);
|
||||
if(consumerKeyAndSecret == null){
|
||||
ArrayList<DeviceTypeConfig> iotDeviceTypeConfigs = new ArrayList<>();
|
||||
DeviceTypeConfig DeviceTypeConfig = DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap().get(deviceType);
|
||||
if(DeviceTypeConfig != null) {
|
||||
iotDeviceTypeConfigs.add(DeviceTypeConfig);
|
||||
setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigs);
|
||||
consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType);
|
||||
if(consumerKeyAndSecret==null){
|
||||
log.warn("There is no API application for the device type " + deviceType);
|
||||
}
|
||||
}
|
||||
}
|
||||
return consumerKeyAndSecret;
|
||||
}
|
||||
|
||||
public void setBase64EncodedConsumerKeyAndSecret(List<DeviceTypeConfig> iotDeviceTypeConfigList) {
|
||||
if(!isEnabled) return;
|
||||
|
||||
URL loginURL = null;
|
||||
try {
|
||||
loginURL = new URL(loginEndpoint);
|
||||
} catch (MalformedURLException e) {
|
||||
String errMsg = "Malformed URL " + loginEndpoint;
|
||||
log.error(errMsg);
|
||||
return;
|
||||
}
|
||||
HttpClient httpClient = null;
|
||||
try {
|
||||
httpClient = IoTUtil.getHttpClient(loginURL.getPort(), loginURL.getProtocol());
|
||||
} catch (Exception e) {
|
||||
log.error("Error on getting a http client for port :" + loginURL.getPort() + " protocol :"
|
||||
+ loginURL.getProtocol());
|
||||
return;
|
||||
}
|
||||
|
||||
HttpPost postMethod = new HttpPost(loginEndpoint);
|
||||
JSONObject apiJsonResponse;
|
||||
try {
|
||||
HttpResponse httpResponse = httpClient.execute(postMethod);
|
||||
String response = IoTUtil.getResponseString(httpResponse);
|
||||
if(log.isDebugEnabled()) {
|
||||
log.debug(response);
|
||||
}
|
||||
JSONObject jsonObject = new JSONObject(response);
|
||||
|
||||
|
||||
boolean apiError = jsonObject.getBoolean("error");
|
||||
if(!apiError){
|
||||
String cookie = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0];
|
||||
HttpGet getMethod=new HttpGet(subscriptionListEndpoint);
|
||||
getMethod.setHeader("cookie", cookie);
|
||||
httpResponse = httpClient.execute(getMethod);
|
||||
response = IoTUtil.getResponseString(httpResponse);
|
||||
|
||||
|
||||
if(log.isDebugEnabled()) {
|
||||
log.debug(response);
|
||||
}
|
||||
apiJsonResponse = new JSONObject(response);
|
||||
apiError=apiJsonResponse.getBoolean("error");
|
||||
if(apiError){
|
||||
log.error("invalid subscription endpoint "+subscriptionListEndpoint);
|
||||
return;
|
||||
}
|
||||
}else{
|
||||
log.error("invalid access for login endpoint " +loginEndpoint);
|
||||
return;
|
||||
}
|
||||
|
||||
} catch (IOException | JSONException | DeviceMgtCommonsException e) {
|
||||
log.warn("Trying to connect to the Api manager");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
JSONArray jsonSubscriptions = apiJsonResponse.getJSONObject("subscriptions").getJSONArray("applications");
|
||||
|
||||
HashMap<String, String> subscriptionMap = new HashMap<>();
|
||||
for (int n = 0; n < jsonSubscriptions.length(); n++) {
|
||||
|
||||
JSONObject object = jsonSubscriptions.getJSONObject(n);
|
||||
String appName = object.getString("name");
|
||||
String prodConsumerKey = object.getString("prodConsumerKey");
|
||||
String prodConsumerSecret = object.getString("prodConsumerSecret");
|
||||
subscriptionMap.put(appName, new String(Base64.encodeBase64(
|
||||
(prodConsumerKey + ":" + prodConsumerSecret).getBytes())));
|
||||
}
|
||||
|
||||
for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) {
|
||||
String deviceType = iotDeviceTypeConfig.getType();
|
||||
String deviceTypeApiApplicationName = iotDeviceTypeConfig.getApiApplicationName();
|
||||
String base64EncodedString = subscriptionMap.get(deviceTypeApiApplicationName);
|
||||
if (base64EncodedString != null && base64EncodedString.length() != 0) {
|
||||
deviceTypeToApiAppMap.put(deviceType, base64EncodedString);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (JSONException e) {
|
||||
log.error("Json exception: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@ -1,218 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DeviceCloudConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.datastore.impl.ThriftDataStoreConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.util.ResourceFileLoader;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.datastore.DataStoreConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.UnauthorizedException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceController {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceController.class);
|
||||
|
||||
private static HashMap<String, DataStoreConnector> dataStoresMap = new HashMap<>();
|
||||
private static HashMap<String, ControlQueueConnector> controlQueueMap = new HashMap<>();
|
||||
|
||||
public static void init() {
|
||||
DeviceCloudConfig config = DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig();
|
||||
|
||||
if (config != null) {
|
||||
initSecurity(config);
|
||||
loadDataStores(config);
|
||||
loadControlQueues(config);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private static void loadDataStores(DeviceCloudConfig config) {
|
||||
List<DataStore> dataStores = config.getDataStores().getDataStore();
|
||||
if (dataStores == null) {
|
||||
log.error("Error occurred when trying to read data stores configurations");
|
||||
return;
|
||||
}
|
||||
|
||||
for (DataStore dataStore : dataStores) {
|
||||
try {
|
||||
String handlerClass = dataStore.getPublisherClass();
|
||||
|
||||
Class<?> dataStoreClass = Class.forName(handlerClass);
|
||||
if (DataStoreConnector.class.isAssignableFrom(dataStoreClass)) {
|
||||
|
||||
DataStoreConnector dataStoreConnector =
|
||||
(DataStoreConnector) dataStoreClass.newInstance();
|
||||
String dataStoreName = dataStore.getName();
|
||||
if (dataStore.isEnabled()) {
|
||||
dataStoresMap.put(dataStoreName, dataStoreConnector);
|
||||
dataStoreConnector.initDataStore(dataStore);
|
||||
}
|
||||
}
|
||||
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
|
||||
log.error("Error occurred when trying to initiate data store", ex);
|
||||
} catch (DeviceControllerException ex) {
|
||||
log.error(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void loadControlQueues(DeviceCloudConfig config) {
|
||||
List<ControlQueue> controlQueues = config.getControlQueues().getControlQueue();
|
||||
if (controlQueues == null) {
|
||||
log.error("Error occurred when trying to read control queue configurations");
|
||||
return;
|
||||
}
|
||||
|
||||
for (ControlQueue controlQueue : controlQueues) {
|
||||
try {
|
||||
String handlerClass = controlQueue.getControlClass();
|
||||
|
||||
Class<?> controlQueueClass = Class.forName(handlerClass);
|
||||
if (ControlQueueConnector.class.isAssignableFrom(controlQueueClass)) {
|
||||
|
||||
ControlQueueConnector controlQueueConnector =
|
||||
(ControlQueueConnector) controlQueueClass.newInstance();
|
||||
String controlQueueName = controlQueue.getName();
|
||||
if (controlQueue.isEnabled()) {
|
||||
controlQueueMap.put(controlQueueName, controlQueueConnector);
|
||||
controlQueueConnector.initControlQueue();
|
||||
}
|
||||
}
|
||||
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {
|
||||
log.error("Error occurred when trying to initiate control queue" +
|
||||
controlQueue.getName());
|
||||
} catch (DeviceControllerException ex) {
|
||||
log.error(ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void initSecurity(DeviceCloudConfig config) {
|
||||
String trustStoreFile = null;
|
||||
String trustStorePassword = null;
|
||||
File certificateFile = null;
|
||||
|
||||
trustStoreFile = config.getSecurity().getClientTrustStore();
|
||||
trustStorePassword = config.getSecurity().getPassword();
|
||||
String certificatePath =
|
||||
CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator +
|
||||
"resources" + File.separator + "security" + File.separator;
|
||||
|
||||
certificateFile = new ResourceFileLoader(certificatePath + trustStoreFile).getFile();
|
||||
if (certificateFile.exists()) {
|
||||
trustStoreFile = certificateFile.getAbsolutePath();
|
||||
log.info("Trust Store Path : " + trustStoreFile);
|
||||
|
||||
System.setProperty("javax.net.ssl.trustStore", trustStoreFile);
|
||||
System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
|
||||
} else {
|
||||
log.error("Trust Store not found in path : " + certificateFile.getAbsolutePath());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean publishMqttControl(String owner, String deviceType, String deviceId, String key,
|
||||
String value) throws DeviceControllerException {
|
||||
HashMap<String, String> deviceControlsMap = new HashMap<String, String>();
|
||||
|
||||
deviceControlsMap.put("owner", owner);
|
||||
deviceControlsMap.put("deviceType", deviceType);
|
||||
deviceControlsMap.put("deviceId", deviceId);
|
||||
deviceControlsMap.put("key", key);
|
||||
deviceControlsMap.put("value", value);
|
||||
|
||||
|
||||
ControlQueueConnector mqttControlQueue = controlQueueMap.get(MqttConfig.getMqttQueueConfigName());
|
||||
if (mqttControlQueue == null) {
|
||||
log.info("MQTT Queue has not been listed in 'device-mgt-config.xml'");
|
||||
return false;
|
||||
}
|
||||
|
||||
mqttControlQueue.enqueueControls(deviceControlsMap);
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean pushData(HashMap<String, String> deviceDataMap, String publisherType)
|
||||
throws DeviceControllerException {
|
||||
|
||||
DataStoreConnector dataStoreConnector = dataStoresMap.get(publisherType);
|
||||
if (dataStoreConnector == null) {
|
||||
log.error(publisherType + " is not enabled");
|
||||
return false;
|
||||
}
|
||||
|
||||
dataStoreConnector.publishDeviceData(deviceDataMap);
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean pushBamData(String owner, String deviceType, String deviceId, Long time,
|
||||
String key,
|
||||
String value, String description) throws UnauthorizedException {
|
||||
|
||||
HashMap<String, String> deviceDataMap = new HashMap<String, String>();
|
||||
|
||||
deviceDataMap.put("owner", owner);
|
||||
deviceDataMap.put("deviceType", deviceType);
|
||||
deviceDataMap.put("deviceId", deviceId);
|
||||
deviceDataMap.put("time", "" + time);
|
||||
deviceDataMap.put("key", key);
|
||||
deviceDataMap.put("value", value);
|
||||
deviceDataMap.put("description", description);
|
||||
|
||||
try {
|
||||
return pushData(deviceDataMap, ThriftDataStoreConnector.DataStoreConstants.BAM);
|
||||
} catch (DeviceControllerException e) {
|
||||
throw new UnauthorizedException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean pushCepData(String owner, String deviceType, String deviceId, Long time,
|
||||
String key,
|
||||
String value, String description)
|
||||
throws UnauthorizedException {
|
||||
HashMap<String, String> deviceDataMap = new HashMap<String, String>();
|
||||
|
||||
deviceDataMap.put("owner", owner);
|
||||
deviceDataMap.put("deviceType", deviceType);
|
||||
deviceDataMap.put("deviceId", deviceId);
|
||||
deviceDataMap.put("time", "" + time);
|
||||
deviceDataMap.put("key", key);
|
||||
deviceDataMap.put("value", value);
|
||||
deviceDataMap.put("description", description);
|
||||
|
||||
try {
|
||||
return pushData(deviceDataMap, ThriftDataStoreConnector.DataStoreConstants.CEP);
|
||||
} catch (DeviceControllerException e) {
|
||||
throw new UnauthorizedException(e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,122 +0,0 @@
|
||||
/*
|
||||
c * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.etc.util.DeviceTypes;
|
||||
import org.wso2.carbon.device.mgt.etc.util.ZipArchive;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil;
|
||||
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException;
|
||||
import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.core.dto.DeviceType;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class DeviceManagement {
|
||||
|
||||
private static Log log = LogFactory.getLog(DeviceManagement.class);
|
||||
|
||||
public DeviceManagement(String tenantDomain){
|
||||
}
|
||||
|
||||
public boolean isExist(String owner, DeviceIdentifier deviceIdentifier)
|
||||
throws DeviceManagementException {
|
||||
|
||||
DeviceManagementProviderService dmService = getDeviceManagementService();
|
||||
if (dmService.isEnrolled(deviceIdentifier)) {
|
||||
Device device=dmService.getDevice(deviceIdentifier);
|
||||
if (device.getEnrolmentInfo().getOwner().equals(owner)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public DeviceManagementProviderService getDeviceManagementService() {
|
||||
return (DeviceManagementProviderService) CarbonContext.getThreadLocalCarbonContext().getOSGiService(
|
||||
DeviceManagementProviderService.class, null);
|
||||
}
|
||||
|
||||
public Device[] getActiveDevices(String username)
|
||||
throws DeviceManagementException {
|
||||
List<Device> devices = getDeviceManagementService().getDevicesOfUser(
|
||||
username);
|
||||
List<Device> activeDevices = new ArrayList<>();
|
||||
if (devices != null) {
|
||||
for (Device device : devices) {
|
||||
if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
|
||||
activeDevices.add(device);
|
||||
}
|
||||
}
|
||||
}
|
||||
return activeDevices.toArray(new Device[activeDevices.size()]);
|
||||
}
|
||||
|
||||
public int getActiveDeviceCount(String username)
|
||||
throws DeviceManagementException {
|
||||
List<Device> devices = getDeviceManagementService().getDevicesOfUser(username);
|
||||
|
||||
if (devices != null) {
|
||||
List<Device> activeDevices = new ArrayList<>();
|
||||
for (Device device : devices) {
|
||||
if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
|
||||
activeDevices.add(device);
|
||||
}
|
||||
}
|
||||
return activeDevices.size();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams)
|
||||
throws DeviceManagementException {
|
||||
/* create a context and add data */
|
||||
try {
|
||||
return IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath,
|
||||
contextParams);
|
||||
} catch (IOException e) {
|
||||
throw new DeviceManagementException("Zip File Creation Failed",e);
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceTypes[] getDeviceTypes(int tenantId) throws DeviceManagementDAOException {
|
||||
List<DeviceType> deviceTypes = DeviceManagementDAOFactory.getDeviceTypeDAO().getDeviceTypes(tenantId);
|
||||
DeviceTypes dTypes[] = new DeviceTypes[deviceTypes.size()];
|
||||
int iter = 0;
|
||||
for (DeviceType type : deviceTypes) {
|
||||
|
||||
DeviceTypes dt = new DeviceTypes();
|
||||
dt.setName(type.getName());
|
||||
dTypes[iter] = dt;
|
||||
iter++;
|
||||
}
|
||||
return dTypes;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,106 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
import org.apache.commons.collections.map.LRUMap;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
|
||||
|
||||
public class DeviceValidator {
|
||||
|
||||
private static Log log = LogFactory.getLog(DeviceValidator.class);
|
||||
private static LRUMap cache;
|
||||
|
||||
// private static Log log = LogFactory.getLog(DeviceValidator.class);
|
||||
static {
|
||||
int cacheSize = DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getDeviceUserValidator()
|
||||
.getCacheSize();
|
||||
cache = new LRUMap(cacheSize);
|
||||
}
|
||||
|
||||
private PrivilegedCarbonContext ctx;
|
||||
|
||||
public boolean isExist(String owner, String tenantDomain, DeviceIdentifier deviceId)
|
||||
throws DeviceManagementException {
|
||||
return true;
|
||||
//TODO check cache impl
|
||||
//return cacheCheck(owner,tenantDomain, deviceId);
|
||||
}
|
||||
|
||||
private boolean cacheCheck(String owner, String tenantDomain, DeviceIdentifier deviceId)
|
||||
throws DeviceManagementException {
|
||||
|
||||
String value = (String) cache.get(deviceId);
|
||||
|
||||
if (value != null && !value.isEmpty()) {
|
||||
return value.equals(owner);
|
||||
} else {
|
||||
boolean status = isExist(owner, deviceId);
|
||||
if (status) {
|
||||
addToCache(owner, deviceId);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
private void addToCache(String owner, DeviceIdentifier deviceId) {
|
||||
cache.put(deviceId, owner);
|
||||
}
|
||||
|
||||
private boolean isExist(String owner, DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
|
||||
try {
|
||||
DeviceManagementProviderService dmService = getServiceProvider();
|
||||
if (dmService.isEnrolled(deviceIdentifier)) {
|
||||
Device device = dmService.getDevice(deviceIdentifier);
|
||||
if (device.getEnrolmentInfo().getOwner().equals(owner)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
} finally {
|
||||
endTenantFlow();
|
||||
}
|
||||
}
|
||||
|
||||
private DeviceManagementProviderService getServiceProvider() {
|
||||
String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
ctx.setTenantDomain(tenantDomain, true);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain);
|
||||
}
|
||||
return (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
|
||||
}
|
||||
|
||||
private void endTenantFlow() {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
ctx = null;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Tenant flow ended");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,240 +0,0 @@
|
||||
package org.wso2.carbon.device.mgt.etc;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.context.CarbonContext;
|
||||
import org.wso2.carbon.device.mgt.etc.util.Role;
|
||||
import org.wso2.carbon.device.mgt.etc.util.User;
|
||||
import org.wso2.carbon.user.api.Claim;
|
||||
import org.wso2.carbon.user.api.Permission;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
import org.wso2.carbon.user.api.UserStoreManager;
|
||||
import org.wso2.carbon.user.core.UserCoreConstants;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class UserManagement {
|
||||
private static Log log = LogFactory.getLog(UserManagement.class);
|
||||
|
||||
public static final String GIVEN_NAME = UserCoreConstants.ClaimTypeURIs.GIVEN_NAME;
|
||||
public static final String EMAIL_ADDRESS = UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS;
|
||||
public static final String SURNAME = UserCoreConstants.ClaimTypeURIs.SURNAME;
|
||||
public static final String STREET_ADDRESS = UserCoreConstants.ClaimTypeURIs.STREET_ADDRESS;
|
||||
public static final String LOCALITY = UserCoreConstants.ClaimTypeURIs.LOCALITY;
|
||||
public static final String REGION = UserCoreConstants.ClaimTypeURIs.REGION;
|
||||
public static final String POSTAL_CODE = UserCoreConstants.ClaimTypeURIs.POSTAL_CODE;
|
||||
public static final String COUNTRY = UserCoreConstants.ClaimTypeURIs.COUNTRY;
|
||||
public static final String HONE = UserCoreConstants.ClaimTypeURIs.HONE;
|
||||
public static final String IM = UserCoreConstants.ClaimTypeURIs.IM;
|
||||
public static final String ORGANIZATION = UserCoreConstants.ClaimTypeURIs.ORGANIZATION;
|
||||
public static final String URL = UserCoreConstants.ClaimTypeURIs.URL;
|
||||
public static final String TITLE = UserCoreConstants.ClaimTypeURIs.TITLE;
|
||||
public static final String ROLE = UserCoreConstants.ClaimTypeURIs.ROLE;
|
||||
public static final String MOBILE = UserCoreConstants.ClaimTypeURIs.MOBILE;
|
||||
public static final String NICKNAME = UserCoreConstants.ClaimTypeURIs.NICKNAME;
|
||||
public static final String DATE_OF_BIRTH = UserCoreConstants.ClaimTypeURIs.DATE_OF_BIRTH;
|
||||
public static final String GENDER = UserCoreConstants.ClaimTypeURIs.GENDER;
|
||||
public static final String ACCOUNT_STATUS = UserCoreConstants.ClaimTypeURIs.ACCOUNT_STATUS;
|
||||
public static final String CHALLENGE_QUESTION_URI
|
||||
= UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI;
|
||||
public static final String IDENTITY_CLAIM_URI
|
||||
= UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI;
|
||||
public static final String TEMPORARY_EMAIL_ADDRESS
|
||||
= UserCoreConstants.ClaimTypeURIs.TEMPORARY_EMAIL_ADDRESS;
|
||||
|
||||
private static final String DEVICE_API_ACCESS_ROLE_NAME="deviceRole";
|
||||
private static final String DEVICE_USER_API_ACCESS_ROLE_NAME="deviceUser";
|
||||
private static RealmService realmService;
|
||||
|
||||
public static RealmService getRealmService() {
|
||||
return realmService;
|
||||
}
|
||||
|
||||
public static void setRealmService(RealmService realmService) {
|
||||
UserManagement.realmService = realmService;
|
||||
}
|
||||
|
||||
public int getUserCount() {
|
||||
|
||||
try {
|
||||
String[] users = getUserStoreManager().listUsers("", -1);
|
||||
if (users == null) {
|
||||
return 0;
|
||||
}
|
||||
return users.length;
|
||||
} catch (UserStoreException e) {
|
||||
String msg
|
||||
=
|
||||
"Error occurred while retrieving the list of users that exist within the " +
|
||||
"current tenant";
|
||||
log.error(msg, e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
//===========================================================================
|
||||
//TODO: Below methods are implemented to support jaggery code upon removal of org.wso2.carbon
|
||||
// .device.mgt.user.core from CDMF
|
||||
//===========================================================================
|
||||
|
||||
private static UserStoreManager getUserStoreManager() throws UserStoreException {
|
||||
|
||||
UserStoreManager userStoreManager;
|
||||
try {
|
||||
|
||||
if (realmService == null) {
|
||||
String msg = "Realm service not initialized";
|
||||
log.error(msg);
|
||||
throw new UserStoreException(msg);
|
||||
}
|
||||
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
|
||||
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
|
||||
} catch (UserStoreException e) {
|
||||
String msg = "Error occurred while retrieving current user store manager";
|
||||
log.error(msg, e);
|
||||
throw new UserStoreException(msg, e);
|
||||
} finally {
|
||||
//PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
return userStoreManager;
|
||||
|
||||
|
||||
}
|
||||
|
||||
public List<User> getUsersForTenantAndRole(int tenantId, String roleName)
|
||||
throws UserStoreException {
|
||||
|
||||
UserStoreManager userStoreManager = getUserStoreManager();
|
||||
String[] userNames;
|
||||
ArrayList usersList = new ArrayList();
|
||||
|
||||
userNames = userStoreManager.getUserListOfRole(roleName);
|
||||
User newUser;
|
||||
for (String userName : userNames) {
|
||||
newUser = new User(userName);
|
||||
Claim[] claims = userStoreManager.getUserClaimValues(userName, null);
|
||||
Map<String, String> claimMap = new HashMap<String, String>();
|
||||
for (Claim claim : claims) {
|
||||
String claimURI = claim.getClaimUri();
|
||||
String value = claim.getValue();
|
||||
claimMap.put(claimURI, value);
|
||||
}
|
||||
setUserClaims(newUser, claimMap);
|
||||
usersList.add(newUser);
|
||||
}
|
||||
|
||||
return usersList;
|
||||
}
|
||||
|
||||
public List<Role> getRolesForTenant(int tenantId) throws UserStoreException {
|
||||
|
||||
String[] roleNames;
|
||||
ArrayList<Role> rolesList = new ArrayList<Role>();
|
||||
Role newRole;
|
||||
UserStoreManager userStoreManager = getUserStoreManager();
|
||||
|
||||
roleNames = userStoreManager.getRoleNames();
|
||||
for (String roleName : roleNames) {
|
||||
newRole = new Role(roleName);
|
||||
rolesList.add(newRole);
|
||||
}
|
||||
|
||||
return rolesList;
|
||||
}
|
||||
|
||||
public List<User> getUsersForTenant(int tenantId) throws UserStoreException {
|
||||
|
||||
UserStoreManager userStoreManager;
|
||||
String[] userNames;
|
||||
ArrayList usersList = new ArrayList();
|
||||
|
||||
userStoreManager = getUserStoreManager();
|
||||
|
||||
userNames = userStoreManager.listUsers("", -1);
|
||||
User newUser;
|
||||
for (String userName : userNames) {
|
||||
newUser = new User(userName);
|
||||
Claim[] claims = userStoreManager.getUserClaimValues(userName, null);
|
||||
Map<String, String> claimMap = new HashMap<String, String>();
|
||||
for (Claim claim : claims) {
|
||||
String claimURI = claim.getClaimUri();
|
||||
String value = claim.getValue();
|
||||
claimMap.put(claimURI, value);
|
||||
}
|
||||
setUserClaims(newUser, claimMap);
|
||||
usersList.add(newUser);
|
||||
}
|
||||
|
||||
return usersList;
|
||||
}
|
||||
|
||||
public User getUser(String username, int tenantId) throws UserStoreException {
|
||||
UserStoreManager userStoreManager;
|
||||
User user;
|
||||
userStoreManager = getUserStoreManager();
|
||||
user = new User(username);
|
||||
|
||||
Claim[] claims = userStoreManager.getUserClaimValues(username, null);
|
||||
Map<String, String> claimMap = new HashMap<String, String>();
|
||||
for (Claim claim : claims) {
|
||||
String claimURI = claim.getClaimUri();
|
||||
String value = claim.getValue();
|
||||
claimMap.put(claimURI, value);
|
||||
}
|
||||
|
||||
setUserClaims(user, claimMap);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
private void setUserClaims(User newUser, Map<String, String> claimMap) {
|
||||
newUser.setRoleName(UserCoreConstants.ClaimTypeURIs.ROLE);
|
||||
newUser.setAccountStatus(claimMap.get(ACCOUNT_STATUS));
|
||||
newUser.setChallengeQuestion(claimMap.get(CHALLENGE_QUESTION_URI));
|
||||
newUser.setCountry(claimMap.get(COUNTRY));
|
||||
newUser.setDateOfBirth(claimMap.get(DATE_OF_BIRTH));
|
||||
newUser.setEmail(claimMap.get(EMAIL_ADDRESS));
|
||||
newUser.setFirstName(claimMap.get(GIVEN_NAME));
|
||||
newUser.setGender(claimMap.get(GENDER));
|
||||
newUser.setHone(claimMap.get(HONE));
|
||||
newUser.setIm(claimMap.get(IM));
|
||||
newUser.setIdentityClaimUri(claimMap.get(IDENTITY_CLAIM_URI));
|
||||
newUser.setLastName(claimMap.get(SURNAME));
|
||||
newUser.setLocality(claimMap.get(LOCALITY));
|
||||
newUser.setEmail(claimMap.get(EMAIL_ADDRESS));
|
||||
newUser.setMobile(claimMap.get(MOBILE));
|
||||
newUser.setNickName(claimMap.get(NICKNAME));
|
||||
newUser.setOrganization(claimMap.get(ORGANIZATION));
|
||||
newUser.setPostalCode(claimMap.get(POSTAL_CODE));
|
||||
newUser.setRegion(claimMap.get(REGION));
|
||||
newUser.setStreatAddress(claimMap.get(STREET_ADDRESS));
|
||||
newUser.setTitle(claimMap.get(TITLE));
|
||||
newUser.setTempEmailAddress(claimMap.get(TEMPORARY_EMAIL_ADDRESS));
|
||||
}
|
||||
|
||||
public static void registerApiAccessRoles() {
|
||||
UserStoreManager userStoreManager = null;
|
||||
try {
|
||||
userStoreManager = getUserStoreManager();
|
||||
String[] userList = new String[]{"admin"};
|
||||
Permission permissions[] = new Permission[]{};
|
||||
if (!userStoreManager.isExistingRole(DEVICE_API_ACCESS_ROLE_NAME)) {
|
||||
userStoreManager.addRole(DEVICE_API_ACCESS_ROLE_NAME, userList, permissions);
|
||||
}
|
||||
if (!userStoreManager.isExistingRole(DEVICE_USER_API_ACCESS_ROLE_NAME)) {
|
||||
userStoreManager.addRole(DEVICE_USER_API_ACCESS_ROLE_NAME, userList, permissions);
|
||||
}
|
||||
} catch (UserStoreException e) {
|
||||
log.error("error on wso2 user component");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.impl.analytics.statistics;
|
||||
|
||||
public class DeviceEventsStatisticsException extends Exception{
|
||||
|
||||
private static final long serialVersionUID = -5743346027793277063L;
|
||||
|
||||
public DeviceEventsStatisticsException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public DeviceEventsStatisticsException(String msg, Throwable e) {
|
||||
super(msg, e);
|
||||
}
|
||||
|
||||
public DeviceEventsStatisticsException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
||||
@ -1,139 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.impl.analytics.statistics;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.impl.analytics.statistics.dto.DeviceEventsDTO;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceMgtEventsStatisticsClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceMgtEventsStatisticsClient.class);
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB";
|
||||
|
||||
private static volatile DataSource dataSource = null;
|
||||
|
||||
|
||||
public static void initializeDataSource() throws DeviceEventsStatisticsException {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
|
||||
} catch (NamingException e) {
|
||||
throw new DeviceEventsStatisticsException("Error while looking up the data " +
|
||||
"source: " + DATA_SOURCE_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public List<DeviceEventsDTO> getRecentDeviceStats(String owner, int recordLimit)
|
||||
throws DeviceEventsStatisticsException {
|
||||
|
||||
if (dataSource == null) {
|
||||
throw new DeviceEventsStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration.");
|
||||
}
|
||||
|
||||
Connection connection = null;
|
||||
Statement statement = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
connection = dataSource.getConnection();
|
||||
statement = connection.createStatement();
|
||||
String query = null;
|
||||
String table = "DEVICE_EVENTS";
|
||||
|
||||
if(owner==null){
|
||||
throw new DeviceEventsStatisticsException("Owner cannot be null!");
|
||||
}
|
||||
|
||||
String ownerString = "";
|
||||
ownerString = String.format(" AND owner = '%s'", owner);
|
||||
|
||||
String limitString = "";
|
||||
if(recordLimit > 0){
|
||||
limitString = String.format(" LIMIT %d", recordLimit);
|
||||
}
|
||||
|
||||
query = String.format("SELECT * FROM %s WHERE 1=1 %s ORDER BY `time` DESC %s"
|
||||
,table, ownerString, limitString);
|
||||
|
||||
log.info("query: " + query);
|
||||
|
||||
if (query == null) {
|
||||
throw new DeviceEventsStatisticsException("SQL query is null!");
|
||||
}
|
||||
|
||||
List<DeviceEventsDTO> DeviceEventsDTOs = new ArrayList<DeviceEventsDTO>();
|
||||
rs = statement.executeQuery(query);
|
||||
while (rs.next()) {
|
||||
DeviceEventsDTO DeviceEventsDTO = new DeviceEventsDTO();
|
||||
DeviceEventsDTO.setTime(rs.getString("TIME"));
|
||||
DeviceEventsDTO.setDeviceActivity(rs.getString("ACTIVITY"));
|
||||
//(id + type) uniquely identifies a device
|
||||
DeviceEventsDTO.setDeviceId(rs.getString("DEVICEID"));
|
||||
DeviceEventsDTO.setDeviceType(rs.getString("DEVICETYPE"));
|
||||
|
||||
DeviceEventsDTOs.add(DeviceEventsDTO);
|
||||
|
||||
}
|
||||
|
||||
return DeviceEventsDTOs;
|
||||
|
||||
} catch (Exception e) {
|
||||
// throw new IoTEventsStatisticsException(
|
||||
// "Error occurred while querying from JDBC database", e);
|
||||
//Exception hiding to avoid GC error
|
||||
log.error("Error occurred while querying from JDBC database: " + e.getMessage());
|
||||
return new ArrayList<>();
|
||||
} finally {
|
||||
if (rs != null) {
|
||||
try {
|
||||
rs.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (statement != null) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,176 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.impl.analytics.statistics;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.impl.analytics.statistics.dto.DeviceUsageDTO;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceMgtUsageStatisticsClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceMgtUsageStatisticsClient.class);
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB";
|
||||
|
||||
private static volatile DataSource dataSource = null;
|
||||
|
||||
|
||||
public static void initializeDataSource() throws DeviceUsageStatisticsException {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
|
||||
} catch (NamingException e) {
|
||||
throw new DeviceUsageStatisticsException("Error while looking up the data " +
|
||||
"source: " + DATA_SOURCE_NAME);
|
||||
}
|
||||
}
|
||||
//
|
||||
// public List<DeviceUsageDTO> getTemperatureData(String user, String deviceId, String fromDate,
|
||||
// String toDate)
|
||||
// throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching temperature data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
//
|
||||
// public List<DeviceUsageDTO> getBulbStatusData(String user, String deviceId, String fromDate,
|
||||
// String toDate)
|
||||
// throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching bulb status data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_BULB_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
//
|
||||
// public List<DeviceUsageDTO> getFanStatusData(String user, String deviceId, String fromDate,
|
||||
// String toDate) throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching fan status data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_FAN_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
|
||||
public List<DeviceUsageDTO> getDeviceStats(String table, String valueColumn, String owner,
|
||||
String deviceId, String fromDate, String toDate)
|
||||
throws DeviceUsageStatisticsException {
|
||||
|
||||
if (dataSource == null) {
|
||||
throw new DeviceUsageStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration.");
|
||||
}
|
||||
|
||||
Connection connection = null;
|
||||
Statement statement = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
connection = dataSource.getConnection();
|
||||
statement = connection.createStatement();
|
||||
String query = null;
|
||||
|
||||
String ownerString = "";
|
||||
if (owner != null) {
|
||||
ownerString = String.format("owner = '%s' AND ", owner);
|
||||
}
|
||||
|
||||
if (fromDate != null && toDate != null) {
|
||||
//fromDate = getConvertedTime(fromDate);
|
||||
//toDate = getConvertedTime(toDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` "
|
||||
+ "BETWEEN '%s' AND '%s'", table, deviceId, fromDate, toDate);
|
||||
} else if (fromDate != null) {
|
||||
//fromDate = getConvertedTime(fromDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` >= "
|
||||
+ "'%s'", table, deviceId, fromDate);
|
||||
} else if (toDate != null) {
|
||||
//toDate = getConvertedTime(toDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` <= "
|
||||
+ "'%s'", table, deviceId, toDate);
|
||||
}
|
||||
|
||||
log.info("query: " + query);
|
||||
|
||||
if (query == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<DeviceUsageDTO> deviceUsageDTOs = new ArrayList<DeviceUsageDTO>();
|
||||
rs = statement.executeQuery(query);
|
||||
while (rs.next()) {
|
||||
DeviceUsageDTO deviceUsageDTO = new DeviceUsageDTO();
|
||||
deviceUsageDTO.setTime(rs.getString("TIME"));
|
||||
deviceUsageDTO.setValue(rs.getString(valueColumn));
|
||||
|
||||
deviceUsageDTOs.add(deviceUsageDTO);
|
||||
|
||||
}
|
||||
|
||||
return deviceUsageDTOs;
|
||||
|
||||
} catch (Exception e) {
|
||||
// throw new IoTUsageStatisticsException(
|
||||
// "Error occurred while querying from JDBC database", e);
|
||||
//Exception hiding to avoid GC error
|
||||
log.error("Error occurred while querying from JDBC database: " + e.getMessage());
|
||||
return new ArrayList<>();
|
||||
} finally {
|
||||
if (rs != null) {
|
||||
try {
|
||||
rs.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (statement != null) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.impl.analytics.statistics;
|
||||
|
||||
public class DeviceUsageStatisticsException extends Exception{
|
||||
|
||||
private static final long serialVersionUID = -5743346027793277063L;
|
||||
|
||||
public DeviceUsageStatisticsException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public DeviceUsageStatisticsException(String msg, Throwable e) {
|
||||
super(msg, e);
|
||||
}
|
||||
|
||||
public DeviceUsageStatisticsException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
||||
@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.common.impl.analytics.statistics.dto;
|
||||
|
||||
public class DeviceEventsDTO {
|
||||
|
||||
private String time;
|
||||
private String deviceId;
|
||||
private String deviceType;
|
||||
private String deviceActivity;
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getDeviceActivity() {
|
||||
return deviceActivity;
|
||||
}
|
||||
|
||||
public void setDeviceActivity(String deviceActivity) {
|
||||
this.deviceActivity = deviceActivity;
|
||||
}
|
||||
|
||||
public void setDeviceId(String deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public String getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public String getDeviceType() {
|
||||
return deviceType;
|
||||
}
|
||||
|
||||
public void setDeviceType(String deviceType) {
|
||||
this.deviceType = deviceType;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.apimgt;
|
||||
|
||||
public class AccessTokenInfo {
|
||||
|
||||
private String token_type;
|
||||
private int expires_in;
|
||||
private String refresh_token;
|
||||
private String access_token;
|
||||
|
||||
public String getToken_type() {
|
||||
return token_type;
|
||||
}
|
||||
|
||||
public void setToken_type(String token_type) {
|
||||
this.token_type = token_type;
|
||||
}
|
||||
|
||||
public int getExpires_in() {
|
||||
return expires_in;
|
||||
}
|
||||
|
||||
public void setExpires_in(int expres_in) {
|
||||
this.expires_in = expres_in;
|
||||
}
|
||||
|
||||
public String getRefresh_token() {
|
||||
return refresh_token;
|
||||
}
|
||||
|
||||
public void setRefresh_token(String refresh_token) {
|
||||
this.refresh_token = refresh_token;
|
||||
}
|
||||
|
||||
public String getAccess_token() {
|
||||
return access_token;
|
||||
}
|
||||
|
||||
public void setAccess_token(String access_token) {
|
||||
this.access_token = access_token;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,182 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.etc.apimgt;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ApiManagerConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException;
|
||||
import org.wso2.carbon.device.mgt.etc.util.IoTUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public class ApisAppClient {
|
||||
|
||||
private static ConcurrentHashMap<String, String> deviceTypeToApiAppMap = new ConcurrentHashMap<>();
|
||||
private static ApisAppClient instance = null;
|
||||
|
||||
private String loginEndpoint;
|
||||
private String subscriptionListEndpoint;
|
||||
private static Log log = LogFactory.getLog(ApisAppClient.class);
|
||||
private boolean isEnabled;
|
||||
|
||||
public static ApisAppClient getInstance() {
|
||||
|
||||
if (instance == null) {
|
||||
instance = new ApisAppClient();
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private ApisAppClient() {
|
||||
ApiManagerConfig apiManagerConfig =
|
||||
DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager();
|
||||
String serverUrl = apiManagerConfig.getServerURL();
|
||||
String serverPort = apiManagerConfig.getServerPort();
|
||||
isEnabled = apiManagerConfig.isEnabled();
|
||||
|
||||
String loginURL = serverUrl + ":" + serverPort + apiManagerConfig.getLoginURL();
|
||||
loginEndpoint = loginURL + "?action=login&username=" + apiManagerConfig.getUsername()
|
||||
+ "&password=" + apiManagerConfig.getPassword();
|
||||
|
||||
String subscriptionListUrl = serverUrl + ":" + serverPort + apiManagerConfig.getSubscriptionListURL();
|
||||
subscriptionListEndpoint = subscriptionListUrl + "?action=getAllSubscriptions";
|
||||
}
|
||||
|
||||
public String getBase64EncodedConsumerKeyAndSecret(String deviceType) {
|
||||
if (!isEnabled) return null;
|
||||
String consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType);
|
||||
if (consumerKeyAndSecret == null) {
|
||||
ArrayList<DeviceTypeConfig> iotDeviceTypeConfigs = new ArrayList<>();
|
||||
DeviceTypeConfig DeviceTypeConfig =
|
||||
DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap().get(deviceType);
|
||||
if (DeviceTypeConfig != null) {
|
||||
iotDeviceTypeConfigs.add(DeviceTypeConfig);
|
||||
setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigs);
|
||||
consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType);
|
||||
if (consumerKeyAndSecret == null) {
|
||||
log.warn("There is no API application for the device type " + deviceType);
|
||||
}
|
||||
}
|
||||
}
|
||||
return consumerKeyAndSecret;
|
||||
}
|
||||
|
||||
public void setBase64EncodedConsumerKeyAndSecret(List<DeviceTypeConfig> iotDeviceTypeConfigList) {
|
||||
if (!isEnabled) {
|
||||
return;
|
||||
}
|
||||
URL loginURL;
|
||||
try {
|
||||
loginURL = new URL(loginEndpoint);
|
||||
} catch (MalformedURLException e) {
|
||||
String errMsg = "Malformed URL " + loginEndpoint;
|
||||
log.error(errMsg);
|
||||
return;
|
||||
}
|
||||
HttpClient httpClient;
|
||||
try {
|
||||
httpClient = IoTUtil.getHttpClient(loginURL.getPort(), loginURL.getProtocol());
|
||||
} catch (Exception e) {
|
||||
log.error("Error on getting a http client for port :" + loginURL.getPort() + " protocol :"
|
||||
+ loginURL.getProtocol());
|
||||
return;
|
||||
}
|
||||
|
||||
HttpPost postMethod = new HttpPost(loginEndpoint);
|
||||
JSONObject apiJsonResponse;
|
||||
try {
|
||||
HttpResponse httpResponse = httpClient.execute(postMethod);
|
||||
String response = IoTUtil.getResponseString(httpResponse);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(response);
|
||||
}
|
||||
JSONObject jsonObject = new JSONObject(response);
|
||||
|
||||
|
||||
boolean apiError = jsonObject.getBoolean("error");
|
||||
if (!apiError) {
|
||||
String cookie = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0];
|
||||
HttpGet getMethod = new HttpGet(subscriptionListEndpoint);
|
||||
getMethod.setHeader("cookie", cookie);
|
||||
httpResponse = httpClient.execute(getMethod);
|
||||
response = IoTUtil.getResponseString(httpResponse);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(response);
|
||||
}
|
||||
apiJsonResponse = new JSONObject(response);
|
||||
apiError = apiJsonResponse.getBoolean("error");
|
||||
if (apiError) {
|
||||
log.error("invalid subscription endpoint " + subscriptionListEndpoint);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
log.error("invalid access for login endpoint " + loginEndpoint);
|
||||
return;
|
||||
}
|
||||
} catch (IOException | JSONException | DeviceMgtCommonsException e) {
|
||||
log.warn("Trying to connect to the Api manager");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
JSONArray jsonSubscriptions = apiJsonResponse.getJSONObject("subscriptions").getJSONArray("applications");
|
||||
|
||||
HashMap<String, String> subscriptionMap = new HashMap<>();
|
||||
for (int n = 0; n < jsonSubscriptions.length(); n++) {
|
||||
|
||||
JSONObject object = jsonSubscriptions.getJSONObject(n);
|
||||
String appName = object.getString("name");
|
||||
String prodConsumerKey = object.getString("prodConsumerKey");
|
||||
String prodConsumerSecret = object.getString("prodConsumerSecret");
|
||||
subscriptionMap.put(appName, new String(Base64.encodeBase64(
|
||||
(prodConsumerKey + ":" + prodConsumerSecret).getBytes())));
|
||||
}
|
||||
|
||||
for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) {
|
||||
String deviceType = iotDeviceTypeConfig.getType();
|
||||
String deviceTypeApiApplicationName = iotDeviceTypeConfig.getApiApplicationName();
|
||||
String base64EncodedString = subscriptionMap.get(deviceTypeApiApplicationName);
|
||||
if (base64EncodedString != null && base64EncodedString.length() != 0) {
|
||||
deviceTypeToApiAppMap.put(deviceType, base64EncodedString);
|
||||
}
|
||||
}
|
||||
} catch (JSONException e) {
|
||||
log.error("Json exception: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,127 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, 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.etc.config.devicetype;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil;
|
||||
import org.wso2.carbon.device.mgt.etc.ApisAppClient;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.bind.ValidationEvent;
|
||||
import javax.xml.bind.ValidationEventHandler;
|
||||
import javax.xml.validation.Schema;
|
||||
import javax.xml.validation.SchemaFactory;
|
||||
import java.io.File;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Class responsible for the iot device manager configuration initialization.
|
||||
*/
|
||||
public class DeviceTypeConfigurationManager {
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeConfigurationManager.class);
|
||||
|
||||
private static final String DEVICE_TYPE_CONFIG_XML_NAME = "devicetype-config.xml";
|
||||
private static final String DEVICE_TYPE_CONFIG_XSD_NAME = "devicetype-config.xsd";
|
||||
private DeviceTypeConfigManager currentDeviceTypeConfig;
|
||||
private static DeviceTypeConfigurationManager
|
||||
deviceConfigManager = new DeviceTypeConfigurationManager();
|
||||
|
||||
private final String deviceMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath()
|
||||
+ File.separator + DEVICE_TYPE_CONFIG_XML_NAME;
|
||||
|
||||
private final String deviceMgtConfigXSDPath = CarbonUtils.getCarbonConfigDirPath()
|
||||
+ File.separator + DEVICE_TYPE_CONFIG_XSD_NAME;
|
||||
|
||||
private HashMap<String,DeviceTypeConfig> deviceTypeConfigMap = new HashMap<>();
|
||||
|
||||
public static DeviceTypeConfigurationManager getInstance() {
|
||||
return deviceConfigManager;
|
||||
}
|
||||
|
||||
public synchronized void initConfig() throws DeviceManagementException {
|
||||
try {
|
||||
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
|
||||
Schema schema = sf.newSchema(new File(deviceMgtConfigXSDPath));
|
||||
|
||||
File iotDeviceMgtConfig = new File(deviceMgtConfigXMLPath);
|
||||
Document doc = IotDeviceManagementUtil.convertToDocument(iotDeviceMgtConfig);
|
||||
JAXBContext iotDeviceMgmtContext = JAXBContext.newInstance(DeviceTypeConfigManager.class);
|
||||
Unmarshaller unmarshaller = iotDeviceMgmtContext.createUnmarshaller();
|
||||
unmarshaller.setSchema(schema);
|
||||
unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
|
||||
this.currentDeviceTypeConfig = (DeviceTypeConfigManager) unmarshaller.unmarshal(doc);
|
||||
|
||||
List<DeviceTypeConfig> iotDeviceTypeConfigList= currentDeviceTypeConfig.getDeviceTypeConfigs();
|
||||
for(DeviceTypeConfig iotDeviceTypeConfig:iotDeviceTypeConfigList){
|
||||
String applicationName=iotDeviceTypeConfig.getApiApplicationName();
|
||||
|
||||
if(applicationName==null||applicationName.isEmpty()){
|
||||
iotDeviceTypeConfig.setApiApplicationName(iotDeviceTypeConfig.getType());
|
||||
}
|
||||
deviceTypeConfigMap.put(iotDeviceTypeConfig.getType(), iotDeviceTypeConfig);
|
||||
}
|
||||
ApisAppClient.getInstance().setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigList);
|
||||
} catch (Exception e) {
|
||||
String error = "Error occurred while initializing device configurations";
|
||||
log.error(error, e);
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceTypeConfigManager getDeviceManagementConfig() {
|
||||
return currentDeviceTypeConfig;
|
||||
}
|
||||
|
||||
|
||||
public Map<String,DeviceTypeConfig> getDeviceTypeConfigMap(){
|
||||
return Collections.unmodifiableMap(deviceTypeConfigMap);
|
||||
}
|
||||
|
||||
|
||||
private class IotConfigValidationEventHandler implements ValidationEventHandler {
|
||||
@Override
|
||||
public boolean handleEvent(ValidationEvent event) {
|
||||
String error= "\nEVENT" +"\nSEVERITY: " + event.getSeverity()
|
||||
+ "\nMESSAGE: " + event.getMessage()
|
||||
+"\nLINKED EXCEPTION: " + event.getLinkedException()
|
||||
+"\nLOCATOR"
|
||||
+"\n LINE NUMBER: " + event.getLocator().getLineNumber()
|
||||
+"\n COLUMN NUMBER: " + event.getLocator().getColumnNumber()
|
||||
+"\n OFFSET: " + event.getLocator().getOffset()
|
||||
+"\n OBJECT: " + event.getLocator().getObject()
|
||||
+"\n NODE: " + event.getLocator().getNode()
|
||||
+"\n URL: " + event.getLocator().getURL();
|
||||
|
||||
|
||||
log.error(error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,135 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.devicetype.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlAttribute;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DeviceTypeConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DeviceTypeConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="DatasourceName" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="ApiApplicationName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
|
||||
* </sequence>
|
||||
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DeviceTypeConfig", propOrder = {
|
||||
"datasourceName",
|
||||
"apiApplicationName"
|
||||
})
|
||||
public class DeviceTypeConfig {
|
||||
|
||||
@XmlElement(name = "DatasourceName", required = true)
|
||||
protected String datasourceName;
|
||||
@XmlElement(name = "ApiApplicationName")
|
||||
protected String apiApplicationName;
|
||||
@XmlAttribute(name = "type", required = true)
|
||||
protected String type;
|
||||
|
||||
/**
|
||||
* Gets the value of the datasourceName property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getDatasourceName() {
|
||||
return datasourceName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the datasourceName property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setDatasourceName(String value) {
|
||||
this.datasourceName = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the apiApplicationName property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getApiApplicationName() {
|
||||
return apiApplicationName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the apiApplicationName property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setApiApplicationName(String value) {
|
||||
this.apiApplicationName = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the type property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the type property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setType(String value) {
|
||||
this.type = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,89 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.devicetype.datasource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DeviceTypeConfigManager complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DeviceTypeConfigManager">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="DeviceTypeConfig" type="{}DeviceTypeConfig" maxOccurs="unbounded" minOccurs="0"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DeviceTypeConfigManager", propOrder = {
|
||||
"deviceTypeConfigs"
|
||||
})
|
||||
|
||||
@XmlRootElement(name = "DeviceTypeConfigManager")
|
||||
public class DeviceTypeConfigManager {
|
||||
|
||||
@XmlElement(name = "DeviceTypeConfig")
|
||||
protected List<DeviceTypeConfig> deviceTypeConfigs;
|
||||
|
||||
/**
|
||||
* Gets the value of the DeviceTypeConfig property.
|
||||
*
|
||||
* <p>
|
||||
* This accessor method returns a reference to the live list,
|
||||
* not a snapshot. Therefore any modification you make to the
|
||||
* returned list will be present inside the JAXB object.
|
||||
* This is why there is not a <CODE>set</CODE> method for the iotDeviceTypeConfig property.
|
||||
*
|
||||
* <p>
|
||||
* For example, to add a new item, do as follows:
|
||||
* <pre>
|
||||
* getDeviceTypeConfigs().add(newItem);
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* Objects of the following type(s) are allowed in the list
|
||||
* {@link DeviceTypeConfig }
|
||||
*
|
||||
*
|
||||
*/
|
||||
public List<DeviceTypeConfig> getDeviceTypeConfigs() {
|
||||
if (deviceTypeConfigs == null) {
|
||||
deviceTypeConfigs = new ArrayList<>();
|
||||
}
|
||||
return this.deviceTypeConfigs;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,80 +0,0 @@
|
||||
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.devicetype.datasource;
|
||||
|
||||
import javax.xml.bind.JAXBElement;
|
||||
import javax.xml.bind.annotation.XmlElementDecl;
|
||||
import javax.xml.bind.annotation.XmlRegistry;
|
||||
import javax.xml.namespace.QName;
|
||||
|
||||
|
||||
/**
|
||||
* This object contains factory methods for each
|
||||
* Java content interface and Java element interface
|
||||
* generated in the org.wso2.carbon.device.mgt.iot.common.config.server.configs package.
|
||||
* <p>An ObjectFactory allows you to programatically
|
||||
* construct new instances of the Java representation
|
||||
* for XML content. The Java representation of XML
|
||||
* content can consist of schema derived interfaces
|
||||
* and classes representing the binding of schema
|
||||
* type definitions, element declarations and model
|
||||
* groups. Factory methods for each of these are
|
||||
* provided in this class.
|
||||
*
|
||||
*/
|
||||
@XmlRegistry
|
||||
public class ObjectFactory {
|
||||
|
||||
private final static QName _DeviceTypeConfigManager_QNAME = new QName("", "DeviceTypeConfigManager");
|
||||
|
||||
/**
|
||||
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.wso2.carbon.device.mgt.iot.common.config.server.configs
|
||||
*
|
||||
*/
|
||||
public ObjectFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceTypeConfigManager }
|
||||
*
|
||||
*/
|
||||
public DeviceTypeConfigManager createDeviceTypeConfigManager() {
|
||||
return new DeviceTypeConfigManager();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceTypeConfig }
|
||||
*
|
||||
*/
|
||||
public DeviceTypeConfig createDeviceTypeConfig() {
|
||||
return new DeviceTypeConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link JAXBElement }{@code <}{@link DeviceTypeConfigManager }{@code >}}
|
||||
*
|
||||
*/
|
||||
@XmlElementDecl(namespace = "", name = "DeviceTypeConfigManager")
|
||||
public JAXBElement<DeviceTypeConfigManager> createDeviceTypeConfigManager(
|
||||
DeviceTypeConfigManager value) {
|
||||
return new JAXBElement<DeviceTypeConfigManager>(_DeviceTypeConfigManager_QNAME, DeviceTypeConfigManager.class, null, value);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,131 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.w3c.dom.Document;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DeviceCloudConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.Unmarshaller;
|
||||
import javax.xml.bind.ValidationEvent;
|
||||
import javax.xml.bind.ValidationEventHandler;
|
||||
import javax.xml.validation.Schema;
|
||||
import javax.xml.validation.SchemaFactory;
|
||||
import java.io.File;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Class responsible for the iot device manager configuration initialization.
|
||||
*/
|
||||
public class DeviceCloudConfigManager {
|
||||
private static final Log log = LogFactory.getLog(DeviceCloudConfigManager.class);
|
||||
|
||||
private static final String DEVICE_CONFIG_XML_NAME = "devicemgt-config.xml";
|
||||
private final String XMLCONFIGS_FILE_LOCATION =
|
||||
CarbonUtils.getCarbonConfigDirPath() + File.separator + DEVICE_CONFIG_XML_NAME;
|
||||
|
||||
private static final String DEVICE_CONFIG_XSD_NAME = "devicemgt-config.xsd";
|
||||
private final String XSDCONFIGS_FILE_LOCATION =
|
||||
CarbonUtils.getCarbonConfigDirPath() + File.separator + DEVICE_CONFIG_XSD_NAME;
|
||||
|
||||
private DeviceCloudConfig currentDeviceCloudConfig;
|
||||
private static DeviceCloudConfigManager
|
||||
deviceConfigurationManager = new DeviceCloudConfigManager();
|
||||
|
||||
private DeviceCloudConfigManager() {
|
||||
}
|
||||
|
||||
public static DeviceCloudConfigManager getInstance() {
|
||||
return deviceConfigurationManager;
|
||||
}
|
||||
|
||||
public void initConfig() throws DeviceControllerException {
|
||||
try {
|
||||
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
|
||||
Schema schema = sf.newSchema(new File(XSDCONFIGS_FILE_LOCATION));
|
||||
|
||||
File deviceCloudMgtConfig = new File(XMLCONFIGS_FILE_LOCATION);
|
||||
Document doc = IotDeviceManagementUtil.convertToDocument(deviceCloudMgtConfig);
|
||||
JAXBContext deviceCloudContext = JAXBContext.newInstance(DeviceCloudConfig.class);
|
||||
Unmarshaller unmarshaller = deviceCloudContext.createUnmarshaller();
|
||||
unmarshaller.setSchema(schema);
|
||||
unmarshaller.setEventHandler(new IotConfigValidationEventHandler());
|
||||
this.currentDeviceCloudConfig = (DeviceCloudConfig) unmarshaller.unmarshal(doc);
|
||||
} catch (Exception e) {
|
||||
String error = "Error occurred while initializing DeviceController configurations";
|
||||
log.error(error);
|
||||
throw new DeviceControllerException(error, e);
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceCloudConfig getDeviceCloudMgtConfig() {
|
||||
return currentDeviceCloudConfig;
|
||||
}
|
||||
|
||||
public DataStore getDataStore(String name){
|
||||
List<DataStore> dataStores= currentDeviceCloudConfig.getDataStores().getDataStore();
|
||||
if(dataStores!=null) {
|
||||
for (DataStore dataStore : dataStores) {
|
||||
if (dataStore.getName().equals(name)) {
|
||||
return dataStore;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public ControlQueue getControlQueue(String name){
|
||||
List<ControlQueue> controlQueues= currentDeviceCloudConfig.getControlQueues().getControlQueue();
|
||||
if(controlQueues!=null) {
|
||||
for (ControlQueue controlQueue : controlQueues) {
|
||||
if (controlQueue.getName().equals(name)) {
|
||||
return controlQueue;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private class IotConfigValidationEventHandler implements ValidationEventHandler {
|
||||
@Override
|
||||
public boolean handleEvent(ValidationEvent event) {
|
||||
String error= "\nEVENT" +"\nSEVERITY: " + event.getSeverity()
|
||||
+ "\nMESSAGE: " + event.getMessage()
|
||||
+"\nLINKED EXCEPTION: " + event.getLinkedException()
|
||||
+"\nLOCATOR"
|
||||
+"\n LINE NUMBER: " + event.getLocator().getLineNumber()
|
||||
+"\n COLUMN NUMBER: " + event.getLocator().getColumnNumber()
|
||||
+"\n OFFSET: " + event.getLocator().getOffset()
|
||||
+"\n OBJECT: " + event.getLocator().getObject()
|
||||
+"\n NODE: " + event.getLocator().getNode()
|
||||
+"\n URL: " + event.getLocator().getURL();
|
||||
log.error(error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,351 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for ApiManagerConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="ApiManagerConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="Enabled" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
|
||||
* <element name="AccessTokenURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="ServerURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="ServerPort" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="GatewayPort" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="LoginURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="SubscriptionListURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Username" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Password" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="DeviceGrantType" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="DeviceScopes" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "ApiManagerConfig", propOrder = {
|
||||
"enabled",
|
||||
"accessTokenURL",
|
||||
"serverURL",
|
||||
"serverPort",
|
||||
"gatewayPort",
|
||||
"loginURL",
|
||||
"subscriptionListURL",
|
||||
"username",
|
||||
"password",
|
||||
"deviceGrantType",
|
||||
"deviceScopes"
|
||||
})
|
||||
public class ApiManagerConfig {
|
||||
|
||||
@XmlElement(name = "Enabled")
|
||||
protected boolean enabled;
|
||||
@XmlElement(name = "AccessTokenURL", required = true)
|
||||
protected String accessTokenURL;
|
||||
@XmlElement(name = "ServerURL", required = true)
|
||||
protected String serverURL;
|
||||
@XmlElement(name = "ServerPort", required = true)
|
||||
protected String serverPort;
|
||||
@XmlElement(name = "GatewayPort", required = true)
|
||||
protected String gatewayPort;
|
||||
@XmlElement(name = "LoginURL", required = true)
|
||||
protected String loginURL;
|
||||
@XmlElement(name = "SubscriptionListURL", required = true)
|
||||
protected String subscriptionListURL;
|
||||
@XmlElement(name = "Username", required = true)
|
||||
protected String username;
|
||||
@XmlElement(name = "Password", required = true)
|
||||
protected String password;
|
||||
@XmlElement(name = "DeviceGrantType", required = true)
|
||||
protected String deviceGrantType;
|
||||
@XmlElement(name = "DeviceScopes", required = true)
|
||||
protected String deviceScopes;
|
||||
|
||||
/**
|
||||
* Gets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public void setEnabled(boolean value) {
|
||||
this.enabled = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the accessTokenURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getAccessTokenURL() {
|
||||
return accessTokenURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the accessTokenURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setAccessTokenURL(String value) {
|
||||
this.accessTokenURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the serverURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getServerURL() {
|
||||
return serverURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the serverURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setServerURL(String value) {
|
||||
this.serverURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the serverPort property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getServerPort() {
|
||||
return serverPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the serverPort property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setServerPort(String value) {
|
||||
this.serverPort = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the gatewayPort property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getGatewayPort() {
|
||||
return gatewayPort;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the gatewayPort property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setGatewayPort(String value) {
|
||||
this.gatewayPort = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the loginURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getLoginURL() {
|
||||
return loginURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the loginURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setLoginURL(String value) {
|
||||
this.loginURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the subscriptionListURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getSubscriptionListURL() {
|
||||
return subscriptionListURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the subscriptionListURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setSubscriptionListURL(String value) {
|
||||
this.subscriptionListURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the username property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the username property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setUsername(String value) {
|
||||
this.username = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the password property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the password property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setPassword(String value) {
|
||||
this.password = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the deviceGrantType property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getDeviceGrantType() {
|
||||
return deviceGrantType;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the deviceGrantType property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setDeviceGrantType(String value) {
|
||||
this.deviceGrantType = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the deviceScopes property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getDeviceScopes() {
|
||||
return deviceScopes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the deviceScopes property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setDeviceScopes(String value) {
|
||||
this.deviceScopes = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,259 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for ControlQueue complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="ControlQueue">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Enabled" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
|
||||
* <element name="ControlClass" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Protocol" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="ServerURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Port" type="{http://www.w3.org/2001/XMLSchema}short"/>
|
||||
* <element name="Username" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Password" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "ControlQueue", propOrder = {
|
||||
"name",
|
||||
"enabled",
|
||||
"controlClass",
|
||||
"protocol",
|
||||
"serverURL",
|
||||
"port",
|
||||
"username",
|
||||
"password"
|
||||
})
|
||||
public class ControlQueue {
|
||||
|
||||
@XmlElement(name = "Name", required = true)
|
||||
protected String name;
|
||||
@XmlElement(name = "Enabled")
|
||||
protected boolean enabled;
|
||||
@XmlElement(name = "ControlClass", required = true)
|
||||
protected String controlClass;
|
||||
@XmlElement(name = "Protocol", required = true)
|
||||
protected String protocol;
|
||||
@XmlElement(name = "ServerURL", required = true)
|
||||
protected String serverURL;
|
||||
@XmlElement(name = "Port")
|
||||
protected short port;
|
||||
@XmlElement(name = "Username", required = true)
|
||||
protected String username;
|
||||
@XmlElement(name = "Password", required = true)
|
||||
protected String password;
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public void setEnabled(boolean value) {
|
||||
this.enabled = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the controlClass property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getControlClass() {
|
||||
return controlClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the controlClass property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setControlClass(String value) {
|
||||
this.controlClass = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the protocol property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getProtocol() {
|
||||
return protocol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the protocol property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setProtocol(String value) {
|
||||
this.protocol = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the serverURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getServerURL() {
|
||||
return serverURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the serverURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setServerURL(String value) {
|
||||
this.serverURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the port property.
|
||||
*
|
||||
*/
|
||||
public short getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the port property.
|
||||
*
|
||||
*/
|
||||
public void setPort(short value) {
|
||||
this.port = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the username property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the username property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setUsername(String value) {
|
||||
this.username = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the password property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the password property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setPassword(String value) {
|
||||
this.password = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,69 +0,0 @@
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for ControlQueuesConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="ControlQueuesConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="ControlQueue" type="{}ControlQueue" maxOccurs="unbounded" minOccurs="0"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "ControlQueuesConfig", propOrder = {
|
||||
"controlQueue"
|
||||
})
|
||||
public class ControlQueuesConfig {
|
||||
|
||||
@XmlElement(name = "ControlQueue")
|
||||
protected List<ControlQueue> controlQueue;
|
||||
|
||||
/**
|
||||
* Gets the value of the controlQueue property.
|
||||
*
|
||||
* <p>
|
||||
* This accessor method returns a reference to the live list,
|
||||
* not a snapshot. Therefore any modification you make to the
|
||||
* returned list will be present inside the JAXB object.
|
||||
* This is why there is not a <CODE>set</CODE> method for the controlQueue property.
|
||||
*
|
||||
* <p>
|
||||
* For example, to add a new item, do as follows:
|
||||
* <pre>
|
||||
* getControlQueue().add(newItem);
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* Objects of the following type(s) are allowed in the list
|
||||
* {@link ControlQueue }
|
||||
*
|
||||
*
|
||||
*/
|
||||
public List<ControlQueue> getControlQueue() {
|
||||
if (controlQueue == null) {
|
||||
controlQueue = new ArrayList<ControlQueue>();
|
||||
}
|
||||
return this.controlQueue;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,231 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DataStore complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DataStore">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Enabled" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
|
||||
* <element name="PublisherClass" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="ServerURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Port" type="{http://www.w3.org/2001/XMLSchema}short"/>
|
||||
* <element name="Username" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Password" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DataStore", propOrder = {
|
||||
"name",
|
||||
"enabled",
|
||||
"publisherClass",
|
||||
"serverURL",
|
||||
"port",
|
||||
"username",
|
||||
"password"
|
||||
})
|
||||
public class DataStore {
|
||||
|
||||
@XmlElement(name = "Name", required = true)
|
||||
protected String name;
|
||||
@XmlElement(name = "Enabled")
|
||||
protected boolean enabled;
|
||||
@XmlElement(name = "PublisherClass", required = true)
|
||||
protected String publisherClass;
|
||||
@XmlElement(name = "ServerURL", required = true)
|
||||
protected String serverURL;
|
||||
@XmlElement(name = "Port")
|
||||
protected short port;
|
||||
@XmlElement(name = "Username", required = true)
|
||||
protected String username;
|
||||
@XmlElement(name = "Password", required = true)
|
||||
protected String password;
|
||||
|
||||
/**
|
||||
* Gets the value of the name property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the name property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setName(String value) {
|
||||
this.name = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the enabled property.
|
||||
*
|
||||
*/
|
||||
public void setEnabled(boolean value) {
|
||||
this.enabled = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the publisherClass property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getPublisherClass() {
|
||||
return publisherClass;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the publisherClass property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setPublisherClass(String value) {
|
||||
this.publisherClass = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the serverURL property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getServerURL() {
|
||||
return serverURL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the serverURL property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setServerURL(String value) {
|
||||
this.serverURL = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the port property.
|
||||
*
|
||||
*/
|
||||
public short getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the port property.
|
||||
*
|
||||
*/
|
||||
public void setPort(short value) {
|
||||
this.port = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the username property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the username property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setUsername(String value) {
|
||||
this.username = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the password property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the password property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setPassword(String value) {
|
||||
this.password = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,86 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DataStoresConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DataStoresConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="DataStore" type="{}DataStore" maxOccurs="unbounded" minOccurs="0"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DataStoresConfig", propOrder = {
|
||||
"dataStore"
|
||||
})
|
||||
public class DataStoresConfig {
|
||||
|
||||
@XmlElement(name = "DataStore")
|
||||
protected List<DataStore> dataStore;
|
||||
|
||||
/**
|
||||
* Gets the value of the dataStore property.
|
||||
*
|
||||
* <p>
|
||||
* This accessor method returns a reference to the live list,
|
||||
* not a snapshot. Therefore any modification you make to the
|
||||
* returned list will be present inside the JAXB object.
|
||||
* This is why there is not a <CODE>set</CODE> method for the dataStore property.
|
||||
*
|
||||
* <p>
|
||||
* For example, to add a new item, do as follows:
|
||||
* <pre>
|
||||
* getDataStore().add(newItem);
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
* <p>
|
||||
* Objects of the following type(s) are allowed in the list
|
||||
* {@link DataStore }
|
||||
*
|
||||
*
|
||||
*/
|
||||
public List<DataStore> getDataStore() {
|
||||
if (dataStore == null) {
|
||||
dataStore = new ArrayList<DataStore>();
|
||||
}
|
||||
return this.dataStore;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,193 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DeviceCloudConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DeviceCloudConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="DataStores" type="{}DataStoresConfig"/>
|
||||
* <element name="ControlQueues" type="{}ControlQueuesConfig"/>
|
||||
* <element name="Security" type="{}SecurityConfig"/>
|
||||
* <element name="ApiManager" type="{}ApiManagerConfig"/>
|
||||
* <element name="DeviceUserValidator" type="{}DeviceUserValidatorConfig"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DeviceCloudConfig", propOrder = {
|
||||
"dataStores",
|
||||
"controlQueues",
|
||||
"security",
|
||||
"apiManager",
|
||||
"deviceUserValidator"
|
||||
})
|
||||
@XmlRootElement(name = "DeviceCloudConfiguration")
|
||||
public class DeviceCloudConfig {
|
||||
|
||||
@XmlElement(name = "DataStores", required = true)
|
||||
protected DataStoresConfig dataStores;
|
||||
@XmlElement(name = "ControlQueues", required = true)
|
||||
protected ControlQueuesConfig controlQueues;
|
||||
@XmlElement(name = "Security", required = true)
|
||||
protected SecurityConfig security;
|
||||
@XmlElement(name = "ApiManager", required = true)
|
||||
protected ApiManagerConfig apiManager;
|
||||
@XmlElement(name = "DeviceUserValidator", required = true)
|
||||
protected DeviceUserValidatorConfig deviceUserValidator;
|
||||
|
||||
/**
|
||||
* Gets the value of the dataStores property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link DataStoresConfig }
|
||||
*
|
||||
*/
|
||||
public DataStoresConfig getDataStores() {
|
||||
return dataStores;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the dataStores property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link DataStoresConfig }
|
||||
*
|
||||
*/
|
||||
public void setDataStores(DataStoresConfig value) {
|
||||
this.dataStores = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the controlQueues property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link ControlQueuesConfig }
|
||||
*
|
||||
*/
|
||||
public ControlQueuesConfig getControlQueues() {
|
||||
return controlQueues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the controlQueues property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link ControlQueuesConfig }
|
||||
*
|
||||
*/
|
||||
public void setControlQueues(ControlQueuesConfig value) {
|
||||
this.controlQueues = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the security property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link SecurityConfig }
|
||||
*
|
||||
*/
|
||||
public SecurityConfig getSecurity() {
|
||||
return security;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the security property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link SecurityConfig }
|
||||
*
|
||||
*/
|
||||
public void setSecurity(SecurityConfig value) {
|
||||
this.security = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the apiManager property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link ApiManagerConfig }
|
||||
*
|
||||
*/
|
||||
public ApiManagerConfig getApiManager() {
|
||||
return apiManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the apiManager property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link ApiManagerConfig }
|
||||
*
|
||||
*/
|
||||
public void setApiManager(ApiManagerConfig value) {
|
||||
this.apiManager = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the deviceUserValidator property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link DeviceUserValidatorConfig }
|
||||
*
|
||||
*/
|
||||
public DeviceUserValidatorConfig getDeviceUserValidator() {
|
||||
return deviceUserValidator;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the deviceUserValidator property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link DeviceUserValidatorConfig }
|
||||
*
|
||||
*/
|
||||
public void setDeviceUserValidator(DeviceUserValidatorConfig value) {
|
||||
this.deviceUserValidator = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,108 +0,0 @@
|
||||
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for DeviceUserValidatorConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="DeviceUserValidatorConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="CacheSize" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="TTL" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "DeviceUserValidatorConfig", propOrder = {
|
||||
"cacheSize",
|
||||
"ttl"
|
||||
})
|
||||
public class DeviceUserValidatorConfig {
|
||||
|
||||
@XmlElement(name = "CacheSize", required = true)
|
||||
protected int cacheSize;
|
||||
@XmlElement(name = "TTL", required = true)
|
||||
protected int ttl;
|
||||
|
||||
/**
|
||||
* Gets the value of the cacheSize property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link int }
|
||||
*
|
||||
*/
|
||||
public int getCacheSize() {
|
||||
return cacheSize;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the cacheSize property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link int }
|
||||
*
|
||||
*/
|
||||
public void setCacheSize(int value) {
|
||||
this.cacheSize = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the ttl property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link int }
|
||||
*
|
||||
*/
|
||||
public int getTTL() {
|
||||
return ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the ttl property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link int }
|
||||
*
|
||||
*/
|
||||
public void setTTL(int value) {
|
||||
this.ttl = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,116 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.JAXBElement;
|
||||
import javax.xml.bind.annotation.XmlElementDecl;
|
||||
import javax.xml.bind.annotation.XmlRegistry;
|
||||
import javax.xml.namespace.QName;
|
||||
|
||||
|
||||
/**
|
||||
* This object contains factory methods for each
|
||||
* Java content interface and Java element interface
|
||||
* generated in the org.wso2.carbon.device.mgt.etc.config.server.configs package.
|
||||
* <p>An ObjectFactory allows you to programatically
|
||||
* construct new instances of the Java representation
|
||||
* for XML content. The Java representation of XML
|
||||
* content can consist of schema derived interfaces
|
||||
* and classes representing the binding of schema
|
||||
* type definitions, element declarations and model
|
||||
* groups. Factory methods for each of these are
|
||||
* provided in this class.
|
||||
*/
|
||||
@XmlRegistry
|
||||
public class ObjectFactory {
|
||||
|
||||
private final static QName _DeviceCloudConfiguration_QNAME = new QName("", "DeviceCloudConfiguration");
|
||||
|
||||
/**
|
||||
* Create a new ObjectFactory that can be used to create new instances of
|
||||
* schema derived classes for package: org.wso2.carbon.device.mgt.etc.config.server.configs
|
||||
*/
|
||||
public ObjectFactory() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceCloudConfig }
|
||||
*/
|
||||
public DeviceCloudConfig createDeviceCloudConfig() {
|
||||
return new DeviceCloudConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link ApiManagerConfig }
|
||||
*/
|
||||
public ApiManagerConfig createApiManagerConfig() {
|
||||
return new ApiManagerConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link ControlQueuesConfig }
|
||||
*/
|
||||
public ControlQueuesConfig createControlQueuesConfig() {
|
||||
return new ControlQueuesConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link SecurityConfig }
|
||||
*/
|
||||
public SecurityConfig createSecurityConfig() {
|
||||
return new SecurityConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link ControlQueue }
|
||||
*/
|
||||
public ControlQueue createControlQueue() {
|
||||
return new ControlQueue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DeviceUserValidatorConfig }
|
||||
*/
|
||||
public DeviceUserValidatorConfig createDeviceUserValidatorConfig() {
|
||||
return new DeviceUserValidatorConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DataStore }
|
||||
*/
|
||||
public DataStore createDataStore() {
|
||||
return new DataStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link DataStoresConfig }
|
||||
*/
|
||||
public DataStoresConfig createDataStoresConfig() {
|
||||
return new DataStoresConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an instance of {@link JAXBElement }{@code <}{@link DeviceCloudConfig }{@code >}}
|
||||
*/
|
||||
@XmlElementDecl(namespace = "", name = "DeviceCloudConfiguration")
|
||||
public JAXBElement<DeviceCloudConfig> createDeviceCloudConfiguration(DeviceCloudConfig value) {
|
||||
return new JAXBElement<DeviceCloudConfig>(_DeviceCloudConfiguration_QNAME, DeviceCloudConfig.class, null, value);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,108 +0,0 @@
|
||||
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.config.server.datasource;
|
||||
|
||||
import javax.xml.bind.annotation.XmlAccessType;
|
||||
import javax.xml.bind.annotation.XmlAccessorType;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlType;
|
||||
|
||||
|
||||
/**
|
||||
* <p>Java class for SecurityConfig complex type.
|
||||
*
|
||||
* <p>The following schema fragment specifies the expected content contained within this class.
|
||||
*
|
||||
* <pre>
|
||||
* <complexType name="SecurityConfig">
|
||||
* <complexContent>
|
||||
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
|
||||
* <sequence>
|
||||
* <element name="ClientTrustStore" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* <element name="Password" type="{http://www.w3.org/2001/XMLSchema}string"/>
|
||||
* </sequence>
|
||||
* </restriction>
|
||||
* </complexContent>
|
||||
* </complexType>
|
||||
* </pre>
|
||||
*
|
||||
*
|
||||
*/
|
||||
@XmlAccessorType(XmlAccessType.FIELD)
|
||||
@XmlType(name = "SecurityConfig", propOrder = {
|
||||
"clientTrustStore",
|
||||
"password"
|
||||
})
|
||||
public class SecurityConfig {
|
||||
|
||||
@XmlElement(name = "ClientTrustStore", required = true)
|
||||
protected String clientTrustStore;
|
||||
@XmlElement(name = "Password", required = true)
|
||||
protected String password;
|
||||
|
||||
/**
|
||||
* Gets the value of the clientTrustStore property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getClientTrustStore() {
|
||||
return clientTrustStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the clientTrustStore property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setClientTrustStore(String value) {
|
||||
this.clientTrustStore = value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the value of the password property.
|
||||
*
|
||||
* @return
|
||||
* possible object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the value of the password property.
|
||||
*
|
||||
* @param value
|
||||
* allowed object is
|
||||
* {@link String }
|
||||
*
|
||||
*/
|
||||
public void setPassword(String value) {
|
||||
this.password = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,53 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* The Interface ControlQueueConnector.
|
||||
*
|
||||
*/
|
||||
public interface ControlQueueConnector {
|
||||
|
||||
/**
|
||||
* Initializes the control queue.
|
||||
* This method loads the initial configurations relevant to the
|
||||
* Control-Queue implementation
|
||||
*
|
||||
* @return A status message according to the outcome of the
|
||||
* method execution.
|
||||
*/
|
||||
void initControlQueue() throws DeviceControllerException;
|
||||
|
||||
/**
|
||||
* Pushes the control messages received to the implemented queue
|
||||
*
|
||||
* @param deviceControls
|
||||
* A Hash Map which contains the parameters relevant to the
|
||||
* control message and the actual control message to be pushed to
|
||||
* the queue
|
||||
* @return A status message according to the outcome of the
|
||||
* method execution.
|
||||
*/
|
||||
void enqueueControls(HashMap<String, String> deviceControls) throws
|
||||
DeviceControllerException;
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.mqtt;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue;
|
||||
|
||||
public class MqttConfig {
|
||||
private String mqttQueueEndpoint;
|
||||
private String mqttQueueUsername;
|
||||
private String mqttQueuePassword;
|
||||
private boolean isEnabled;
|
||||
|
||||
private static final String MQTT_QUEUE_CONFIG_NAME = "MQTT";
|
||||
|
||||
private ControlQueue mqttControlQueue;
|
||||
|
||||
private static MqttConfig mqttConfig = new MqttConfig();
|
||||
|
||||
public String getMqttQueueEndpoint() {
|
||||
return mqttQueueEndpoint;
|
||||
}
|
||||
|
||||
public String getMqttQueueUsername() {
|
||||
return mqttQueueUsername;
|
||||
}
|
||||
|
||||
public String getMqttQueuePassword() {
|
||||
return mqttQueuePassword;
|
||||
}
|
||||
|
||||
public ControlQueue getMqttControlQueue() {
|
||||
return mqttControlQueue;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
public static String getMqttQueueConfigName() {
|
||||
return MQTT_QUEUE_CONFIG_NAME;
|
||||
}
|
||||
|
||||
private MqttConfig() {
|
||||
mqttControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue(
|
||||
MQTT_QUEUE_CONFIG_NAME);
|
||||
mqttQueueEndpoint = mqttControlQueue.getServerURL() + ":" + mqttControlQueue.getPort();
|
||||
mqttQueueUsername = mqttControlQueue.getUsername();
|
||||
mqttQueuePassword = mqttControlQueue.getPassword();
|
||||
isEnabled = mqttControlQueue.isEnabled();
|
||||
}
|
||||
|
||||
public static MqttConfig getInstance() {
|
||||
return mqttConfig;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,162 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.mqtt;
|
||||
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.HashMap;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
|
||||
/**
|
||||
* The Class MqttControlPublisher. It is an implementation of the interface
|
||||
* ControlQueueConnector.
|
||||
* This implementation supports publishing of control signals received to an
|
||||
* MQTT end-point.
|
||||
* The configuration settings for the MQTT end-point are read from the
|
||||
* 'controller.xml' file of the project.
|
||||
* This is done using the class 'DefaultDeviceControlConfigs.java' which loads
|
||||
* the settings from the default xml org.wso2.carbon.device.mgt.iot.common.devicecloud.org.wso2.carbon.device.mgt.iot.common.config.server.configs
|
||||
* file -
|
||||
* /resources/conf/device-controls/controller.xml
|
||||
*/
|
||||
//TODO-Make these MQTT, XMPP publishers/ subscribers into "transport" package
|
||||
public class MqttControlPublisher implements ControlQueueConnector, MqttCallback {
|
||||
|
||||
private static final Log log = LogFactory.getLog(MqttControlPublisher.class);
|
||||
|
||||
private String mqttEndpoint;
|
||||
private String mqttUsername;
|
||||
private String mqttPassword;
|
||||
private boolean mqttEnabled = false;
|
||||
|
||||
public MqttControlPublisher() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initControlQueue() throws DeviceControllerException {
|
||||
mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
|
||||
mqttUsername = MqttConfig.getInstance().getMqttQueueUsername();
|
||||
mqttPassword = MqttConfig.getInstance().getMqttQueuePassword();
|
||||
mqttEnabled = MqttConfig.getInstance().isEnabled();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void enqueueControls(HashMap<String, String> deviceControls)
|
||||
throws DeviceControllerException {
|
||||
|
||||
if (mqttEnabled) {
|
||||
MqttClient client;
|
||||
MqttConnectOptions options;
|
||||
|
||||
String owner = deviceControls.get("owner");
|
||||
String deviceType = deviceControls.get("deviceType");
|
||||
String deviceId = deviceControls.get("deviceId");
|
||||
String key = deviceControls.get("key");
|
||||
String value = deviceControls.get("value");
|
||||
|
||||
String clientId = owner + "." + deviceId;
|
||||
|
||||
if (clientId.length() > 24) {
|
||||
String errorString =
|
||||
"No of characters '" + clientId.length() + "' for ClientID: '" + clientId +
|
||||
"' is invalid (should be less than 24, hence please provide a " +
|
||||
"simple " +
|
||||
|
||||
|
||||
"'owner' tag)";
|
||||
log.error(errorString);
|
||||
throw new DeviceControllerException(errorString);
|
||||
} else {
|
||||
log.info("No of Characters " + clientId.length() + " for ClientID : '" + clientId +
|
||||
"' is acceptable");
|
||||
}
|
||||
|
||||
String publishTopic =
|
||||
"wso2" + File.separator + "iot" + File.separator + owner + File.separator +
|
||||
deviceType + File.separator
|
||||
+ deviceId;
|
||||
String payLoad = key + ":" + value;
|
||||
|
||||
log.info("Publish-Topic: " + publishTopic);
|
||||
log.info("PayLoad: " + payLoad);
|
||||
|
||||
try {
|
||||
client = new MqttClient(mqttEndpoint,clientId);
|
||||
options = new MqttConnectOptions();
|
||||
options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true);
|
||||
client.setCallback(this);
|
||||
client.connect(options);
|
||||
|
||||
MqttMessage message = new MqttMessage();
|
||||
message.setPayload(payLoad.getBytes(UTF_8));
|
||||
client.publish(publishTopic, payLoad.getBytes(UTF_8), 0, true);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("MQTT Client successfully published to topic: " + publishTopic +
|
||||
", with payload - " + payLoad);
|
||||
}
|
||||
client.disconnect();
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg =
|
||||
"MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() +
|
||||
"\n\tMessage: " +
|
||||
ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() +
|
||||
"\n\tCause: " + ex.getCause() + "\n\tException: " + ex;
|
||||
|
||||
log.error(errorMsg, ex);
|
||||
throw new DeviceControllerException(errorMsg, ex);
|
||||
}
|
||||
} else {
|
||||
log.warn("MQTT <Enabled> set to false in 'device-mgt-config.xml'");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable arg0) {
|
||||
log.error("Connection to MQTT Endpoint Lost");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken topic) {
|
||||
log.info("Published topic: '" + topic.getTopics()[0] + "' successfully to client: '" +
|
||||
topic.getClient().getClientId() + "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
|
||||
log.info("MQTT Message received: " + arg1.toString());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -1,289 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.mqtt;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* This class contains the Agent specific implementation for all the MQTT functionality. This
|
||||
* includes connecting to a MQTT Broker & subscribing to the appropriate MQTT-topic, action plan
|
||||
* upon losing connection or successfully delivering a message to the broker and processing
|
||||
* incoming messages. Makes use of the 'Paho-MQTT' library provided by Eclipse Org.
|
||||
* <p/>
|
||||
* It is an abstract class with an abstract method 'postMessageArrived' allowing the user to have
|
||||
* their own implementation of the actions to be taken upon receiving a message to the subscribed
|
||||
* MQTT-Topic.
|
||||
*/
|
||||
public abstract class MqttSubscriber implements MqttCallback {
|
||||
private static final Log log = LogFactory.getLog(MqttSubscriber.class);
|
||||
|
||||
private MqttClient client;
|
||||
private String clientId;
|
||||
private MqttConnectOptions options;
|
||||
private String subscribeTopic;
|
||||
private String clientWillTopic;
|
||||
private String mqttBrokerEndPoint;
|
||||
private int reConnectionInterval;
|
||||
|
||||
/**
|
||||
* Constructor for the MQTTClient which takes in the owner, type of the device and the MQTT
|
||||
* Broker URL and the topic to subscribe.
|
||||
*
|
||||
* @param owner the owner of the device.
|
||||
* @param deviceType the CDMF Device-Type of the device.
|
||||
* @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint.
|
||||
* @param subscribeTopic the MQTT topic to which the client is to be subscribed
|
||||
*/
|
||||
protected MqttSubscriber(String owner, String deviceType, String mqttBrokerEndPoint, String subscribeTopic) {
|
||||
this.clientId = owner + ":" + deviceType;
|
||||
this.subscribeTopic = subscribeTopic;
|
||||
this.clientWillTopic = deviceType + File.separator + "disconnection";
|
||||
this.mqttBrokerEndPoint = mqttBrokerEndPoint;
|
||||
this.reConnectionInterval = 5000;
|
||||
this.initSubscriber();
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor for the MQTTClient which takes in the owner, type of the device and the MQTT
|
||||
* Broker URL and the topic to subscribe. Additionally this constructor takes in the
|
||||
* reconnection-time interval between successive attempts to connect to the broker.
|
||||
*
|
||||
* @param deviceOwner the owner of the device.
|
||||
* @param deviceType the CDMF Device-Type of the device.
|
||||
* @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint.
|
||||
* @param subscribeTopic the MQTT topic to which the client is to be subscribed
|
||||
* @param reConnectionInterval time interval in SECONDS between successive attempts to connect
|
||||
* to the broker.
|
||||
*/
|
||||
protected MqttSubscriber(String deviceOwner, String deviceType, String mqttBrokerEndPoint,
|
||||
String subscribeTopic, int reConnectionInterval) {
|
||||
this.clientId = deviceOwner + ":" + deviceType;
|
||||
this.subscribeTopic = subscribeTopic;
|
||||
this.clientWillTopic = deviceType + File.separator + "disconnection";
|
||||
this.mqttBrokerEndPoint = mqttBrokerEndPoint;
|
||||
this.reConnectionInterval = reConnectionInterval;
|
||||
this.initSubscriber();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the MQTT-Client.
|
||||
* Creates a client using the given MQTT-broker endpoint and the clientId (which is
|
||||
* constructed by a concatenation of [deviceOwner]:[deviceType]). Also sets the client's
|
||||
* options parameter with the clientWillTopic (in-case of connection failure) and other info.
|
||||
* Also sets the call-back this current class.
|
||||
*/
|
||||
private void initSubscriber() {
|
||||
if(!MqttConfig.getInstance().isEnabled()){
|
||||
log.info("Mqtt Queue is not enabled");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
client = new MqttClient(this.mqttBrokerEndPoint, clientId, null);
|
||||
log.info("MQTT subscriber was created with ClientID : " + clientId);
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Client Error\n" + "\tReason: " + ex.getReasonCode() +
|
||||
"\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " +
|
||||
ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() +
|
||||
"\n\tException: " + ex;
|
||||
log.error(errorMsg);
|
||||
}
|
||||
|
||||
options = new MqttConnectOptions();
|
||||
options.setCleanSession(false);
|
||||
options.setWill(clientWillTopic, "connection crashed".getBytes(StandardCharsets.UTF_8), 2, true);
|
||||
client.setCallback(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the connection to the MQTT-Broker persists.
|
||||
*
|
||||
* @return true if the client is connected to the MQTT-Broker, else false.
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return client.isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the MQTT-Broker and if successfully established connection, then tries to
|
||||
* subscribe to the MQTT-Topic specific to the device. (The MQTT-Topic specific to the
|
||||
* device is created is taken in as a constructor parameter of this class) .
|
||||
*
|
||||
* @throws DeviceManagementException in the event of 'Connecting to' or 'Subscribing to' the
|
||||
* MQTT broker fails.
|
||||
*/
|
||||
public void connectAndSubscribe() throws DeviceManagementException {
|
||||
if(!MqttConfig.getInstance().isEnabled()){
|
||||
log.info("Mqtt Queue is not enabled");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
client.connect(options);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Subscriber connected to queue at: " + this.mqttBrokerEndPoint);
|
||||
}
|
||||
} catch (MqttSecurityException ex) {
|
||||
String errorMsg = "MQTT Security Exception when connecting to queue\n" + "\tReason: " +
|
||||
ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() +
|
||||
"\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " +
|
||||
ex.getCause() + "\n\tException: " + ex; //throw
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(errorMsg);
|
||||
}
|
||||
throw new DeviceManagementException(errorMsg, ex);
|
||||
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Exception when connecting to queue\n" + "\tReason: " +
|
||||
ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() +
|
||||
"\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " +
|
||||
ex.getCause() + "\n\tException: " + ex; //throw
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(errorMsg);
|
||||
}
|
||||
throw new DeviceManagementException(errorMsg, ex);
|
||||
}
|
||||
|
||||
try {
|
||||
client.subscribe(subscribeTopic, 0);
|
||||
|
||||
log.info("Subscribed with client id: " + clientId);
|
||||
log.info("Subscribed to topic: " + subscribeTopic);
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg = "MQTT Exception when trying to subscribe to topic: " +
|
||||
subscribeTopic + "\n\tReason: " + ex.getReasonCode() +
|
||||
"\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " +
|
||||
ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() +
|
||||
"\n\tException: " + ex;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(errorMsg);
|
||||
}
|
||||
throw new DeviceManagementException(errorMsg, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which is triggered once the MQTT client losers its connection to the broker.
|
||||
* A scheduler thread is spawned to continuously re-attempt and connect to the broker and
|
||||
* subscribe to the device's topic. This thread is scheduled to execute after every break
|
||||
* equal to that of the 'reConnectionInterval' of the MQTTClient.
|
||||
*
|
||||
* @param throwable a Throwable Object containing the details as to why the failure occurred.
|
||||
*/
|
||||
@Override
|
||||
public void connectionLost(Throwable throwable) {
|
||||
log.warn("Lost Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint + ".\nThis was due to - " + throwable.getMessage());
|
||||
|
||||
Runnable reSubscriber = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (!isConnected()) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Subscriber reconnecting to queue........");
|
||||
}
|
||||
try {
|
||||
connectAndSubscribe();
|
||||
} catch (DeviceManagementException e) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Could not reconnect and subscribe to ControlQueue.");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
|
||||
service.scheduleAtFixedRate(reSubscriber, 0, this.reConnectionInterval, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which is triggered upon receiving a MQTT Message from the broker. Spawns a
|
||||
* new thread that executes any actions to be taken with the received message.
|
||||
*
|
||||
* @param topic the MQTT-Topic to which the received message was published to and the
|
||||
* client was subscribed to.
|
||||
* @param mqttMessage the actual MQTT-Message that was received from the broker.
|
||||
*/
|
||||
@Override
|
||||
public void messageArrived(final String topic, final MqttMessage mqttMessage) {
|
||||
Thread subscriberThread = new Thread() {
|
||||
public void run() {
|
||||
postMessageArrived(topic, mqttMessage);
|
||||
}
|
||||
};
|
||||
subscriberThread.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback method which gets triggered upon successful completion of a message delivery to
|
||||
* the broker.
|
||||
*
|
||||
* @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the
|
||||
* specific message delivery.
|
||||
*/
|
||||
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
|
||||
String message = "";
|
||||
try {
|
||||
message = iMqttDeliveryToken.getMessage().toString();
|
||||
} catch (MqttException e) {
|
||||
log.error("Error occurred whilst trying to read the message from the MQTT delivery token.");
|
||||
}
|
||||
String topic = iMqttDeliveryToken.getTopics()[0];
|
||||
String client = iMqttDeliveryToken.getClient().getClientId();
|
||||
log.info("Message - '" + message + "' of client [" + client + "] for the topic (" + topic + ") was delivered successfully.");
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an abstract method used for post processing the received MQTT-message. This
|
||||
* method will be implemented as per requirement at the time of creating an object of this
|
||||
* class.
|
||||
*
|
||||
* @param topic The topic for which the message was received for.
|
||||
* @param message The message received for the subscription to the above topic.
|
||||
*/
|
||||
protected abstract void postMessageArrived(String topic, MqttMessage message);
|
||||
|
||||
/**
|
||||
* Gets the MQTTClient object.
|
||||
*
|
||||
* @return the MQTTClient object.
|
||||
*/
|
||||
public MqttClient getClient() {
|
||||
return client;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.xmpp;
|
||||
|
||||
public class XmppAccount {
|
||||
private String username;
|
||||
private String password;
|
||||
private String accountName;
|
||||
private String email;
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getAccountName() {
|
||||
return accountName;
|
||||
}
|
||||
|
||||
public void setAccountName(String accountName) {
|
||||
this.accountName = accountName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,95 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.xmpp;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
|
||||
public class XmppConfig {
|
||||
private String xmppServerIP;
|
||||
private int xmppServerPort;
|
||||
private String xmppEndpoint;
|
||||
private String xmppUsername;
|
||||
private String xmppPassword;
|
||||
private boolean isEnabled;
|
||||
|
||||
private static final String XMPP_QUEUE_CONFIG_NAME = "XMPP";
|
||||
private final int SERVER_CONNECTION_PORT = 5222;
|
||||
|
||||
private ControlQueue xmppControlQueue;
|
||||
|
||||
private static XmppConfig xmppConfig = new XmppConfig();
|
||||
|
||||
public String getXmppServerIP() {
|
||||
return xmppServerIP;
|
||||
}
|
||||
|
||||
public int getXmppServerPort() {
|
||||
return xmppServerPort;
|
||||
}
|
||||
|
||||
public String getXmppEndpoint() {
|
||||
return xmppEndpoint;
|
||||
}
|
||||
|
||||
public String getXmppUsername() {
|
||||
return xmppUsername;
|
||||
}
|
||||
|
||||
public String getXmppPassword() {
|
||||
return xmppPassword;
|
||||
}
|
||||
|
||||
public ControlQueue getXmppControlQueue() {
|
||||
return xmppControlQueue;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
public static String getXmppQueueConfigName() {
|
||||
return XMPP_QUEUE_CONFIG_NAME;
|
||||
}
|
||||
|
||||
private XmppConfig() {
|
||||
xmppControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue(
|
||||
XMPP_QUEUE_CONFIG_NAME);
|
||||
|
||||
xmppServerIP = xmppControlQueue.getServerURL();
|
||||
int indexOfChar = xmppServerIP.lastIndexOf('/');
|
||||
if (indexOfChar != -1) {
|
||||
xmppServerIP = xmppServerIP.substring((indexOfChar + 1), xmppServerIP.length());
|
||||
}
|
||||
|
||||
xmppServerPort = xmppControlQueue.getPort();
|
||||
xmppEndpoint = xmppControlQueue.getServerURL() + ":" + xmppServerPort;
|
||||
xmppUsername = xmppControlQueue.getUsername();
|
||||
xmppPassword = xmppControlQueue.getPassword();
|
||||
isEnabled = xmppControlQueue.isEnabled();
|
||||
}
|
||||
|
||||
public static XmppConfig getInstance() {
|
||||
return xmppConfig;
|
||||
}
|
||||
|
||||
public int getSERVER_CONNECTION_PORT() {
|
||||
return SERVER_CONNECTION_PORT;
|
||||
}
|
||||
}
|
||||
@ -1,303 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.xmpp;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.jivesoftware.smack.ConnectionConfiguration;
|
||||
import org.jivesoftware.smack.PacketListener;
|
||||
import org.jivesoftware.smack.SmackConfiguration;
|
||||
import org.jivesoftware.smack.XMPPConnection;
|
||||
import org.jivesoftware.smack.XMPPException;
|
||||
import org.jivesoftware.smack.filter.AndFilter;
|
||||
import org.jivesoftware.smack.filter.FromContainsFilter;
|
||||
import org.jivesoftware.smack.filter.OrFilter;
|
||||
import org.jivesoftware.smack.filter.PacketFilter;
|
||||
import org.jivesoftware.smack.filter.PacketTypeFilter;
|
||||
import org.jivesoftware.smack.filter.ToContainsFilter;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.jivesoftware.smack.packet.Packet;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
|
||||
/**
|
||||
* This class contains the Agent specific implementation for all the XMPP functionality. This
|
||||
* includes connecting to a XMPP Server & Login using the device's XMPP-Account, Setting
|
||||
* listeners and filters on incoming XMPP messages and Sending XMPP replies for control signals
|
||||
* received. Makes use of the 'Smack-XMPP' library provided by jivesoftware/igniterealtime.
|
||||
* <p/>
|
||||
* It is an abstract class with an abstract method 'processXMPPMessage' allowing the user to have
|
||||
* their own implementation of the actions to be taken upon receiving an appropriate XMPP message.
|
||||
*/
|
||||
public abstract class XmppConnector {
|
||||
private static final Log log = LogFactory.getLog(XmppConnector.class);
|
||||
|
||||
private int replyTimeoutInterval = 500; // millis
|
||||
private String server;
|
||||
private int port;
|
||||
private ConnectionConfiguration config;
|
||||
private XMPPConnection connection;
|
||||
private PacketFilter filter;
|
||||
private PacketListener listener;
|
||||
|
||||
/**
|
||||
* Constructor for XMPPClient passing server-IP and the XMPP-port.
|
||||
*
|
||||
* @param server the IP of the XMPP server.
|
||||
* @param port the XMPP server's port to connect to. (default - 5222)
|
||||
*/
|
||||
public XmppConnector(String server, int port) {
|
||||
this.server = server;
|
||||
this.port = port;
|
||||
initXMPPClient();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the XMPP Client.
|
||||
* Sets the time-out-limit whilst waiting for XMPP-replies from server. Creates the XMPP
|
||||
* configurations to connect to the server and creates the XMPPConnection object used for
|
||||
* connecting and Logging-In.
|
||||
*/
|
||||
private void initXMPPClient() {
|
||||
log.info(String.format(
|
||||
"Initializing connection to XMPP Server at %1$s via port %2$d......", server,
|
||||
port));
|
||||
SmackConfiguration.setPacketReplyTimeout(replyTimeoutInterval);
|
||||
config = new ConnectionConfiguration(server, port);
|
||||
// TODO:: Need to enable SASL-Authentication appropriately
|
||||
config.setSASLAuthenticationEnabled(false);
|
||||
config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
|
||||
connection = new XMPPConnection(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to the XMPP-Server and if successfully established connection, then tries to Log
|
||||
* in using the device's XMPP Account credentials. (The XMPP-Account specific to the device is
|
||||
* created in the XMPP server whilst downloading the Agent from the IoT Server) .
|
||||
*
|
||||
* @param username the username of the device's XMPP-Account.
|
||||
* @param password the password of the device's XMPP-Account.
|
||||
* @param resource the resource the resource, specific to the XMPP-Account to which the login
|
||||
* is made to
|
||||
* @throws DeviceManagementException in the event of 'Connecting to' or 'Logging into' the
|
||||
* XMPP server fails.
|
||||
*/
|
||||
public void connectAndLogin(String username, String password, String resource)
|
||||
throws DeviceManagementException {
|
||||
try {
|
||||
connection.connect();
|
||||
log.info(String.format(
|
||||
"Connection to XMPP Server at %1$s established successfully......", server));
|
||||
|
||||
} catch (XMPPException xmppExcepion) {
|
||||
String errorMsg =
|
||||
"Connection attempt to the XMPP Server at " + server + " via port " + port +
|
||||
" failed.";
|
||||
log.info(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, xmppExcepion);
|
||||
}
|
||||
|
||||
if (connection.isConnected()) {
|
||||
try {
|
||||
if (resource == null) {
|
||||
connection.login(username, password);
|
||||
log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......",
|
||||
server, username));
|
||||
} else {
|
||||
connection.login(username, password, resource);
|
||||
log.info(String.format(
|
||||
"Logged into XMPP Server at %1$s as user %2$s on resource %3$s......",
|
||||
server, username, resource));
|
||||
}
|
||||
} catch (XMPPException xmppException) {
|
||||
String errorMsg =
|
||||
"Login attempt to the XMPP Server at " + server + " with username - " +
|
||||
username + " failed.";
|
||||
log.info(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, xmppException);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a filter on all the incoming XMPP-Messages for the JID (XMPP-Account ID) passed in.
|
||||
* Also creates a listener for the incoming messages and connects the listener to the
|
||||
* XMPPConnection alongside the set filter.
|
||||
*
|
||||
* @param senderJID the JID (XMPP-Account ID) to which the filter is to be set.
|
||||
*/
|
||||
public void setMessageFilterOnSender(String senderJID) {
|
||||
filter = new AndFilter(new PacketTypeFilter(Message.class), new FromContainsFilter(
|
||||
senderJID));
|
||||
listener = new PacketListener() {
|
||||
@Override
|
||||
public void processPacket(Packet packet) {
|
||||
if (packet instanceof Message) {
|
||||
final Message xmppMessage = (Message) packet;
|
||||
Thread msgProcessThread = new Thread() {
|
||||
public void run() {
|
||||
processXMPPMessage(xmppMessage);
|
||||
}
|
||||
};
|
||||
msgProcessThread.start();
|
||||
}
|
||||
}
|
||||
};
|
||||
connection.addPacketListener(listener, filter);
|
||||
}
|
||||
|
||||
|
||||
public void setMessageFilterOnReceiver(String receiverJID) {
|
||||
filter = new AndFilter(new PacketTypeFilter(Message.class), new ToContainsFilter(
|
||||
receiverJID));
|
||||
listener = new PacketListener() {
|
||||
@Override
|
||||
public void processPacket(Packet packet) {
|
||||
if (packet instanceof Message) {
|
||||
final Message xmppMessage = (Message) packet;
|
||||
Thread msgProcessThread = new Thread() {
|
||||
public void run() {
|
||||
processXMPPMessage(xmppMessage);
|
||||
}
|
||||
};
|
||||
msgProcessThread.start();
|
||||
}
|
||||
}
|
||||
};
|
||||
connection.addPacketListener(listener, filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a filter on all the incoming XMPP-Messages for the From-JID & To-JID (XMPP-Account IDs)
|
||||
* passed in. Also creates a listener for the incoming messages and connects the listener to
|
||||
* the XMPPConnection alongside the set filter.
|
||||
*
|
||||
* @param senderJID the From-JID (XMPP-Account ID) to which the filter is to be set.
|
||||
* @param receiverJID the To-JID (XMPP-Account ID) to which the filter is to be set.
|
||||
* @param andCondition if true: then filter is set with 'AND' operator (senderJID &&
|
||||
* receiverJID),
|
||||
* if false: then the filter is set with 'OR' operator (senderJID |
|
||||
* receiverJID)
|
||||
*/
|
||||
public void setSenderReceiverMessageFilter(String senderJID, String receiverJID, boolean
|
||||
andCondition) {
|
||||
PacketFilter jidFilter;
|
||||
|
||||
if (andCondition) {
|
||||
jidFilter = new AndFilter(new FromContainsFilter(senderJID), new ToContainsFilter(
|
||||
receiverJID));
|
||||
} else {
|
||||
jidFilter = new OrFilter(new FromContainsFilter(senderJID), new ToContainsFilter(
|
||||
receiverJID));
|
||||
}
|
||||
|
||||
filter = new AndFilter(new PacketTypeFilter(Message.class), jidFilter);
|
||||
listener = new PacketListener() {
|
||||
@Override
|
||||
public void processPacket(Packet packet) {
|
||||
if (packet instanceof Message) {
|
||||
final Message xmppMessage = (Message) packet;
|
||||
Thread msgProcessThread = new Thread() {
|
||||
public void run() {
|
||||
processXMPPMessage(xmppMessage);
|
||||
}
|
||||
};
|
||||
msgProcessThread.start();
|
||||
}
|
||||
}
|
||||
};
|
||||
connection.addPacketListener(listener, filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an XMPP message
|
||||
*
|
||||
* @param JID the JID (XMPP Account ID) to which the message is to be sent to.
|
||||
* @param message the XMPP-Message that is to be sent.
|
||||
*/
|
||||
public void sendXMPPMessage(String JID, String message) {
|
||||
sendXMPPMessage(JID, message, "Reply-From-Device");
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Message: " + message + " to XMPP JID [" + JID + "] sent successfully");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Overloaded method to send an XMPP message. Includes the subject to be mentioned in the
|
||||
* message that is sent.
|
||||
*
|
||||
* @param JID the JID (XMPP Account ID) to which the message is to be sent to.
|
||||
* @param message the XMPP-Message that is to be sent.
|
||||
* @param subject the subject that the XMPP-Message would carry.
|
||||
*/
|
||||
public void sendXMPPMessage(String JID, String message, String subject) {
|
||||
Message xmppMessage = new Message();
|
||||
xmppMessage.setTo(JID);
|
||||
xmppMessage.setSubject(subject);
|
||||
xmppMessage.setBody(message);
|
||||
xmppMessage.setType(Message.Type.chat);
|
||||
connection.sendPacket(xmppMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether the connection to the XMPP-Server persists.
|
||||
*
|
||||
* @return true if the client is connected to the XMPP-Server, else false.
|
||||
*/
|
||||
public boolean isConnected() {
|
||||
return connection.isConnected();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the client's time-out-limit whilst waiting for XMPP-replies from server.
|
||||
*
|
||||
* @param millis the time in millis to be set as the time-out-limit whilst waiting for a
|
||||
* XMPP-reply.
|
||||
*/
|
||||
public void setReplyTimeoutInterval(int millis) {
|
||||
this.replyTimeoutInterval = millis;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables default debugger provided by the XMPPConnection.
|
||||
*/
|
||||
public void disableDebugger() {
|
||||
connection.DEBUG_ENABLED = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection to the XMPP Server.
|
||||
*/
|
||||
public void closeConnection() {
|
||||
if (connection != null && connection.isConnected()) {
|
||||
connection.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This is an abstract method used for post processing the received XMPP-message. This
|
||||
* method will be implemented as per requirement at the time of creating an object of this
|
||||
* class.
|
||||
*
|
||||
* @param xmppMessage the xmpp message received by the listener.
|
||||
*/
|
||||
protected abstract void processXMPPMessage(Message xmppMessage);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@ -1,160 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.controlqueue.xmpp;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpHeaders;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException;
|
||||
import org.wso2.carbon.device.mgt.etc.util.IoTUtil;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class XmppServerClient implements ControlQueueConnector {
|
||||
|
||||
private static final Log log = LogFactory.getLog(XmppServerClient.class);
|
||||
|
||||
private static final String XMPP_SERVER_API_CONTEXT = "/plugins/restapi/v1";
|
||||
private static final String USERS_API = "/users";
|
||||
private static final String GROUPS_API = "/groups";
|
||||
private static final String APPLICATION_JSON_MT = "application/json";
|
||||
|
||||
private String xmppEndpoint;
|
||||
private String xmppUsername;
|
||||
private String xmppPassword;
|
||||
private boolean xmppEnabled = false;
|
||||
|
||||
public XmppServerClient() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void initControlQueue() throws DeviceControllerException {
|
||||
xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint();
|
||||
xmppUsername = XmppConfig.getInstance().getXmppUsername();
|
||||
xmppPassword = XmppConfig.getInstance().getXmppPassword();
|
||||
xmppEnabled = XmppConfig.getInstance().isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enqueueControls(HashMap<String, String> deviceControls)
|
||||
throws DeviceControllerException {
|
||||
if (!xmppEnabled) {
|
||||
log.warn("XMPP <Enabled> set to false in 'device-mgt-config.xml'");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException {
|
||||
if (xmppEnabled) {
|
||||
String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + USERS_API;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("The API Endpoint URL of the XMPP Server is set to: " +
|
||||
xmppUsersAPIEndpoint);
|
||||
}
|
||||
|
||||
String encodedString = xmppUsername + ":" + xmppPassword;
|
||||
encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8)));
|
||||
String authorizationHeader = "Basic " + encodedString;
|
||||
String jsonRequest ="{\n" +
|
||||
" \"username\": \""+newUserAccount.getUsername()+"\"," +
|
||||
" \"password\": \""+newUserAccount.getPassword()+"\"," +
|
||||
" \"name\": \""+newUserAccount.getAccountName()+"\"," +
|
||||
" \"email\": \""+newUserAccount.getEmail()+"\"," +
|
||||
" \"properties\": {" +
|
||||
" \"property\": [" +
|
||||
" {" +
|
||||
" \"@key\": \"console.rows_per_page\"," +
|
||||
" \"@value\": \"user-summary=8\"" +
|
||||
" }," +
|
||||
" {" +
|
||||
" \"@key\": \"console.order\"," +
|
||||
" \"@value\": \"session-summary=1\"" +
|
||||
" }" +
|
||||
" ]" +
|
||||
" }" +
|
||||
"}";
|
||||
StringEntity requestEntity;
|
||||
try {
|
||||
requestEntity = new StringEntity(jsonRequest,"application/json","UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
URL xmppUserApiUrl;
|
||||
try {
|
||||
xmppUserApiUrl = new URL(xmppUsersAPIEndpoint);
|
||||
} catch (MalformedURLException e) {
|
||||
String errMsg = "Malformed URL + " + xmppUsersAPIEndpoint;
|
||||
log.error(errMsg);
|
||||
throw new DeviceControllerException(errMsg);
|
||||
}
|
||||
HttpClient httpClient;
|
||||
try {
|
||||
httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol());
|
||||
} catch (Exception e) {
|
||||
log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :"
|
||||
+ xmppUserApiUrl.getProtocol());
|
||||
return false;
|
||||
}
|
||||
HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint);
|
||||
|
||||
httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader);
|
||||
httpPost.setEntity(requestEntity);
|
||||
|
||||
|
||||
|
||||
try {
|
||||
HttpResponse httpResponse = httpClient.execute(httpPost);
|
||||
|
||||
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
|
||||
String response = IoTUtil.getResponseString(httpResponse);
|
||||
String errorMsg = "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() +
|
||||
"' for account creation with error:\n" + response;
|
||||
log.error(errorMsg);
|
||||
throw new DeviceControllerException(errorMsg);
|
||||
} else {
|
||||
EntityUtils.consume(httpResponse.getEntity());
|
||||
return true;
|
||||
}
|
||||
} catch (IOException | DeviceMgtCommonsException e) {
|
||||
String errorMsg =
|
||||
"Error occurred whilst trying a 'POST' at : " + xmppUsersAPIEndpoint + " error: " + e.getMessage();
|
||||
log.error(errorMsg);
|
||||
throw new DeviceControllerException(errorMsg, e);
|
||||
}
|
||||
|
||||
} else {
|
||||
log.warn("XMPP <Enabled> set to false in 'device-mgt-config.xml'");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.datastore;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* The Interface DataStoreConnector.
|
||||
*
|
||||
*/
|
||||
public interface DataStoreConnector {
|
||||
|
||||
/**
|
||||
* Initializes the data store.
|
||||
* This method loads the initial configurations relevant to the
|
||||
* Data-Store implementation where the sensor data will pushed into
|
||||
*
|
||||
* @return A status message according to the outcome of the
|
||||
* method execution.
|
||||
*/
|
||||
void initDataStore(DataStore config) throws DeviceControllerException;
|
||||
|
||||
/**
|
||||
* Pushes the device/sensor data received from the devices into the
|
||||
* implemented data-store
|
||||
*
|
||||
* @param deviceData
|
||||
* A Hash Map which contains the parameters relevant to the
|
||||
* device and the actual device-data to be pushed into
|
||||
* the datastore
|
||||
* @return A status message according to the outcome of the
|
||||
* method execution.
|
||||
*/
|
||||
void publishDeviceData(HashMap<String, String> deviceData)
|
||||
throws DeviceControllerException;
|
||||
}
|
||||
@ -1,125 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.datastore.impl;
|
||||
|
||||
public class DataStreamDefinitions {
|
||||
|
||||
public final class StreamTypeLabel {
|
||||
|
||||
public static final String TEMPERATURE = "TEMPERATURE";
|
||||
public static final String FAN = "FAN";
|
||||
public static final String BULB = "BULB";
|
||||
public static final String SONAR = "SONAR";
|
||||
public static final String LIGHT = "LIGHT";
|
||||
public static final String MOTION = "MOTION";
|
||||
|
||||
}
|
||||
|
||||
public final static String TEMPERATURE_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org.wso2.iot.devices.temperature'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Temperature Data',"
|
||||
+ " 'description': 'Temperature data received from the Device',"
|
||||
+ " 'tags': ['iot', 'temperature']," + " 'metaData': ["
|
||||
+ " {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'temperature','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
public final static String BULB_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org_wso2_iot_devices_bulb'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Bulb Status',"
|
||||
+ " 'description': 'State of the bulb attached to a Device'," +
|
||||
" 'tags': ['iot', 'bulb'],"
|
||||
+ " 'metaData': [" +
|
||||
" {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'status','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
public final static String FAN_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org_wso2_iot_devices_fan'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Fan Status'," +
|
||||
" 'description': 'State of the Fan attached to a Device',"
|
||||
+ " 'tags': ['iot', 'fan']," + " 'metaData': ["
|
||||
+ " {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'status','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
public final static String MOTION_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org_wso2_iot_devices_motion'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Motion Data'," +
|
||||
" 'description': 'Motion data received from the Device',"
|
||||
+ " 'tags': ['iot', 'motion']," + " 'metaData': ["
|
||||
+ " {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'motion','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
public final static String SONAR_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org_wso2_iot_devices_sonar'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Sonar Data'," +
|
||||
" 'description': 'Sonar data received from the Device',"
|
||||
+ " 'tags': ['iot', 'sonar']," + " 'metaData': ["
|
||||
+ " {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'sonar','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
public final static String LIGHT_STREAM_DEFINITION =
|
||||
"{" + " 'name':'org_wso2_iot_devices_light'," + " 'version':'1.0.0',"
|
||||
+ " 'nickName': 'Light Data'," +
|
||||
" 'description': 'Light data received from the Device',"
|
||||
+ " 'tags': ['iot', 'light']," + " 'metaData': ["
|
||||
+ " {'name':'owner','type':'STRING'},"
|
||||
+ " {'name':'deviceType','type':'STRING'},"
|
||||
+ " {'name':'deviceId','type':'STRING'},"
|
||||
+ " {'name':'time','type':'LONG'}" + " " +
|
||||
"]," +
|
||||
" "
|
||||
+ " 'payloadData': [" +
|
||||
" {'name':'light','type':'STRING'}"
|
||||
+ " ]" + "}";
|
||||
|
||||
}
|
||||
@ -1,192 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.datastore.impl;
|
||||
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.databridge.agent.DataPublisher;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException;
|
||||
import org.wso2.carbon.databridge.agent.exception.DataEndpointException;
|
||||
import org.wso2.carbon.databridge.commons.exception.AuthenticationException;
|
||||
import org.wso2.carbon.databridge.commons.exception.DifferentStreamDefinitionAlreadyDefinedException;
|
||||
import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException;
|
||||
import org.wso2.carbon.databridge.commons.exception.SessionTimeoutException;
|
||||
import org.wso2.carbon.databridge.commons.exception.TransportException;
|
||||
import org.wso2.carbon.databridge.core.DataBridgeReceiverService;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore;
|
||||
import org.wso2.carbon.device.mgt.etc.datastore.DataStoreConnector;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.etc.internal.DeviceMgtCommonDataHolder;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class ThriftDataStoreConnector implements DataStoreConnector {
|
||||
|
||||
private static final Log log = LogFactory.getLog(ThriftDataStoreConnector.class);
|
||||
|
||||
private String dataStoreEndpoint;
|
||||
private String dataStoreUsername;
|
||||
private String dataStorePassword;
|
||||
private boolean enabled = false;
|
||||
|
||||
@Override
|
||||
public void initDataStore(DataStore config) throws DeviceControllerException {
|
||||
dataStoreEndpoint = config.getServerURL() + ":" + config.getPort();
|
||||
dataStoreUsername = config.getUsername();
|
||||
dataStorePassword = config.getPassword();
|
||||
enabled = config.isEnabled();
|
||||
}
|
||||
|
||||
private DataPublisher getDataPublisher() throws DeviceControllerException {
|
||||
|
||||
try {
|
||||
DataPublisher dataPublisher = new DataPublisher(dataStoreEndpoint, dataStoreUsername,
|
||||
dataStorePassword);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.info("data publisher created for endpoint " + dataStoreEndpoint);
|
||||
}
|
||||
return dataPublisher;
|
||||
} catch (DataEndpointAuthenticationException | DataEndpointAgentConfigurationException | DataEndpointException
|
||||
| DataEndpointConfigurationException | TransportException e) {
|
||||
String error = "Error creating data publisher for endpoint: " + dataStoreEndpoint +
|
||||
"with credentials, username-" + dataStoreUsername + " and password-" +
|
||||
dataStorePassword + ": ";
|
||||
log.error(error);
|
||||
throw new DeviceControllerException(error);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(HashMap<String, String> deviceData) throws
|
||||
DeviceControllerException {
|
||||
//TODO: Create a threadpool and publish the Data or use a queue and publish to it and
|
||||
// have a data retreiver.
|
||||
DataPublisher dataPublisher = getDataPublisher();
|
||||
if (!enabled || dataPublisher == null) {
|
||||
throw new DeviceControllerException();
|
||||
}
|
||||
|
||||
String owner = deviceData.get("owner");
|
||||
String deviceType = deviceData.get("deviceType");
|
||||
String deviceId = deviceData.get("deviceId");
|
||||
String time = deviceData.get("time");
|
||||
String key = deviceData.get("key");
|
||||
String value = deviceData.get("value");
|
||||
String description = deviceData.get("description");
|
||||
String deviceDataStream = null;
|
||||
String sessionId;
|
||||
|
||||
DataBridgeReceiverService dataBridgeReceiverService = DeviceMgtCommonDataHolder.getDataBridgeReceiverService();
|
||||
try {
|
||||
//TODO: read from configuration
|
||||
sessionId = dataBridgeReceiverService.login("admin", "admin");
|
||||
} catch (AuthenticationException e) {
|
||||
String error = "Error in login in to data publisher";
|
||||
log.error(error);
|
||||
throw new DeviceControllerException(error, e);
|
||||
}
|
||||
try {
|
||||
//TODO: read from configuration
|
||||
switch (description) {
|
||||
case DataStreamDefinitions.StreamTypeLabel.TEMPERATURE:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Temperature");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, DataStreamDefinitions.TEMPERATURE_STREAM_DEFINITION);
|
||||
|
||||
break;
|
||||
case DataStreamDefinitions.StreamTypeLabel.MOTION:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Motion (PIR)");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId,
|
||||
DataStreamDefinitions.MOTION_STREAM_DEFINITION);
|
||||
break;
|
||||
case DataStreamDefinitions.StreamTypeLabel.SONAR:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Sonar");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId,
|
||||
DataStreamDefinitions.SONAR_STREAM_DEFINITION);
|
||||
break;
|
||||
case DataStreamDefinitions.StreamTypeLabel.LIGHT:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Light");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId,
|
||||
DataStreamDefinitions.LIGHT_STREAM_DEFINITION);
|
||||
break;
|
||||
case DataStreamDefinitions.StreamTypeLabel.BULB:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Bulb Status");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId,
|
||||
DataStreamDefinitions.BULB_STREAM_DEFINITION);
|
||||
break;
|
||||
case DataStreamDefinitions.StreamTypeLabel.FAN:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Stream definition set to Fan Status");
|
||||
}
|
||||
deviceDataStream = dataBridgeReceiverService.defineStream(sessionId,
|
||||
DataStreamDefinitions.FAN_STREAM_DEFINITION);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (MalformedStreamDefinitionException | DifferentStreamDefinitionAlreadyDefinedException | SessionTimeoutException e) {
|
||||
String error = "Error in defining streams for data publisher";
|
||||
log.error(error);
|
||||
throw new DeviceControllerException(error, e);
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Publishing data");
|
||||
}
|
||||
dataPublisher.publish(deviceDataStream, System.currentTimeMillis(),
|
||||
new Object[]{owner, deviceType, deviceId, Long.parseLong(
|
||||
time)}, null,
|
||||
new Object[]{value});
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
String logMsg = "event published to devicePinDataStream\n" + "\tOwner: " + owner +
|
||||
"\tDeviceType: " + deviceType + "\n" + "\tDeviceId: " + deviceId +
|
||||
"\tTime: " +
|
||||
time + "\n" + "\tDescription: " + description + "\n" + "\tKey: " + key +
|
||||
"\tValue: " + value + "\n";
|
||||
log.info(logMsg);
|
||||
}
|
||||
|
||||
try {
|
||||
dataBridgeReceiverService.logout(sessionId);
|
||||
} catch (Exception e) {
|
||||
String error = "Error in login out from DataBridge Receiver Service";
|
||||
log.error(error);
|
||||
throw new DeviceControllerException(error, e);
|
||||
}
|
||||
}
|
||||
|
||||
public final class DataStoreConstants {
|
||||
public final static String BAM = "WSO2-BAM";
|
||||
public final static String CEP = "WSO2-CEP";
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.exception;
|
||||
|
||||
|
||||
public class AccessTokenException extends Exception {
|
||||
|
||||
|
||||
public AccessTokenException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public AccessTokenException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public AccessTokenException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public AccessTokenException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.exception;
|
||||
|
||||
public class DeviceControllerException extends Exception{
|
||||
|
||||
public DeviceControllerException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
|
||||
public DeviceControllerException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public DeviceControllerException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public DeviceControllerException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public DeviceControllerException() {
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.exception;
|
||||
|
||||
public class DeviceMgtCommonsException extends Exception {
|
||||
public DeviceMgtCommonsException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public DeviceMgtCommonsException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public DeviceMgtCommonsException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public DeviceMgtCommonsException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
protected DeviceMgtCommonsException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@ -1,43 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.exception;
|
||||
|
||||
public class NotImplementedException extends RuntimeException {
|
||||
|
||||
public NotImplementedException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public NotImplementedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public NotImplementedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public NotImplementedException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
protected NotImplementedException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.exception;
|
||||
|
||||
|
||||
public class UnauthorizedException extends Exception{
|
||||
|
||||
|
||||
|
||||
public UnauthorizedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public UnauthorizedException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public UnauthorizedException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public UnauthorizedException(String message, Throwable cause, boolean enableSuppression,
|
||||
boolean writableStackTrace) {
|
||||
super(message, cause, enableSuppression, writableStackTrace);
|
||||
}
|
||||
}
|
||||
@ -1,225 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.internal;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.osgi.framework.BundleContext;
|
||||
import org.osgi.service.component.ComponentContext;
|
||||
import org.wso2.carbon.core.ServerStartupObserver;
|
||||
import org.wso2.carbon.databridge.core.DataBridgeReceiverService;
|
||||
import org.wso2.carbon.device.mgt.etc.DeviceController;
|
||||
import org.wso2.carbon.device.mgt.etc.UserManagement;
|
||||
import org.wso2.carbon.device.mgt.etc.statistics.DeviceMgtEventsStatisticsClient;
|
||||
import org.wso2.carbon.device.mgt.etc.statistics.DeviceMgtUsageStatisticsClient;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.device.mgt.etc.service.DeviceTypeService;
|
||||
import org.wso2.carbon.device.mgt.etc.service.DeviceTypeServiceImpl;
|
||||
import org.wso2.carbon.device.mgt.etc.startup.StartupUrlPrinter;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dao.DeviceManagementDAOFactory;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dao.util.DeviceManagementDAOUtil;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.exception.DeviceMgtPluginException;
|
||||
import org.wso2.carbon.ndatasource.core.DataSourceService;
|
||||
import org.wso2.carbon.user.core.service.RealmService;
|
||||
import org.wso2.carbon.utils.ConfigurationContextService;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.device.mgt.common.DeviceManagementServiceComponent"
|
||||
* immediate="true"
|
||||
* @scr.reference name="user.realmservice.default"
|
||||
* interface="org.wso2.carbon.user.core.service.RealmService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setRealmService"
|
||||
* unbind="unsetRealmService"
|
||||
* @scr.reference name="org.wso2.carbon.ndatasource"
|
||||
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setDataSourceService"
|
||||
* unbind="unsetDataSourceService"
|
||||
* @scr.reference name="config.context.service"
|
||||
* interface="org.wso2.carbon.utils.ConfigurationContextService"
|
||||
* cardinality="0..1"
|
||||
* policy="dynamic"
|
||||
* bind="setConfigurationContextService"
|
||||
* unbind="unsetConfigurationContextService"
|
||||
* @scr.reference name="databridge.component"
|
||||
* interface="org.wso2.carbon.databridge.core.DataBridgeReceiverService"
|
||||
* cardinality="1..1"
|
||||
* policy="dynamic"
|
||||
* bind="setDataBridgeReceiverService"
|
||||
* unbind="unsetDataBridgeReceiverService"
|
||||
*/
|
||||
public class DeviceManagementServiceComponent {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceManagementServiceComponent.class);
|
||||
public static ConfigurationContextService configurationContextService;
|
||||
|
||||
protected void activate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Activating Iot Device Management Service Component");
|
||||
}
|
||||
try {
|
||||
BundleContext bundleContext = ctx.getBundleContext(); /* Initialize the data source configuration */
|
||||
DeviceCloudConfigManager.getInstance().initConfig();
|
||||
DeviceTypeConfigurationManager.getInstance().initConfig();
|
||||
Map<String, DeviceTypeConfig> dsConfigMap =
|
||||
DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap();
|
||||
|
||||
DeviceManagementDAOFactory.init(dsConfigMap);
|
||||
|
||||
String setupOption = System.getProperty("setup");
|
||||
if (setupOption != null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(
|
||||
"-Dsetup is enabled. Iot Device management repository schema initialization is about " +
|
||||
"to begin");
|
||||
}
|
||||
try {
|
||||
for (String pluginType : dsConfigMap.keySet()) {
|
||||
DeviceManagementDAOUtil
|
||||
.setupDeviceManagementSchema(
|
||||
DeviceManagementDAOFactory.getDataSourceMap
|
||||
().get(pluginType));
|
||||
}
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
log.error(
|
||||
"Exception occurred while initializing device management database schema",
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
DeviceMgtCommonDataHolder.getInstance().initialize();
|
||||
|
||||
//TODO: handle
|
||||
|
||||
DeviceController.init();
|
||||
DeviceMgtUsageStatisticsClient.initializeDataSource();
|
||||
DeviceMgtEventsStatisticsClient.initializeDataSource();
|
||||
UserManagement.registerApiAccessRoles();
|
||||
|
||||
|
||||
bundleContext.registerService(DeviceTypeService.class.getName(),
|
||||
new DeviceTypeServiceImpl(), null);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Iot Device Management Service Component has been successfully activated");
|
||||
}
|
||||
|
||||
bundleContext.registerService(ServerStartupObserver.class, new StartupUrlPrinter(), null);
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while activating Iot Device Management Service Component", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void deactivate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("De-activating Iot Device Management Service Component");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected void setDataSourceService(DataSourceService dataSourceService) {
|
||||
/* This is to avoid iot device management component getting initialized before the
|
||||
underlying datasources
|
||||
are registered */
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Data source service set to mobile service component");
|
||||
}
|
||||
}
|
||||
|
||||
protected void unsetDataSourceService(DataSourceService dataSourceService) {
|
||||
//do nothing
|
||||
}
|
||||
|
||||
protected void setConfigurationContextService(
|
||||
ConfigurationContextService configurationContextService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Setting ConfigurationContextService");
|
||||
}
|
||||
|
||||
DeviceManagementServiceComponent.configurationContextService = configurationContextService;
|
||||
|
||||
}
|
||||
|
||||
protected void unsetConfigurationContextService(
|
||||
ConfigurationContextService configurationContextService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Un-setting ConfigurationContextService");
|
||||
}
|
||||
DeviceManagementServiceComponent.configurationContextService = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets Realm Service
|
||||
*
|
||||
* @param realmService associated realm service reference
|
||||
*/
|
||||
protected void setRealmService(RealmService realmService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Setting Realm Service");
|
||||
|
||||
}
|
||||
UserManagement.setRealmService(realmService);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets Realm Service
|
||||
*
|
||||
* @param realmService associated realm service reference
|
||||
*/
|
||||
protected void unsetRealmService(RealmService realmService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Unsetting Realm Service");
|
||||
}
|
||||
UserManagement.setRealmService(realmService);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets DataBridge Receiver Service
|
||||
*
|
||||
* @param dataBridgeReceiverService associated DataBridge service reference
|
||||
*/
|
||||
protected void setDataBridgeReceiverService(
|
||||
DataBridgeReceiverService dataBridgeReceiverService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Setting DataBridge Receiver Service");
|
||||
}
|
||||
DeviceMgtCommonDataHolder.setDataBridgeReceiverService(dataBridgeReceiverService);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsets Realm Service
|
||||
*
|
||||
* @param dataBridgeReceiverService associated DataBridge service reference
|
||||
*/
|
||||
protected void unsetDataBridgeReceiverService(
|
||||
DataBridgeReceiverService dataBridgeReceiverService) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Unsetting DataBridge Receiver Service");
|
||||
}
|
||||
DeviceMgtCommonDataHolder.setDataBridgeReceiverService(null);
|
||||
}
|
||||
}
|
||||
@ -1,63 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.internal;
|
||||
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.databridge.core.DataBridgeReceiverService;
|
||||
|
||||
public class DeviceMgtCommonDataHolder {
|
||||
|
||||
private static DeviceMgtCommonDataHolder thisInstance = new DeviceMgtCommonDataHolder();
|
||||
private String trustStoreLocaiton;
|
||||
private String trustStorePassword;
|
||||
|
||||
private static DataBridgeReceiverService dataBridgeReceiverService;
|
||||
|
||||
private DeviceMgtCommonDataHolder() {}
|
||||
|
||||
public void initialize(){
|
||||
setTrustStore();
|
||||
}
|
||||
|
||||
public static DeviceMgtCommonDataHolder getInstance() {
|
||||
return thisInstance;
|
||||
}
|
||||
|
||||
private void setTrustStore(){
|
||||
this.trustStoreLocaiton = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Location");
|
||||
this.trustStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Password");
|
||||
}
|
||||
|
||||
public String getTrustStoreLocation(){
|
||||
return trustStoreLocaiton;
|
||||
}
|
||||
|
||||
public String getTrustStorePassword(){
|
||||
return trustStorePassword;
|
||||
}
|
||||
|
||||
public static DataBridgeReceiverService getDataBridgeReceiverService() {
|
||||
return dataBridgeReceiverService;
|
||||
}
|
||||
|
||||
public static void setDataBridgeReceiverService(
|
||||
DataBridgeReceiverService dataBridgeReceiverService) {
|
||||
DeviceMgtCommonDataHolder.dataBridgeReceiverService = dataBridgeReceiverService;
|
||||
}
|
||||
}
|
||||
@ -1,73 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.mqtt;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
|
||||
public class MqttConfig {
|
||||
private String mqttQueueEndpoint;
|
||||
private String mqttQueueUsername;
|
||||
private String mqttQueuePassword;
|
||||
private boolean isEnabled;
|
||||
|
||||
private static final String MQTT_QUEUE_CONFIG_NAME = "MQTT";
|
||||
|
||||
private ControlQueue mqttControlQueue;
|
||||
|
||||
private static MqttConfig mqttConfig = new MqttConfig();
|
||||
|
||||
public String getMqttQueueEndpoint() {
|
||||
return mqttQueueEndpoint;
|
||||
}
|
||||
|
||||
public String getMqttQueueUsername() {
|
||||
return mqttQueueUsername;
|
||||
}
|
||||
|
||||
public String getMqttQueuePassword() {
|
||||
return mqttQueuePassword;
|
||||
}
|
||||
|
||||
public ControlQueue getMqttControlQueue() {
|
||||
return mqttControlQueue;
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
public static String getMqttQueueConfigName() {
|
||||
return MQTT_QUEUE_CONFIG_NAME;
|
||||
}
|
||||
|
||||
private MqttConfig() {
|
||||
mqttControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue(
|
||||
MQTT_QUEUE_CONFIG_NAME);
|
||||
mqttQueueEndpoint = mqttControlQueue.getServerURL() + ":" + mqttControlQueue.getPort();
|
||||
mqttQueueUsername = mqttControlQueue.getUsername();
|
||||
mqttQueuePassword = mqttControlQueue.getPassword();
|
||||
isEnabled = mqttControlQueue.isEnabled();
|
||||
}
|
||||
|
||||
public static MqttConfig getInstance() {
|
||||
return mqttConfig;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,128 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.mqtt;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.paho.client.mqttv3.*;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
/**
|
||||
* The Class MqttControlPublisher. It is an implementation of the interface
|
||||
* ControlQueueConnector.
|
||||
* This implementation supports publishing of control signals received to an
|
||||
* MQTT end-point.
|
||||
* The configuration settings for the MQTT end-point are read from the
|
||||
* 'device-mgt-config.xml' file of the project.
|
||||
* This is done using the class 'DeviceCloudConfigManager.java' which loads
|
||||
* the settings from the default xml org.wso2.carbon.device.mgt.common
|
||||
* file -
|
||||
* /resources/conf/device-mgt-config.xml
|
||||
*/
|
||||
public class MqttPublisher implements MqttCallback {
|
||||
|
||||
private static final Log log = LogFactory.getLog(MqttPublisher.class);
|
||||
|
||||
private String mqttEndpoint;
|
||||
private String mqttUsername;
|
||||
private String mqttPassword;
|
||||
private boolean mqttEnabled = false;
|
||||
|
||||
public MqttPublisher() {
|
||||
}
|
||||
|
||||
public void initControlQueue() throws DeviceControllerException {
|
||||
mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
|
||||
mqttUsername = MqttConfig.getInstance().getMqttQueueUsername();
|
||||
mqttPassword = MqttConfig.getInstance().getMqttQueuePassword();
|
||||
mqttEnabled = MqttConfig.getInstance().isEnabled();
|
||||
}
|
||||
|
||||
public void publish(String publishClientId, String publishTopic, byte[] payload)
|
||||
throws DeviceControllerException {
|
||||
|
||||
if (mqttEnabled) {
|
||||
MqttClient client;
|
||||
MqttConnectOptions options;
|
||||
|
||||
if (publishClientId.length() > 24) {
|
||||
String errorString =
|
||||
"No of characters '" + publishClientId.length() + "' for ClientID: '" + publishClientId +
|
||||
"' is invalid (should be less than 24, hence please provide a " +
|
||||
"simple " +
|
||||
|
||||
|
||||
"'owner' tag)";
|
||||
log.error(errorString);
|
||||
throw new DeviceControllerException(errorString);
|
||||
} else {
|
||||
log.info("No of Characters " + publishClientId.length() + " for ClientID : '" + publishClientId +
|
||||
"' is acceptable");
|
||||
}
|
||||
|
||||
try {
|
||||
client = new MqttClient(mqttEndpoint,publishClientId);
|
||||
options = new MqttConnectOptions();
|
||||
options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true);
|
||||
client.setCallback(this);
|
||||
client.connect(options);
|
||||
|
||||
client.publish(publishTopic, payload, 0, true);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("MQTT Client successfully published to topic: " + publishTopic +
|
||||
", with payload - " + payload);
|
||||
}
|
||||
client.disconnect();
|
||||
} catch (MqttException ex) {
|
||||
String errorMsg =
|
||||
"MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() +
|
||||
"\n\tMessage: " +
|
||||
ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() +
|
||||
"\n\tCause: " + ex.getCause() + "\n\tException: " + ex;
|
||||
|
||||
log.error(errorMsg, ex);
|
||||
throw new DeviceControllerException(errorMsg, ex);
|
||||
}
|
||||
} else {
|
||||
log.warn("MQTT <Enabled> set to false in 'device-mgt-config.xml'");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connectionLost(Throwable arg0) {
|
||||
log.error("Connection to MQTT Endpoint Lost");
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken topic) {
|
||||
log.info("Published topic: '" + topic.getTopics()[0] + "' successfully to client: '" +
|
||||
topic.getClient().getClientId() + "'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageArrived(String arg0, MqttMessage arg1) throws Exception {
|
||||
log.info("MQTT Message received: " + arg1.toString());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@ -1,41 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.sensormgt;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.io.Serializable;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@XmlRootElement
|
||||
public class DeviceRecord implements Serializable{
|
||||
private Map<String, SensorRecord> sensorDataList = new HashMap<>();
|
||||
|
||||
public DeviceRecord(String sensorName, String sensorValue, long time) {
|
||||
sensorDataList.put(sensorName, new SensorRecord(sensorValue, time));
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public Map<String, SensorRecord> getSensorDataList() {
|
||||
return sensorDataList;
|
||||
}
|
||||
|
||||
public void addDeviceRecord(String sensorName, String sensorValue, long time){
|
||||
sensorDataList.put(sensorName, new SensorRecord(sensorValue, time));
|
||||
}
|
||||
}
|
||||
@ -1,129 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.sensormgt;
|
||||
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* This class is used to store latest sensor value readings against a device id in an in-memory map.
|
||||
*/
|
||||
public class SensorDataManager {
|
||||
|
||||
private static final SensorDataManager instance = new SensorDataManager();
|
||||
private Map<String, DeviceRecord> deviceMap = new HashMap<>();
|
||||
|
||||
private SensorDataManager() {
|
||||
}
|
||||
|
||||
public static SensorDataManager getInstance() {
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store sensor record in a map.
|
||||
* @param deviceId
|
||||
* @param sensorName
|
||||
* @param sensorValue
|
||||
* @param time
|
||||
* @return if success returns true
|
||||
*/
|
||||
public boolean setSensorRecord(String deviceId, String sensorName, String sensorValue, long time){
|
||||
|
||||
DeviceRecord deviceRecord = deviceMap.get(deviceId);
|
||||
if(deviceRecord==null){
|
||||
deviceRecord = new DeviceRecord(sensorName, sensorValue, time);
|
||||
}else{
|
||||
deviceRecord.addDeviceRecord(sensorName, sensorValue, time);
|
||||
}
|
||||
deviceMap.put(deviceId, deviceRecord);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns last updated sensor records list for a device
|
||||
* @param deviceId
|
||||
* @return list of sensor records
|
||||
*/
|
||||
public SensorRecord[] getSensorRecords(String deviceId) throws DeviceControllerException{
|
||||
DeviceRecord deviceRecord = deviceMap.get(deviceId);
|
||||
if(deviceRecord != null){
|
||||
Collection<SensorRecord> list = deviceRecord.getSensorDataList().values();
|
||||
return list.toArray(new SensorRecord[list.size()]);
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns last updated sensor record for a device's sensor
|
||||
* @param deviceId
|
||||
* @param sensorName
|
||||
* @return sensor record
|
||||
*/
|
||||
public SensorRecord getSensorRecord(String deviceId, String sensorName) throws
|
||||
DeviceControllerException{
|
||||
DeviceRecord deviceRecord = deviceMap.get(deviceId);
|
||||
if(deviceRecord != null){
|
||||
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
|
||||
if(sensorRecord != null){
|
||||
return sensorRecord;
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName);
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns last updated sensor value for a device's sensor
|
||||
* @param deviceId
|
||||
* @param sensorName
|
||||
* @return sensor reading
|
||||
*/
|
||||
public String getSensorRecordValue(String deviceId, String sensorName) throws DeviceControllerException{
|
||||
DeviceRecord deviceRecord = deviceMap.get(deviceId);
|
||||
if(deviceRecord != null){
|
||||
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
|
||||
if(sensorRecord != null){
|
||||
return sensorRecord.getSensorValue();
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName);
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns last updated sensor value reading time for a device's sensor
|
||||
* @param deviceId
|
||||
* @param sensorName
|
||||
* @return time in millis
|
||||
*/
|
||||
public long getSensorRecordTime(String deviceId, String sensorName) throws DeviceControllerException{
|
||||
DeviceRecord deviceRecord = deviceMap.get(deviceId);
|
||||
if(deviceRecord != null){
|
||||
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
|
||||
if(sensorRecord != null){
|
||||
return sensorRecord.getTime();
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName);
|
||||
}
|
||||
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,46 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.sensormgt;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.io.Serializable;
|
||||
|
||||
@XmlRootElement
|
||||
public class SensorRecord implements Serializable{
|
||||
//sensor value float, int, boolean all should be converted into string
|
||||
private String sensorValue;
|
||||
private long time;
|
||||
|
||||
public SensorRecord(String sensorValue, long time) {
|
||||
this.sensorValue = sensorValue;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public String getSensorValue() {
|
||||
return sensorValue;
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public long getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.service;
|
||||
|
||||
|
||||
public interface DeviceTypeService {
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.service;
|
||||
|
||||
|
||||
public class DeviceTypeServiceImpl implements DeviceTypeService {
|
||||
}
|
||||
@ -1,58 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.startup;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.core.ServerStartupObserver;
|
||||
import org.wso2.carbon.device.mgt.etc.internal.DeviceManagementServiceComponent;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
import org.wso2.carbon.utils.ConfigurationContextService;
|
||||
import org.wso2.carbon.utils.NetworkUtils;
|
||||
|
||||
public class StartupUrlPrinter implements ServerStartupObserver {
|
||||
private static final Log log = LogFactory.getLog(StartupUrlPrinter.class);
|
||||
@Override
|
||||
public void completingServerStartup() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void completedServerStartup() {
|
||||
printUrl();
|
||||
|
||||
|
||||
}
|
||||
private void printUrl() {
|
||||
// Hostname
|
||||
String hostName = "localhost";
|
||||
try {
|
||||
hostName = NetworkUtils.getMgtHostName();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
// HTTPS port
|
||||
String mgtConsoleTransport = CarbonUtils.getManagementTransport();
|
||||
ConfigurationContextService configContextService = DeviceManagementServiceComponent.configurationContextService;
|
||||
|
||||
int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
|
||||
|
||||
log.info("CDM - Device Common API Service: https://" + hostName + ":" + httpsPort + "/common");
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics;
|
||||
|
||||
public class DeviceEventsStatisticsException extends Exception{
|
||||
|
||||
private static final long serialVersionUID = -5743346027793277063L;
|
||||
|
||||
public DeviceEventsStatisticsException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public DeviceEventsStatisticsException(String msg, Throwable e) {
|
||||
super(msg, e);
|
||||
}
|
||||
|
||||
public DeviceEventsStatisticsException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
||||
@ -1,139 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.etc.statistics.dto.DeviceEventsDTO;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceMgtEventsStatisticsClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceMgtEventsStatisticsClient.class);
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB";
|
||||
|
||||
private static volatile DataSource dataSource = null;
|
||||
|
||||
|
||||
public static void initializeDataSource() throws DeviceEventsStatisticsException {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
|
||||
} catch (NamingException e) {
|
||||
throw new DeviceEventsStatisticsException("Error while looking up the data " +
|
||||
"source: " + DATA_SOURCE_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public List<DeviceEventsDTO> getRecentDeviceStats(String owner, int recordLimit)
|
||||
throws DeviceEventsStatisticsException {
|
||||
|
||||
if (dataSource == null) {
|
||||
throw new DeviceEventsStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration.");
|
||||
}
|
||||
|
||||
Connection connection = null;
|
||||
Statement statement = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
connection = dataSource.getConnection();
|
||||
statement = connection.createStatement();
|
||||
String query = null;
|
||||
String table = "DEVICE_EVENTS";
|
||||
|
||||
if(owner==null){
|
||||
throw new DeviceEventsStatisticsException("Owner cannot be null!");
|
||||
}
|
||||
|
||||
String ownerString = "";
|
||||
ownerString = String.format(" AND owner = '%s'", owner);
|
||||
|
||||
String limitString = "";
|
||||
if(recordLimit > 0){
|
||||
limitString = String.format(" LIMIT %d", recordLimit);
|
||||
}
|
||||
|
||||
query = String.format("SELECT * FROM %s WHERE 1=1 %s ORDER BY `time` DESC %s"
|
||||
,table, ownerString, limitString);
|
||||
|
||||
log.info("query: " + query);
|
||||
|
||||
if (query == null) {
|
||||
throw new DeviceEventsStatisticsException("SQL query is null!");
|
||||
}
|
||||
|
||||
List<DeviceEventsDTO> DeviceEventsDTOs = new ArrayList<DeviceEventsDTO>();
|
||||
rs = statement.executeQuery(query);
|
||||
while (rs.next()) {
|
||||
DeviceEventsDTO DeviceEventsDTO = new DeviceEventsDTO();
|
||||
DeviceEventsDTO.setTime(rs.getString("TIME"));
|
||||
DeviceEventsDTO.setDeviceActivity(rs.getString("ACTIVITY"));
|
||||
//(id + type) uniquely identifies a device
|
||||
DeviceEventsDTO.setDeviceId(rs.getString("DEVICEID"));
|
||||
DeviceEventsDTO.setDeviceType(rs.getString("DEVICETYPE"));
|
||||
|
||||
DeviceEventsDTOs.add(DeviceEventsDTO);
|
||||
|
||||
}
|
||||
|
||||
return DeviceEventsDTOs;
|
||||
|
||||
} catch (Exception e) {
|
||||
// throw new IoTEventsStatisticsException(
|
||||
// "Error occurred while querying from JDBC database", e);
|
||||
//Exception hiding to avoid GC error
|
||||
log.error("Error occurred while querying from JDBC database: " + e.getMessage());
|
||||
return new ArrayList<>();
|
||||
} finally {
|
||||
if (rs != null) {
|
||||
try {
|
||||
rs.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (statement != null) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,176 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.etc.statistics.dto.DeviceUsageDTO;
|
||||
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class DeviceMgtUsageStatisticsClient {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceMgtUsageStatisticsClient.class);
|
||||
|
||||
private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB";
|
||||
|
||||
private static volatile DataSource dataSource = null;
|
||||
|
||||
|
||||
public static void initializeDataSource() throws DeviceUsageStatisticsException {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME);
|
||||
} catch (NamingException e) {
|
||||
throw new DeviceUsageStatisticsException("Error while looking up the data " +
|
||||
"source: " + DATA_SOURCE_NAME);
|
||||
}
|
||||
}
|
||||
//
|
||||
// public List<DeviceUsageDTO> getTemperatureData(String user, String deviceId, String fromDate,
|
||||
// String toDate)
|
||||
// throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching temperature data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
//
|
||||
// public List<DeviceUsageDTO> getBulbStatusData(String user, String deviceId, String fromDate,
|
||||
// String toDate)
|
||||
// throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching bulb status data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_BULB_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
//
|
||||
// public List<DeviceUsageDTO> getFanStatusData(String user, String deviceId, String fromDate,
|
||||
// String toDate) throws IoTUsageStatisticsException {
|
||||
//
|
||||
// log.debug(String.format(
|
||||
// "Fetching fan status data. user : %s, deviceId : %s, from : %s, to : %s", user,
|
||||
// deviceId, fromDate, toDate));
|
||||
// return getDeviceStats("DEVICE_FAN_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate,
|
||||
// toDate);
|
||||
// }
|
||||
|
||||
public List<DeviceUsageDTO> getDeviceStats(String table, String valueColumn, String owner,
|
||||
String deviceId, String fromDate, String toDate)
|
||||
throws DeviceUsageStatisticsException {
|
||||
|
||||
if (dataSource == null) {
|
||||
throw new DeviceUsageStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration.");
|
||||
}
|
||||
|
||||
Connection connection = null;
|
||||
Statement statement = null;
|
||||
ResultSet rs = null;
|
||||
try {
|
||||
connection = dataSource.getConnection();
|
||||
statement = connection.createStatement();
|
||||
String query = null;
|
||||
|
||||
String ownerString = "";
|
||||
if (owner != null) {
|
||||
ownerString = String.format("owner = '%s' AND ", owner);
|
||||
}
|
||||
|
||||
if (fromDate != null && toDate != null) {
|
||||
//fromDate = getConvertedTime(fromDate);
|
||||
//toDate = getConvertedTime(toDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` "
|
||||
+ "BETWEEN '%s' AND '%s'", table, deviceId, fromDate, toDate);
|
||||
} else if (fromDate != null) {
|
||||
//fromDate = getConvertedTime(fromDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` >= "
|
||||
+ "'%s'", table, deviceId, fromDate);
|
||||
} else if (toDate != null) {
|
||||
//toDate = getConvertedTime(toDate);
|
||||
query = String.format(
|
||||
"SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` <= "
|
||||
+ "'%s'", table, deviceId, toDate);
|
||||
}
|
||||
|
||||
log.info("query: " + query);
|
||||
|
||||
if (query == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<DeviceUsageDTO> deviceUsageDTOs = new ArrayList<DeviceUsageDTO>();
|
||||
rs = statement.executeQuery(query);
|
||||
while (rs.next()) {
|
||||
DeviceUsageDTO deviceUsageDTO = new DeviceUsageDTO();
|
||||
deviceUsageDTO.setTime(rs.getString("TIME"));
|
||||
deviceUsageDTO.setValue(rs.getString(valueColumn));
|
||||
|
||||
deviceUsageDTOs.add(deviceUsageDTO);
|
||||
|
||||
}
|
||||
|
||||
return deviceUsageDTOs;
|
||||
|
||||
} catch (Exception e) {
|
||||
// throw new IoTUsageStatisticsException(
|
||||
// "Error occurred while querying from JDBC database", e);
|
||||
//Exception hiding to avoid GC error
|
||||
log.error("Error occurred while querying from JDBC database: " + e.getMessage());
|
||||
return new ArrayList<>();
|
||||
} finally {
|
||||
if (rs != null) {
|
||||
try {
|
||||
rs.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (statement != null) {
|
||||
try {
|
||||
statement.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
if (connection != null) {
|
||||
try {
|
||||
connection.close();
|
||||
} catch (SQLException ignore) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics;
|
||||
|
||||
public class DeviceUsageStatisticsException extends Exception{
|
||||
|
||||
private static final long serialVersionUID = -5743346027793277063L;
|
||||
|
||||
public DeviceUsageStatisticsException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public DeviceUsageStatisticsException(String msg, Throwable e) {
|
||||
super(msg, e);
|
||||
}
|
||||
|
||||
public DeviceUsageStatisticsException(Throwable throwable) {
|
||||
super(throwable);
|
||||
}
|
||||
}
|
||||
@ -1,60 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics.dto;
|
||||
|
||||
public class DeviceEventsDTO {
|
||||
|
||||
private String time;
|
||||
private String deviceId;
|
||||
private String deviceType;
|
||||
private String deviceActivity;
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getDeviceActivity() {
|
||||
return deviceActivity;
|
||||
}
|
||||
|
||||
public void setDeviceActivity(String deviceActivity) {
|
||||
this.deviceActivity = deviceActivity;
|
||||
}
|
||||
|
||||
public void setDeviceId(String deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public String getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public String getDeviceType() {
|
||||
return deviceType;
|
||||
}
|
||||
|
||||
public void setDeviceType(String deviceType) {
|
||||
this.deviceType = deviceType;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,42 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.statistics.dto;
|
||||
|
||||
public class DeviceUsageDTO {
|
||||
|
||||
private String time;
|
||||
private String value;
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public void setTime(String time) {
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,59 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
public class Claims {
|
||||
|
||||
private String dialectUrl;
|
||||
private String description;
|
||||
private String claimUrl;
|
||||
private String value;
|
||||
|
||||
public String getDialectUrl() {
|
||||
return dialectUrl;
|
||||
}
|
||||
|
||||
public void setDialectUrl(String dialectUrl) {
|
||||
this.dialectUrl = dialectUrl;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getClaimUrl() {
|
||||
return claimUrl;
|
||||
}
|
||||
|
||||
public void setClaimUrl(String claimUrl) {
|
||||
this.claimUrl = claimUrl;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
import java.io.Serializable;
|
||||
|
||||
@XmlRootElement
|
||||
public class DeviceTypes implements Serializable{
|
||||
|
||||
//private static final long serialVersionUID = 7526472295622776147L;
|
||||
|
||||
private String name;
|
||||
|
||||
|
||||
public DeviceTypes() {
|
||||
}
|
||||
|
||||
@XmlElement
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,92 +0,0 @@
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.HttpClient;
|
||||
import org.apache.http.conn.scheme.PlainSocketFactory;
|
||||
import org.apache.http.conn.scheme.Scheme;
|
||||
import org.apache.http.conn.scheme.SchemeRegistry;
|
||||
import org.apache.http.conn.ssl.SSLSocketFactory;
|
||||
import org.apache.http.impl.client.DefaultHttpClient;
|
||||
import org.apache.http.impl.conn.PoolingClientConnectionManager;
|
||||
import org.apache.http.params.BasicHttpParams;
|
||||
import org.apache.http.params.HttpParams;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException;
|
||||
import org.wso2.carbon.device.mgt.etc.internal.DeviceMgtCommonDataHolder;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.security.KeyManagementException;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
|
||||
|
||||
public class IoTUtil {
|
||||
|
||||
private static final Log log = LogFactory.getLog(IoTUtil.class);
|
||||
|
||||
/**
|
||||
* Return a http client instance
|
||||
* @param port - server port
|
||||
* @param protocol- service endpoint protocol http/https
|
||||
* @return
|
||||
*/
|
||||
public static HttpClient getHttpClient(int port, String protocol)
|
||||
throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
|
||||
KeyManagementException {
|
||||
SchemeRegistry registry = new SchemeRegistry();
|
||||
|
||||
if ("https".equals(protocol)) {
|
||||
System.setProperty("javax.net.ssl.trustStrore", DeviceMgtCommonDataHolder.getInstance().getTrustStoreLocation());
|
||||
System.setProperty("javax.net.ssl.trustStorePassword", DeviceMgtCommonDataHolder.getInstance().getTrustStorePassword());
|
||||
|
||||
if (port >= 0) {
|
||||
registry.register(new Scheme("https", port, SSLSocketFactory.getSocketFactory()));
|
||||
} else {
|
||||
registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
|
||||
}
|
||||
} else if ("http".equals(protocol)) {
|
||||
if (port >= 0) {
|
||||
registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory()));
|
||||
} else {
|
||||
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
|
||||
}
|
||||
}
|
||||
HttpParams params = new BasicHttpParams();
|
||||
PoolingClientConnectionManager tcm = new PoolingClientConnectionManager(registry);
|
||||
HttpClient client = new DefaultHttpClient(tcm, params);
|
||||
return client;
|
||||
}
|
||||
|
||||
public static String getResponseString(HttpResponse httpResponse) throws
|
||||
DeviceMgtCommonsException {
|
||||
BufferedReader br = null;
|
||||
try {
|
||||
br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
|
||||
String readLine;
|
||||
String response = "";
|
||||
while (((readLine = br.readLine()) != null)) {
|
||||
response += readLine;
|
||||
}
|
||||
return response;
|
||||
} catch (IOException e) {
|
||||
throw new DeviceMgtCommonsException("Error while reading the response from the remote. "
|
||||
+ e.getMessage(), e);
|
||||
} finally {
|
||||
EntityUtils.consumeQuietly(httpResponse.getEntity());
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Error while closing the connection! " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
|
||||
public class ResourceFileLoader {
|
||||
|
||||
private static Log log = LogFactory.getLog(ResourceFileLoader.class);
|
||||
private String filePath;
|
||||
|
||||
public ResourceFileLoader(String fileName) {
|
||||
String path = ResourceFileLoader.class.getClassLoader().getResource("").getPath();
|
||||
|
||||
String fullPath = path;
|
||||
try {
|
||||
fullPath = URLDecoder.decode(path, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
|
||||
}
|
||||
//log.info(fullPath);
|
||||
String pathArr[] = fullPath.split("/WEB-INF/classes/");
|
||||
filePath = pathArr[0] + fileName;
|
||||
|
||||
}
|
||||
|
||||
public String getPath() {
|
||||
return filePath;
|
||||
}
|
||||
|
||||
public File getFile() {
|
||||
File file = new File(filePath);
|
||||
return file;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,37 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
public class Role {
|
||||
|
||||
private String roleName;
|
||||
|
||||
public Role(String roleName) {
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return roleName;
|
||||
}
|
||||
|
||||
public void setRoleName(String roleName) {
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
}
|
||||
@ -1,252 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*
|
||||
*/
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class User {
|
||||
|
||||
private String userName;
|
||||
private String roleName;
|
||||
private String firstName;
|
||||
private String email;
|
||||
private String lastName;
|
||||
private String streatAddress;
|
||||
private String locality;
|
||||
private String region;
|
||||
private String postalCode;
|
||||
private String country;
|
||||
private String hone;
|
||||
private String im;
|
||||
private String organization;
|
||||
private String url;
|
||||
private String title;
|
||||
private String mobile;
|
||||
private String nickName;
|
||||
private String dateOfBirth;
|
||||
private String gender;
|
||||
private String accountStatus;
|
||||
private String challengeQuestion;
|
||||
private String identityClaimUri;
|
||||
private String tempEmailAddress;
|
||||
|
||||
|
||||
private ArrayList<Claims> claimList;
|
||||
|
||||
public User(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public User(String userName, String roleName) {
|
||||
this.userName = userName;
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
public void setUserName(String userName) {
|
||||
this.userName = userName;
|
||||
}
|
||||
|
||||
public String getRoleName() {
|
||||
return roleName;
|
||||
}
|
||||
|
||||
public void setRoleName(String roleName) {
|
||||
this.roleName = roleName;
|
||||
}
|
||||
|
||||
public ArrayList<Claims> getClaimList() {
|
||||
return claimList;
|
||||
}
|
||||
|
||||
public void setClaimList(ArrayList<Claims> claimList) {
|
||||
this.claimList = claimList;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getStreatAddress() {
|
||||
return streatAddress;
|
||||
}
|
||||
|
||||
public void setStreatAddress(String streatAddress) {
|
||||
this.streatAddress = streatAddress;
|
||||
}
|
||||
|
||||
public String getLocality() {
|
||||
return locality;
|
||||
}
|
||||
|
||||
public void setLocality(String locality) {
|
||||
this.locality = locality;
|
||||
}
|
||||
|
||||
public String getRegion() {
|
||||
return region;
|
||||
}
|
||||
|
||||
public void setRegion(String region) {
|
||||
this.region = region;
|
||||
}
|
||||
|
||||
public String getPostalCode() {
|
||||
return postalCode;
|
||||
}
|
||||
|
||||
public void setPostalCode(String postalCode) {
|
||||
this.postalCode = postalCode;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String getHone() {
|
||||
return hone;
|
||||
}
|
||||
|
||||
public void setHone(String hone) {
|
||||
this.hone = hone;
|
||||
}
|
||||
|
||||
public String getIm() {
|
||||
return im;
|
||||
}
|
||||
|
||||
public void setIm(String im) {
|
||||
this.im = im;
|
||||
}
|
||||
|
||||
public String getOrganization() {
|
||||
return organization;
|
||||
}
|
||||
|
||||
public void setOrganization(String organization) {
|
||||
this.organization = organization;
|
||||
}
|
||||
|
||||
public String getUrl() {
|
||||
return url;
|
||||
}
|
||||
|
||||
public void setUrl(String url) {
|
||||
this.url = url;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getMobile() {
|
||||
return mobile;
|
||||
}
|
||||
|
||||
public void setMobile(String mobile) {
|
||||
this.mobile = mobile;
|
||||
}
|
||||
|
||||
public String getNickName() {
|
||||
return nickName;
|
||||
}
|
||||
|
||||
public void setNickName(String nickName) {
|
||||
this.nickName = nickName;
|
||||
}
|
||||
|
||||
public String getDateOfBirth() {
|
||||
return dateOfBirth;
|
||||
}
|
||||
|
||||
public void setDateOfBirth(String dateOfBirth) {
|
||||
this.dateOfBirth = dateOfBirth;
|
||||
}
|
||||
|
||||
public String getGender() {
|
||||
return gender;
|
||||
}
|
||||
|
||||
public void setGender(String gender) {
|
||||
this.gender = gender;
|
||||
}
|
||||
|
||||
public String getAccountStatus() {
|
||||
return accountStatus;
|
||||
}
|
||||
|
||||
public void setAccountStatus(String accountStatus) {
|
||||
this.accountStatus = accountStatus;
|
||||
}
|
||||
|
||||
public String getChallengeQuestion() {
|
||||
return challengeQuestion;
|
||||
}
|
||||
|
||||
public void setChallengeQuestion(String challengeQuestion) {
|
||||
this.challengeQuestion = challengeQuestion;
|
||||
}
|
||||
|
||||
public String getIdentityClaimUri() {
|
||||
return identityClaimUri;
|
||||
}
|
||||
|
||||
public void setIdentityClaimUri(String identityClaimUri) {
|
||||
this.identityClaimUri = identityClaimUri;
|
||||
}
|
||||
|
||||
public String getTempEmailAddress() {
|
||||
return tempEmailAddress;
|
||||
}
|
||||
|
||||
public void setTempEmailAddress(String tempEmailAddress) {
|
||||
this.tempEmailAddress = tempEmailAddress;
|
||||
}
|
||||
}
|
||||
@ -1,30 +0,0 @@
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
public class ZipArchive {
|
||||
private File zipFile = null;
|
||||
private String fileName = null;
|
||||
private String deviceId = null;
|
||||
|
||||
public ZipArchive(String fileName, File zipFile) {
|
||||
this.fileName = fileName;
|
||||
this.zipFile = zipFile;
|
||||
}
|
||||
|
||||
public String getDeviceId() {
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
public void setDeviceId(String deviceId) {
|
||||
this.deviceId = deviceId;
|
||||
}
|
||||
|
||||
public File getZipFile() {
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
}
|
||||
@ -1,97 +0,0 @@
|
||||
package org.wso2.carbon.device.mgt.etc.util;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.controlqueue.xmpp.XmppConfig;
|
||||
import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil;
|
||||
import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
|
||||
public class ZipUtil {
|
||||
|
||||
public ZipArchive downloadSketch(String owner, String tenantDomain, String deviceType,
|
||||
String deviceId, String deviceName, String token,
|
||||
String refreshToken)
|
||||
throws DeviceManagementException {
|
||||
|
||||
if (owner == null || deviceType == null) {
|
||||
throw new DeviceManagementException("Invalid parameters for `owner` or `deviceType`");
|
||||
}
|
||||
|
||||
String sep = File.separator;
|
||||
String sketchFolder = "repository" + sep + "resources" + sep + "sketches";
|
||||
String archivesPath = CarbonUtils.getCarbonHome() + sep + sketchFolder + sep + "archives"
|
||||
+ sep + deviceId;
|
||||
String templateSketchPath = sketchFolder + sep + deviceType;
|
||||
|
||||
// String iotServerIP = System.getProperty("bind.address");
|
||||
String iotServerIP = System.getProperty("server.host");
|
||||
String httpsServerPort = System.getProperty("httpsPort");
|
||||
String httpServerPort = System.getProperty("httpPort");
|
||||
|
||||
String httpsServerEP = "https://" + iotServerIP + ":" + httpsServerPort;
|
||||
String httpServerEP = "http://" + iotServerIP + ":" + httpServerPort;
|
||||
|
||||
String apimHost =
|
||||
DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager()
|
||||
.getServerURL();
|
||||
|
||||
// int indexOfChar = apimIP.lastIndexOf(File.separator);
|
||||
// if (indexOfChar != -1) {
|
||||
// apimIP = apimIP.substring((indexOfChar + 1), apimIP.length());
|
||||
// }
|
||||
|
||||
String apimGatewayPort =
|
||||
DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager()
|
||||
.getGatewayPort();
|
||||
|
||||
String apimEndpoint = apimHost + ":" + apimGatewayPort;
|
||||
|
||||
String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
|
||||
// indexOfChar = mqttEndpoint.lastIndexOf(File.separator);
|
||||
// if (indexOfChar != -1) {
|
||||
// mqttEndpoint = mqttEndpoint.substring((indexOfChar + 1), mqttEndpoint.length());
|
||||
// }
|
||||
|
||||
String xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint();
|
||||
// indexOfChar = xmppEndpoint.lastIndexOf(File.separator);
|
||||
// if (indexOfChar != -1) {
|
||||
// xmppEndpoint = xmppEndpoint.substring((indexOfChar + 1), xmppEndpoint.length());
|
||||
// }
|
||||
|
||||
int indexOfChar = xmppEndpoint.lastIndexOf(":");
|
||||
if (indexOfChar != -1) {
|
||||
xmppEndpoint = xmppEndpoint.substring(0, indexOfChar);
|
||||
}
|
||||
|
||||
xmppEndpoint = xmppEndpoint + ":" + XmppConfig.getInstance().getSERVER_CONNECTION_PORT();
|
||||
|
||||
Map<String, String> contextParams = new HashMap<String, String>();
|
||||
contextParams.put("DEVICE_OWNER", owner);
|
||||
contextParams.put("DEVICE_ID", deviceId);
|
||||
contextParams.put("DEVICE_NAME", deviceName);
|
||||
contextParams.put("HTTPS_EP", httpsServerEP);
|
||||
contextParams.put("HTTP_EP", httpServerEP);
|
||||
contextParams.put("APIM_EP", apimEndpoint);
|
||||
contextParams.put("MQTT_EP", mqttEndpoint);
|
||||
contextParams.put("XMPP_EP", xmppEndpoint);
|
||||
contextParams.put("DEVICE_TOKEN", token);
|
||||
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
|
||||
|
||||
ZipArchive zipFile;
|
||||
try {
|
||||
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath,
|
||||
contextParams);
|
||||
} catch (IOException e) {
|
||||
throw new DeviceManagementException("Zip File Creation Failed", e);
|
||||
}
|
||||
|
||||
return zipFile;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user