revert-70aa11f8
hasuniea 9 years ago
commit 59f1d04c44

@ -33,65 +33,67 @@ public interface GadgetDataServiceDAO {
*/ */
int getTotalDeviceCount() throws GadgetDataServiceDAOException; int getTotalDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get active device count from a particular tenant.
*
* @return active device count.
*/
int getActiveDeviceCount() throws GadgetDataServiceDAOException; int getActiveDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get inactive device count from a particular tenant.
*
* @return inactive device count.
*/
int getInactiveDeviceCount() throws GadgetDataServiceDAOException; int getInactiveDeviceCount() throws GadgetDataServiceDAOException;
/**
* Method to get removed device count from a particular tenant.
*
* @return removed device count.
*/
int getRemovedDeviceCount() throws GadgetDataServiceDAOException; int getRemovedDeviceCount() throws GadgetDataServiceDAOException;
/** /**
* Method to get non-compliant device count. * Method to get non-compliant device count from a particular tenant.
* *
* @return Non-compliant device count. * @return Non-compliant device count.
*/ */
@SuppressWarnings("unused")
int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException; int getNonCompliantDeviceCount() throws GadgetDataServiceDAOException;
/** /**
* Method to get unmonitored device count. * Method to get unmonitored device count from a particular tenant.
* *
* @return Unmonitored device count. * @return Unmonitored device count.
*/ */
@SuppressWarnings("unused")
int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException; int getUnmonitoredDeviceCount() throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; PaginationResult getNonCompliantDeviceCountsByFeatures(PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException; int getDeviceCount(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode, int getFeatureNonCompliantDeviceCount(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Integer> getDeviceCountsByPlatforms(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode, Map<String, Integer> getFeatureNonCompliantDeviceCountsByPlatforms(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters) Map<String, Integer> getDeviceCountsByOwnershipTypes(Map<String, Object> filters)
throws GadgetDataServiceDAOException; throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode, Map<String, Integer> getFeatureNonCompliantDeviceCountsByOwnershipTypes(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
PaginationResult getDevicesWithDetails(Map<String, Object> filters, PaginationResult getDevicesWithDetails(Map<String, Object> filters,
PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, PaginationResult getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException; Map<String, Object> filters, PaginationRequest paginationRequest) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException; List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) throws GadgetDataServiceDAOException;
@SuppressWarnings("unused")
List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
Map<String, Object> filters) throws GadgetDataServiceDAOException; Map<String, Object> filters) throws GadgetDataServiceDAOException;

@ -411,7 +411,6 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Object> filteredDeviceWithDetails = new HashMap<>();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>(); List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
int totalRecordsCount = 0; int totalRecordsCount = 0;
try { try {
@ -448,7 +447,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
// executing query // executing query
rs = stmt.executeQuery(); rs = stmt.executeQuery();
// fetching query results // fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) { while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM")); filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP")); filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));
@ -559,7 +560,6 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
PreparedStatement stmt = null; PreparedStatement stmt = null;
ResultSet rs = null; ResultSet rs = null;
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
Map<String, Object> filteredDeviceWithDetails = new HashMap<>();
List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>(); List<Map<String, Object>> filteredDevicesWithDetails = new ArrayList<>();
try { try {
con = this.getConnection(); con = this.getConnection();
@ -589,7 +589,9 @@ class GadgetDataServiceDAOImpl implements GadgetDataServiceDAO {
// executing query // executing query
rs = stmt.executeQuery(); rs = stmt.executeQuery();
// fetching query results // fetching query results
Map<String, Object> filteredDeviceWithDetails;
while (rs.next()) { while (rs.next()) {
filteredDeviceWithDetails = new HashMap<>();
filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.put("device-id", rs.getInt("DEVICE_ID"));
filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM")); filteredDeviceWithDetails.put("platform", rs.getString("PLATFORM"));
filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP")); filteredDeviceWithDetails.put("ownership", rs.getString("OWNERSHIP"));

@ -270,12 +270,32 @@ class GadgetDataServiceImpl implements GadgetDataService {
@Override @Override
public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) { public List<Map<String, Object>> getDevicesWithDetails(Map<String, Object> filters) {
return null; List<Map<String, Object>> devicesWithDetails = null;
try {
GadgetDataServiceDAOFactory.openConnection();
devicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().getDevicesWithDetails(filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return devicesWithDetails;
} }
@Override @Override
public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode, Map<String, Object> filters) { public List<Map<String, Object>> getFeatureNonCompliantDevicesWithDetails(String nonCompliantFeatureCode,
return null; Map<String, Object> filters) {
List<Map<String, Object>> featureNonCompliantDevicesWithDetails = null;
try {
GadgetDataServiceDAOFactory.openConnection();
featureNonCompliantDevicesWithDetails = GadgetDataServiceDAOFactory.getGadgetDataServiceDAO().
getFeatureNonCompliantDevicesWithDetails(nonCompliantFeatureCode, filters);
} catch (GadgetDataServiceDAOException | SQLException e) {
return null;
} finally {
GadgetDataServiceDAOFactory.closeConnection();
}
return featureNonCompliantDevicesWithDetails;
} }
} }

@ -21,15 +21,15 @@ package org.wso2.carbon.device.mgt.jaxrs.api;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; 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.PaginationResult;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupAlreadyEixistException; 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.GroupManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.GroupUser; 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.core.service.GroupManagementProviderService;
import org.wso2.carbon.device.mgt.jaxrs.api.util.DeviceMgtAPIUtils;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -141,6 +141,26 @@ public class Group {
} }
} }
@Path("/all")
@GET
@Produces("application/json")
public Response getAllGroups() {
try {
GroupManagementProviderService groupManagementProviderService = DeviceMgtAPIUtils
.getGroupManagementProviderService();
PaginationResult paginationResult = groupManagementProviderService
.getGroups(0, groupManagementProviderService.getGroupCount());
if (paginationResult.getRecordsTotal() > 0) {
return Response.status(Response.Status.OK).entity(paginationResult.getData()).build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
@Path("/user/{user}") @Path("/user/{user}")
@GET @GET
@Produces("application/json") @Produces("application/json")
@ -364,16 +384,18 @@ public class Group {
} }
@GET @GET
@Path("/owner/{owner}/name/{groupName}/devices/all") @Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json") @Produces("application/json")
public Response getDevices(@PathParam("groupName") String groupName, public Response getDevices(@PathParam("groupName") String groupName, @PathParam("owner") String owner,
@PathParam("owner") String owner) { @QueryParam("start") int startIdx, @QueryParam("length") int length) {
try { try {
List<Device> devices = DeviceMgtAPIUtils.getGroupManagementProviderService().getDevices( PaginationResult paginationResult = DeviceMgtAPIUtils
groupName, owner); .getGroupManagementProviderService().getDevices(groupName, owner, startIdx, length);
Device[] deviceArray = new Device[devices.size()]; if (paginationResult.getRecordsTotal() > 0) {
devices.toArray(deviceArray); return Response.status(Response.Status.OK).entity(paginationResult).build();
return Response.status(Response.Status.OK).entity(deviceArray).build(); } else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} catch (GroupManagementException e) { } catch (GroupManagementException e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
@ -394,15 +416,12 @@ public class Group {
} }
} }
@PUT @POST
@Path("/owner/{owner}/name/{groupName}/devices/{deviceType}/{deviceId}") @Path("/owner/{owner}/name/{groupName}/devices")
@Produces("application/json") @Produces("application/json")
public Response addDevice(@PathParam("groupName") String groupName, public Response addDevice(@PathParam("groupName") String groupName,
@PathParam("owner") String owner, @PathParam("deviceId") String deviceId, @PathParam("owner") String owner, DeviceIdentifier deviceIdentifier) {
@PathParam("deviceType") String deviceType,
@FormParam("userName") String userName) {
try { try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(deviceId, deviceType);
boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice( boolean isAdded = DeviceMgtAPIUtils.getGroupManagementProviderService().addDevice(
deviceIdentifier, groupName, owner); deviceIdentifier, groupName, owner);
if (isAdded) { if (isAdded) {

@ -959,12 +959,19 @@
</Permission> </Permission>
<Permission> <Permission>
<name>List All Groups</name> <name>List All Groups with Pagination</name>
<path>/device-mgt/admin/groups/list</path> <path>/device-mgt/admin/groups/list</path>
<url>/groups</url> <url>/groups</url>
<method>GET</method> <method>GET</method>
</Permission> </Permission>
<Permission>
<name>List All Groups</name>
<path>/device-mgt/admin/groups/list</path>
<url>/groups/all</url>
<method>GET</method>
</Permission>
<Permission> <Permission>
<name>List Groups</name> <name>List Groups</name>
<path>/device-mgt/user/groups/list</path> <path>/device-mgt/user/groups/list</path>
@ -1080,7 +1087,7 @@
<Permission> <Permission>
<name>List Group Devices</name> <name>List Group Devices</name>
<path>/device-mgt/user/groups/devices/list</path> <path>/device-mgt/user/groups/devices/list</path>
<url>/groups/owner/*/name/*/devices/all</url> <url>/groups/owner/*/name/*/devices</url>
<method>GET</method> <method>GET</method>
</Permission> </Permission>
@ -1094,8 +1101,8 @@
<Permission> <Permission>
<name>Add Device to Group</name> <name>Add Device to Group</name>
<path>/device-mgt/user/groups/devices/add</path> <path>/device-mgt/user/groups/devices/add</path>
<url>/groups/owner/*/name/*/devices/*/*</url> <url>/groups/owner/*/name/*/devices</url>
<method>PUT</method> <method>POST</method>
</Permission> </Permission>
<Permission> <Permission>

@ -382,9 +382,9 @@ public class GroupDAOImpl implements GroupDAO {
ResultSet resultSet = null; ResultSet resultSet = null;
try { try {
Connection conn = GroupManagementDAOFactory.getConnection(); Connection conn = GroupManagementDAOFactory.getConnection();
String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID as GROUP_ID " + String sql = "SELECT COUNT(gm.ID) AS DEVICE_COUNT FROM DM_DEVICE_GROUP_MAP gm, (SELECT ID " +
"FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " + "FROM DM_GROUP WHERE GROUP_NAME = ? AND OWNER = ? AND TENANT_ID = ?) dg " +
"WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?"; "WHERE gm.GROUP_ID = dg.ID AND gm.TENANT_ID = ?";
stmt = conn.prepareStatement(sql); stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName); stmt.setString(1, groupName);
stmt.setString(2, owner); stmt.setString(2, owner);

@ -0,0 +1,83 @@
<%
/*
* 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.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/device-api.jag");
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var serviceInvokers = require("/app/modules/backend-service-invoker.js").backendServiceInvoker;
var user = session.get(constants.USER_SESSION_KEY);
var result;
response.contentType = 'application/json';
if (!user) {
response.sendRedirect("/devicemgt/login?#login-required");
exit();
} else {
if (uriMatcher.match("/{context}/api/groups")) {
var url = request.getParameter("url");
var draw = request.getParameter("draw");
var length = request.getParameter("length");
var start = request.getParameter("start");
var search = request.getParameter("search[value]");
var groupName = request.getParameter("columns[1][search][value]");
var owner = request.getParameter("columns[2][search][value]");
var targetURL;
function appendQueryParam(url, queryParam, value) {
if (url.indexOf("?") > 0) {
return url + "&" + queryParam + "=" + value;
}
return url + "?" + queryParam + "=" + value;
}
targetURL = devicemgtProps.httpsURL + request.getParameter("url");
targetURL = appendQueryParam(targetURL, "start", start);
targetURL = appendQueryParam(targetURL, "length", length);
if (search && search !== "") {
targetURL = appendQueryParam(targetURL, "search", search);
}
if (groupName && groupName !== "") {
targetURL = appendQueryParam(targetURL, "group-name", groupName);
}
if (owner && owner !== "") {
targetURL = appendQueryParam(targetURL, "user", owner);
}
serviceInvokers.XMLHttp.get(
targetURL, function (responsePayload) {
response.status = 200;
result = responsePayload;
},
function (responsePayload) {
response.status = responsePayload.status;
result = responsePayload.responseText;
});
}
}
%>

@ -1,124 +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.
*/
var uri = request.getRequestURI();
var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/stats-api.jag");
var from = request.getParameter("from");
var to = request.getParameter("to");
var constants = require("/app/modules/constants.js");
var utility = require("/app/modules/utility.js").utility;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var deviceCloudGroupService = devicemgtProps["httpsURL"] + "/common/group_manager";
var deviceCloudDeviceService = devicemgtProps["httpsURL"] + "/common/device_manager";
var deviceCloudStatsService = devicemgtProps["httpsURL"] + "/common/stats_manager";
var stats = {};
var deviceId;
var deviceType;
var responseProcessor = require('utils').response;
response.contentType = 'application/json';
var user = session.get(constants.USER_SESSION_KEY);
if (!user) {
response = responseProcessor.buildErrorResponse(response, 401, "Unauthorized");
} else {
if (uriMatcher.match("/{context}/api/stats")) {
deviceId = request.getParameter("deviceId");
deviceType = request.getParameter("deviceType");
getDeviceData(deviceType, deviceId);
} else if (uriMatcher.match("/{context}/api/stats/group")) {
var groupId = request.getParameter("groupId");
//URL: GET https://localhost:9443/devicecloud/group_manager/group/id/{groupId}/device/all
var endPoint = deviceCloudGroupService + "/group/id/" + groupId + "/device/all";
var data = {"username": user};
var devices = get(endPoint, data, "json").data;
for (var device in devices) {
deviceId = devices[device].deviceIdentifier;
deviceType = devices[device].type;
getDeviceData(deviceType, deviceId);
}
}
log.info(stats);
// returning the result.
if (stats) {
print(stats);
}
}
function getDeviceData(deviceType, deviceId) {
//URL: GET https://localhost:9443/devicecloud/device_manager/device/type/{type}/identifier/{identifier}
var endPoint = deviceCloudDeviceService + "/device/type/" + deviceType + "/identifier/" + deviceId;
var data = {"username": user};
var device = get(endPoint, data, "json").data;
log.info(device);
if (!device) {
return;
}
var uname = device.enrolmentInfo.owner;
var analyticStreams = utility.getDeviceTypeConfig(deviceType)["analyticStreams"];
if (analyticStreams) {
var streamTableName;
for (var stream in analyticStreams) {
streamTableName = analyticStreams[stream]["table"];
if (stats[streamTableName] == null) {
stats[streamTableName] = [];
}
stats[streamTableName].push({
"device": device.name,
"stats": getSensorData(streamTableName, analyticStreams[stream]["ui_unit"]["data"][1]["column"]["name"], uname, device.type, device.deviceIdentifier, from, to),
"stream": analyticStreams[stream]
});
}
}
}
function getSensorData(table, column, user, type, deviceIdentifier, from, to) {
var fetchedData = [];
try {
///stats/device/type/{type}/identifier/{identifier}
var endPoint = deviceCloudStatsService + "/stats/device/type/" + type + "/identifier/" + deviceIdentifier;
var query = "?table=" + encodeURIComponent(table)
+ "&column=" + encodeURIComponent(column)
+ "&username=" + encodeURIComponent(user)
+ "&from=" + from
+ "&to=" + to;
endPoint = endPoint + query;
fetchedData = get(endPoint, {}, "json").data;
return fetchedData;
} catch (error) {
log.error(error);
}
}
%>

@ -54,7 +54,7 @@ var groupModule = {};
}; };
groupModule.getGroupDeviceCount = function (groupName, owner) { groupModule.getGroupDeviceCount = function (groupName, owner) {
endPoint = groupServiceEndpoint + "/" + owner + "/" + groupName + "/devices/count"; endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count";
return serviceInvokers.XMLHttp.get( return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) { endPoint, function (responsePayload) {
return responsePayload; return responsePayload;

@ -55,6 +55,11 @@
{{/zone}} {{/zone}}
{{#zone "content"}} {{#zone "content"}}
<div class="row wr-device-board" style="margin-top: -10px;">
<div class="col-lg-12 wr-secondary-bar">
<span class="page-sub-title">{{title}}</span>
</div>
</div>
<div class="wr-device-list row"> <div class="wr-device-list row">
<div class="wr-hidden-operations wr-advance-operations"></div> <div class="wr-hidden-operations wr-advance-operations"></div>
<div class="col-md-12 wr-page-content"> <div class="col-md-12 wr-page-content">
@ -275,7 +280,7 @@
<div id="device-400-content" class="hide"> <div id="device-400-content" class="hide">
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
<div class="col-md-7 col-centered center-container"> <div class="col-lg-5 col-md-6 col-centered">
<h3>Exception at backend. Try Later.</h3> <h3>Exception at backend. Try Later.</h3>
<br/> <br/>
<div class="buttons"> <div class="buttons">
@ -291,7 +296,7 @@
<div id="device-403-content" class="hide"> <div id="device-403-content" class="hide">
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
<div class="col-md-7 col-centered center-container"> <div class="col-lg-5 col-md-6 col-centered">
<h3>Operation not permitted.</h3> <h3>Operation not permitted.</h3>
<br/> <br/>
<div class="buttons"> <div class="buttons">
@ -304,10 +309,30 @@
</div> </div>
</div> </div>
<div id="group-404-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>You don't have any groups to add this device. Please add group first.</h3>
<br/>
<div class="buttons">
<a href="{{@app.context}}/group/add" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Add New Group&nbsp;&nbsp;&nbsp;&nbsp;
</a>
&nbsp;&nbsp;
<a href="#" id="cancel-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Cancel&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide"> <div id="device-409-content" class="hide">
<div class="modal-content"> <div class="modal-content">
<div class="row"> <div class="row">
<div class="col-md-7 col-centered center-container"> <div class="col-lg-5 col-md-6 col-centered">
<h3>Device does not exist.</h3> <h3>Device does not exist.</h3>
<br/> <br/>
<div class="buttons"> <div class="buttons">

@ -44,7 +44,6 @@ function onRequest(context) {
if (groupName && groupOwner) { if (groupName && groupOwner) {
var groupModule = require("/app/modules/group.js").groupModule; var groupModule = require("/app/modules/group.js").groupModule;
deviceCount = groupModule.getGroupDeviceCount(groupName, groupOwner); deviceCount = groupModule.getGroupDeviceCount(groupName, groupOwner);
page.groupOwner = groupOwner;
} else { } else {
deviceCount = deviceModule.getDevicesCount(); deviceCount = deviceModule.getDevicesCount();
} }

@ -61,10 +61,18 @@ function InitiateViewOption(url) {
var deviceCheckbox = "#ast-container .ctrl-wr-asset .itm-select input[type='checkbox']"; var deviceCheckbox = "#ast-container .ctrl-wr-asset .itm-select input[type='checkbox']";
var assetContainer = "#ast-container"; var assetContainer = "#ast-container";
var deviceListing, currentUser, groupName, groupOwner;
/* /*
* DOM ready functions. * DOM ready functions.
*/ */
$(document).ready(function () { $(document).ready(function () {
deviceListing = $("#device-listing");
deviceListing.data("current-user");
groupName = getParameterByName("groupName");
groupOwner = getParameterByName("groupOwner");
/* Adding selected class for selected devices */ /* Adding selected class for selected devices */
$(deviceCheckbox).each(function () { $(deviceCheckbox).each(function () {
addDeviceSelectedClass(this); addDeviceSelectedClass(this);
@ -88,8 +96,6 @@ $(document).ready(function () {
$(".ast-container").on("click", ".claim-btn", function(e){ $(".ast-container").on("click", ".claim-btn", function(e){
e.stopPropagation(); e.stopPropagation();
var deviceId = $(this).data("deviceid"); var deviceId = $(this).data("deviceid");
var deviceListing = $("#device-listing");
var currentUser = deviceListing.data("current-user");
var serviceURL = "/temp-controller-agent/enrollment/claim?username=" + currentUser; var serviceURL = "/temp-controller-agent/enrollment/claim?username=" + currentUser;
var deviceIdentifier = {id: deviceId, type: "TemperatureController"}; var deviceIdentifier = {id: deviceId, type: "TemperatureController"};
invokerUtil.put(serviceURL, deviceIdentifier, function(message){ invokerUtil.put(serviceURL, deviceIdentifier, function(message){
@ -161,10 +167,6 @@ function toTitleCase(str) {
} }
function loadDevices(searchType, searchParam){ function loadDevices(searchType, searchParam){
var deviceListing = $("#device-listing");
var imageResource = deviceListing.data("image-resource");
var currentUser = deviceListing.data("currentUser");
var serviceURL; var serviceURL;
if ($.hasPermission("LIST_DEVICES")) { if ($.hasPermission("LIST_DEVICES")) {
serviceURL = "/devicemgt_admin/devices"; serviceURL = "/devicemgt_admin/devices";
@ -304,6 +306,15 @@ function loadDevices(searchType, searchParam){
'data-click-event="remove-form" class="btn padding-reduce-on-grid-view"><span class="fw-stack">' + 'data-click-event="remove-form" class="btn padding-reduce-on-grid-view"><span class="fw-stack">' +
'<i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-statistics fw-stack-1x"></i></span>' + '<i class="fw fw-ring fw-stack-2x"></i><i class="fw fw-statistics fw-stack-1x"></i></span>' +
'<span class="hidden-xs hidden-on-grid-view">Analytics</span>'; '<span class="hidden-xs hidden-on-grid-view">Analytics</span>';
if (!groupName || !groupOwner) {
html += '<a href="#" data-click-event="remove-form" class="btn padding-reduce-on-grid-view group-device-link" ' +
'data-deviceid="' + deviceIdentifier + '" data-devicetype="' + deviceType + '" data-devicename="' +
row.name + '"><span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
'<i class="fw fw-grouping fw-stack-1x"></i></span>' +
'<span class="hidden-xs hidden-on-grid-view">Group</span></a>';
}
html += '<a href="#" data-click-event="remove-form" class="btn padding-reduce-on-grid-view edit-device-link" ' + html += '<a href="#" data-click-event="remove-form" class="btn padding-reduce-on-grid-view edit-device-link" ' +
'data-deviceid="' + deviceIdentifier + '" data-devicetype="' + deviceType + '" data-devicename="' + row.name + '">' + 'data-deviceid="' + deviceIdentifier + '" data-devicetype="' + deviceType + '" data-devicename="' + row.name + '">' +
'<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' + '<span class="fw-stack"><i class="fw fw-ring fw-stack-2x"></i>' +
@ -370,12 +381,6 @@ function loadDevices(searchType, searchParam){
}); });
} }
/*
* Setting-up global variables.
*/
var deviceCheckbox = "#ast-container .ctrl-wr-asset .itm-select input[type='checkbox']";
var assetContainer = "#ast-container";
function openCollapsedNav() { function openCollapsedNav() {
$('.wr-hidden-nav-toggle-btn').addClass('active'); $('.wr-hidden-nav-toggle-btn').addClass('active');
$('#hiddenNav').slideToggle('slideDown', function () { $('#hiddenNav').slideToggle('slideDown', function () {
@ -386,14 +391,12 @@ function openCollapsedNav() {
} }
function initPage() { function initPage() {
var deviceListing = $("#device-listing");
var currentUser = deviceListing.data("currentUser");
var serviceURL; var serviceURL;
if ($.hasPermission("LIST_DEVICES")) { if ($.hasPermission("LIST_DEVICES")) {
serviceURL = "/devicemgt_admin/devices/count"; serviceURL = "/devicemgt_admin/devices/count";
} else if ($.hasPermission("LIST_OWN_DEVICES")) { } else if ($.hasPermission("LIST_OWN_DEVICES")) {
//Get authenticated users devices //Get authenticated users devices
serviceURL = "/devicemgt_admin/devices/user/"+currentUser+"/count"; serviceURL = "/devicemgt_admin/devices/user/" + currentUser + "/count";
} }
invokerUtil.get(serviceURL, invokerUtil.get(serviceURL,
function (data) { function (data) {
@ -439,20 +442,6 @@ $(document).ready(function () {
} }
}); });
$(".ast-container").on("click", ".claim-btn", function(e) {
e.stopPropagation();
var deviceId = $(this).data("deviceid");
var deviceListing = $("#device-listing");
var currentUser = deviceListing.data("current-user");
var serviceURL = "/temp-controller-agent/enrollment/claim?username=" + currentUser;
var deviceIdentifier = {id: deviceId, type: "TemperatureController"};
invokerUtil.put(serviceURL, deviceIdentifier, function(message) {
console.log(message);
}, function(message){
console.log(message.content);
});
});
/* for data tables*/ /* for data tables*/
$('[data-toggle="tooltip"]').tooltip(); $('[data-toggle="tooltip"]').tooltip();
@ -516,72 +505,54 @@ function attachDeviceEvents() {
$("a.group-device-link").click(function () { $("a.group-device-link").click(function () {
var deviceId = $(this).data("deviceid"); var deviceId = $(this).data("deviceid");
var deviceType = $(this).data("devicetype"); var deviceType = $(this).data("devicetype");
var endPoint = "api/group/all";
$(modalPopupContent).html($('#group-device-modal-content').html()); $(modalPopupContent).html($('#group-device-modal-content').html());
$('#user-groups').html('<div style="height:100px" data-state="loading" data-loading-text="Loading..." data-loading-style="icon-only" data-loading-inverse="true"></div>'); $('#user-groups').html('<div style="height:100px" data-state="loading" data-loading-text="Loading..." data-loading-style="icon-only" data-loading-inverse="true"></div>');
$("a#group-device-yes-link").hide(); $("a#group-device-yes-link").hide();
showPopup(); showPopup();
var getGroupsRequest = $.ajax({ var serviceURL;
url: endPoint, if ($.hasPermission("LIST_ALL_GROUPS")) {
method: "GET", serviceURL = "/devicemgt_admin/groups/all";
contentType: "application/json", } else if ($.hasPermission("LIST_GROUPS")) {
accept: "application/json" //Get authenticated users groups
}); serviceURL = "/devicemgt_admin/groups/user/" + currentUser;
}
getGroupsRequest.done(function (data, txtStatus, jqxhr) {
var groups = JSON.parse(data); invokerUtil.get(serviceURL, function (data) {
var status = jqxhr.status; var groups = JSON.parse(data);
if (status == 200) { var str = '<br /><select id="assign-group-selector" style="color:#3f3f3f;padding:5px;width:250px;">';
groups = groups.data; for (var i = 0; i < groups.length; i++) {
if (groups.length <= 0) { str += '<option value="' + groups[i].owner + "/name/" + groups[i].name + '">' +
$('#user-groups').html("There is no any groups available"); groups[i].name + '</option>';
return; }
} str += '</select>';
var str = '<br /><select id="assign-group-selector" style="color:#3f3f3f;padding:5px;width:250px;">'; $('#user-groups').html(str);
for (var group in groups) { $("a#group-device-yes-link").show();
str += '<option value="' + groups[group].id + '">' + groups[group].name + '</option>'; $("a#group-device-yes-link").click(function () {
} var selectedGroup = $('#assign-group-selector').val();
str += '</select>'; serviceURL = "/devicemgt_admin/groups/owner/" + selectedGroup + "/devices";
$('#user-groups').html(str); var device = {"id": deviceId, "type": deviceType};
$("a#group-device-yes-link").show(); invokerUtil.post(serviceURL, device, function (data) {
$("a#group-device-yes-link").click(function () { $(modalPopupContent).html($('#group-associate-device-200-content').html());
var selectedGroupId = $('#assign-group-selector').val(); setTimeout(function () {
endPoint = "api/group/id/" + selectedGroupId + "/assign"; hidePopup();
var device = {"deviceId": deviceId, "deviceType": deviceType}; location.reload(false);
}, 2000);
var assignRequest = $.ajax({ }, function (jqXHR) {
url: endPoint, displayDeviceErrors(jqXHR);
method: "POST", });
contentType: "application/json", });
accept: "application/json", }, function (jqXHR) {
data: JSON.stringify(device) if (jqXHR.status == 404) {
}); $(modalPopupContent).html($('#group-404-content').html());
$("a#cancel-link").click(function () {
assignRequest.done(function (data, txtStatus, jqxhr) { hidePopup();
var status = jqxhr.status; });
if (status == 200) { } else {
$(modalPopupContent).html($('#group-associate-device-200-content').html()); displayDeviceErrors(jqXHR);
setTimeout(function () { }
hidePopup();
location.reload(false);
}, 2000);
} else {
displayDeviceErrors(jqXHR);
}
}
);
assignRequest.fail(function (jqXHR) {
displayDeviceErrors(jqXHR);
});
});
}
}
);
getGroupsRequest.fail(function (jqXHR) {
displayDeviceErrors(jqXHR);
}); });
$("a#group-device-cancel-link").click(function () { $("a#group-device-cancel-link").click(function () {
hidePopup(); hidePopup();
}); });
@ -656,23 +627,23 @@ function attachDeviceEvents() {
function displayDeviceErrors(jqXHR) { function displayDeviceErrors(jqXHR) {
showPopup(); showPopup();
if (jqXHR.status == 400) { if (jqXHR.status == 400) {
$(modalPopupContent).html($('#group-400-content').html()); $(modalPopupContent).html($('#device-400-content').html());
$("a#group-400-link").click(function () { $("a#device-400-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (jqXHR.status == 403) { } else if (jqXHR.status == 403) {
$(modalPopupContent).html($('#group-403-content').html()); $(modalPopupContent).html($('#device-403-content').html());
$("a#group-403-link").click(function () { $("a#device-403-link").click(function () {
hidePopup(); hidePopup();
}); });
} else if (jqXHR.status == 409) { } else if (jqXHR.status == 409) {
$(modalPopupContent).html($('#group-409-content').html()); $(modalPopupContent).html($('#device-409-content').html());
$("a#group-409-link").click(function () { $("a#device-409-link").click(function () {
hidePopup(); hidePopup();
}); });
} else { } else {
$(modalPopupContent).html($('#group-unexpected-error-content').html()); $(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#group-unexpected-error-link").click(function () { $("a#device-unexpected-error-link").click(function () {
hidePopup(); hidePopup();
}); });
console.log("Error code: " + jqXHR.status); console.log("Error code: " + jqXHR.status);

@ -11,10 +11,6 @@
"url": "/api/group/*", "url": "/api/group/*",
"path": "/api/group-api.jag" "path": "/api/group-api.jag"
}, },
{
"url": "/api/stats/*",
"path": "/api/stats-api.jag"
},
{ {
"url": "/api/operations/*", "url": "/api/operations/*",
"path": "/api/operation-api.jag" "path": "/api/operation-api.jag"

Loading…
Cancel
Save