Add capability to assign device in to a group and bug fixes

4.x.x
charithag 9 years ago
parent 6e84f0a5a3
commit b1683c1ccb

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

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

@ -356,9 +356,9 @@ public class GroupDAOImpl implements GroupDAO {
ResultSet resultSet = null;
try {
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 " +
"WHERE dm.GROUP_ID = dg.GROUP_ID AND dm.TENANT_ID = ?";
"WHERE gm.GROUP_ID = dg.ID AND dm.TENANT_ID = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, groupName);
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) {
endPoint = groupServiceEndpoint + "/" + owner + "/" + groupName + "/devices/count";
endPoint = groupServiceEndpoint + "/owner/" + owner + "/name/" + groupName + "/devices/count";
return serviceInvokers.XMLHttp.get(
endPoint, function (responsePayload) {
return responsePayload;

@ -1,4 +1,4 @@
{{unit "cdmf.unit.ui.title" pageTitle="Device Management"}}
{{unit "cdmf.unit.ui.title" pageTitle=title}}
{{unit "cdmf.unit.data-tables-extended"}}

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

@ -61,10 +61,18 @@ function InitiateViewOption(url) {
var deviceCheckbox = "#ast-container .ctrl-wr-asset .itm-select input[type='checkbox']";
var assetContainer = "#ast-container";
var deviceListing, currentUser, groupName, groupOwner;
/*
* DOM ready functions.
*/
$(document).ready(function () {
deviceListing = $("#device-listing");
deviceListing.data("current-user");
groupName = getParameterByName("groupName");
groupOwner = getParameterByName("groupOwner");
/* Adding selected class for selected devices */
$(deviceCheckbox).each(function () {
addDeviceSelectedClass(this);
@ -88,8 +96,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){
@ -161,10 +167,6 @@ function toTitleCase(str) {
}
function loadDevices(searchType, searchParam){
var deviceListing = $("#device-listing");
var imageResource = deviceListing.data("image-resource");
var currentUser = deviceListing.data("currentUser");
var serviceURL;
if ($.hasPermission("LIST_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">' +
'<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>';
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" ' +
'data-deviceid="' + deviceIdentifier + '" data-devicetype="' + deviceType + '" data-devicename="' + row.name + '">' +
'<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() {
$('.wr-hidden-nav-toggle-btn').addClass('active');
$('#hiddenNav').slideToggle('slideDown', function () {
@ -386,8 +391,6 @@ function openCollapsedNav() {
}
function initPage() {
var deviceListing = $("#device-listing");
var currentUser = deviceListing.data("currentUser");
var serviceURL;
if ($.hasPermission("LIST_DEVICES")) {
serviceURL = "/devicemgt_admin/devices/count";
@ -442,8 +445,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) {
@ -516,72 +517,51 @@ function attachDeviceEvents() {
$("a.group-device-link").click(function () {
var deviceId = $(this).data("deviceid");
var deviceType = $(this).data("devicetype");
var endPoint = "api/group/all";
$(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>');
$("a#group-device-yes-link").hide();
showPopup();
var getGroupsRequest = $.ajax({
url: endPoint,
method: "GET",
contentType: "application/json",
accept: "application/json"
});
var serviceURL;
if ($.hasPermission("LIST_ALL_GROUPS")) {
serviceURL = "/devicemgt_admin/groups/all";
} else if ($.hasPermission("LIST_GROUPS")) {
//Get authenticated users groups
serviceURL = "/devicemgt_admin/groups/user/" + currentUser;
}
getGroupsRequest.done(function (data, txtStatus, jqxhr) {
invokerUtil.get(serviceURL, function (data) {
var groups = JSON.parse(data);
var status = jqxhr.status;
if (status == 200) {
groups = groups.data;
if (groups.length <= 0) {
$('#user-groups').html("There is no any groups available");
return;
}
var str = '<br /><select id="assign-group-selector" style="color:#3f3f3f;padding:5px;width:250px;">';
for (var group in groups) {
str += '<option value="' + groups[group].id + '">' + groups[group].name + '</option>';
for (var i = 0; i < groups.length; i++) {
str += '<option value="' + groups[i].owner + "/name/" + groups[i].name + '">' +
groups[i].name + '</option>';
}
str += '</select>';
$('#user-groups').html(str);
$("a#group-device-yes-link").show();
$("a#group-device-yes-link").click(function () {
var selectedGroupId = $('#assign-group-selector').val();
endPoint = "api/group/id/" + selectedGroupId + "/assign";
var device = {"deviceId": deviceId, "deviceType": deviceType};
var assignRequest = $.ajax({
url: endPoint,
method: "POST",
contentType: "application/json",
accept: "application/json",
data: JSON.stringify(device)
});
assignRequest.done(function (data, txtStatus, jqxhr) {
var status = jqxhr.status;
if (status == 200) {
var selectedGroup = $('#assign-group-selector').val();
serviceURL = "/devicemgt_admin/groups/owner/" + selectedGroup + "/devices";
var device = {"id": deviceId, "type": deviceType};
invokerUtil.post(serviceURL, device, function (data) {
$(modalPopupContent).html($('#group-associate-device-200-content').html());
setTimeout(function () {
hidePopup();
location.reload(false);
}, 2000);
} else {
displayDeviceErrors(jqXHR);
}
}
);
assignRequest.fail(function (jqXHR) {
}, function (message) {
displayDeviceErrors(jqXHR);
});
});
}
}
);
getGroupsRequest.fail(function (jqXHR) {
}, function (message) {
displayDeviceErrors(jqXHR);
});
$("a#group-device-cancel-link").click(function () {
hidePopup();
});

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

Loading…
Cancel
Save