From 3e2731a772ae6066a1ed91a8e5becc439381fc1b Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Fri, 23 Sep 2016 12:45:15 +0530 Subject: [PATCH 01/21] Fixing invoker service return nothing on httpClient requests. --- .../oauth/token-protected-service-invokers.js | 210 +++++++++--------- 1 file changed, 110 insertions(+), 100 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js index d4fdbc3e89..1600618775 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/oauth/token-protected-service-invokers.js @@ -72,7 +72,7 @@ var invokers = function () { var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.open(httpMethod, endpoint); - for(var i in headers){ + for (var i in headers) { xmlHttpRequest.setRequestHeader(headers[i].name, headers[i].value); } xmlHttpRequest.setRequestHeader(constants["CONTENT_TYPE_IDENTIFIER"], constants["APPLICATION_JSON"]); @@ -117,9 +117,10 @@ var invokers = function () { * @param endpoint Backend REST API url. * @param responseCallback a function to be called with response retrieved. */ - privateMethods["initiateXMLHTTPRequest"] = function (httpMethod, requestPayload, endpoint, responseCallback, headers) { - return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0, headers); - }; + privateMethods["initiateXMLHTTPRequest"] = + function (httpMethod, requestPayload, endpoint, responseCallback, headers) { + return privateMethods.execute(httpMethod, requestPayload, endpoint, responseCallback, 0, headers); + }; /** * This method invokes return initiateXMLHttpRequest for get calls. @@ -128,7 +129,8 @@ var invokers = function () { */ publicXMLHTTPInvokers["get"] = function (endpoint, responseCallback, headers) { var requestPayload = null; - return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback, headers); + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_GET"], requestPayload, endpoint, responseCallback, + headers); }; /** @@ -138,7 +140,8 @@ var invokers = function () { * @param responseCallback a function to be called with response retrieved. */ publicXMLHTTPInvokers["post"] = function (endpoint, requestPayload, responseCallback, headers) { - return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback, headers); + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_POST"], requestPayload, endpoint, responseCallback, + headers); }; /** @@ -148,7 +151,8 @@ var invokers = function () { * @param responseCallback a function to be called with response retrieved. */ publicXMLHTTPInvokers["put"] = function (endpoint, requestPayload, responseCallback, headers) { - return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback, headers); + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_PUT"], requestPayload, endpoint, responseCallback, + headers); }; /** @@ -158,7 +162,8 @@ var invokers = function () { */ publicXMLHTTPInvokers["delete"] = function (endpoint, responseCallback, headers) { var requestPayload = null; - return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, responseCallback, headers); + return privateMethods.initiateXMLHTTPRequest(constants["HTTP_DELETE"], requestPayload, endpoint, + responseCallback, headers); }; /** @@ -245,100 +250,105 @@ var invokers = function () { * @param errorCallback a function to be called if en error is reserved. * @param headers a list of name value pairs for additional http headers. */ - privateMethods["initiateHTTPClientRequest"] = function (method, url, successCallback, errorCallback, payload, headers) { - //noinspection JSUnresolvedVariable - var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; - var httpMethodObject; - switch (method) { - case constants["HTTP_GET"]: - //noinspection JSUnresolvedVariable - var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod; - httpMethodObject = new GetMethod(url); - break; - case constants["HTTP_POST"]: - //noinspection JSUnresolvedVariable - var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod; - httpMethodObject = new PostMethod(url); - break; - case constants["HTTP_PUT"]: - //noinspection JSUnresolvedVariable - var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod; - httpMethodObject = new PutMethod(url); - break; - case constants["HTTP_DELETE"]: - //noinspection JSUnresolvedVariable - var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod; - httpMethodObject = new DeleteMethod(url); - break; - default: - //noinspection JSUnresolvedFunction - throw new IllegalArgumentException("Invalid HTTP request method: " + method); - } - - //noinspection JSUnresolvedVariable - var Header = Packages.org.apache.commons.httpclient.Header; - for(var i in headers){ - var header = new Header(); - header.setName(headers[i].name); - header.setValue(headers[i].value); - httpMethodObject.addRequestHeader(header); - } - - var header = new Header(); - header.setName(constants["CONTENT_TYPE_IDENTIFIER"]); - header.setValue(constants["APPLICATION_JSON"]); - //noinspection JSUnresolvedFunction - httpMethodObject.addRequestHeader(header); - header = new Header(); - header.setName(constants["ACCEPT_IDENTIFIER"]); - header.setValue(constants["APPLICATION_JSON"]); - //noinspection JSUnresolvedFunction - httpMethodObject.addRequestHeader(header); + privateMethods["initiateHTTPClientRequest"] = + function (method, url, successCallback, errorCallback, payload, headers) { + //noinspection JSUnresolvedVariable + var HttpClient = Packages.org.apache.commons.httpclient.HttpClient; + var httpMethodObject; + switch (method) { + case constants["HTTP_GET"]: + //noinspection JSUnresolvedVariable + var GetMethod = Packages.org.apache.commons.httpclient.methods.GetMethod; + httpMethodObject = new GetMethod(url); + break; + case constants["HTTP_POST"]: + //noinspection JSUnresolvedVariable + var PostMethod = Packages.org.apache.commons.httpclient.methods.PostMethod; + httpMethodObject = new PostMethod(url); + break; + case constants["HTTP_PUT"]: + //noinspection JSUnresolvedVariable + var PutMethod = Packages.org.apache.commons.httpclient.methods.PutMethod; + httpMethodObject = new PutMethod(url); + break; + case constants["HTTP_DELETE"]: + //noinspection JSUnresolvedVariable + var DeleteMethod = Packages.org.apache.commons.httpclient.methods.DeleteMethod; + httpMethodObject = new DeleteMethod(url); + break; + default: + //noinspection JSUnresolvedFunction + throw new IllegalArgumentException("Invalid HTTP request method: " + method); + } - if (devicemgtProps["isOAuthEnabled"]) { - var accessToken = privateMethods.getAccessToken(); - if (accessToken) { - header = new Header(); - header.setName(constants["AUTHORIZATION_HEADER"]); - header.setValue(constants["BEARER_PREFIX"] + accessToken); - //noinspection JSUnresolvedFunction + //noinspection JSUnresolvedVariable + var Header = Packages.org.apache.commons.httpclient.Header; + for (var i in headers) { + var header = new Header(); + header.setName(headers[i].name); + header.setValue(headers[i].value); httpMethodObject.addRequestHeader(header); - } else { - response.sendRedirect(devicemgtProps["appContext"] + "login"); } - } - //noinspection JSUnresolvedFunction - if (payload != null) { - var StringRequestEntity = Packages.org.apache.commons.httpclient.methods.StringRequestEntity; - var stringRequestEntity = new StringRequestEntity(stringify(payload)); - //noinspection JSUnresolvedFunction - httpMethodObject.setRequestEntity(stringRequestEntity); - } - var client = new HttpClient(); - try { + + var header = new Header(); + header.setName(constants["CONTENT_TYPE_IDENTIFIER"]); + header.setValue(constants["APPLICATION_JSON"]); //noinspection JSUnresolvedFunction - client.executeMethod(httpMethodObject); + httpMethodObject.addRequestHeader(header); + header = new Header(); + header.setName(constants["ACCEPT_IDENTIFIER"]); + header.setValue(constants["APPLICATION_JSON"]); //noinspection JSUnresolvedFunction - var status = httpMethodObject.getStatusCode(); - if (status == 200) { - var responseContentDispositionHeader = httpMethodObject.getResponseHeader(constants["CONTENT_DISPOSITION_IDENTIFIER"]); - if (responseContentDispositionHeader) { - return successCallback(httpMethodObject.getResponseBodyAsStream(), httpMethodObject.getResponseHeaders()); + httpMethodObject.addRequestHeader(header); + + if (devicemgtProps["isOAuthEnabled"]) { + var accessToken = privateMethods.getAccessToken(); + if (accessToken) { + header = new Header(); + header.setName(constants["AUTHORIZATION_HEADER"]); + header.setValue(constants["BEARER_PREFIX"] + accessToken); + //noinspection JSUnresolvedFunction + httpMethodObject.addRequestHeader(header); } else { - return successCallback(httpMethodObject.getResponseBody()); + response.sendRedirect(devicemgtProps["appContext"] + "login"); } - } else { - return errorCallback(httpMethodObject.getResponseBody()); } - } catch (e) { - return errorCallback(response); - } finally { //noinspection JSUnresolvedFunction - if (method != constants["HTTP_GET"]) { - method.releaseConnection(); + if (payload != null) { + var StringRequestEntity = Packages.org.apache.commons.httpclient.methods.StringRequestEntity; + var stringRequestEntity = new StringRequestEntity(stringify(payload)); + //noinspection JSUnresolvedFunction + httpMethodObject.setRequestEntity(stringRequestEntity); } - } - }; + var client = new HttpClient(); + try { + //noinspection JSUnresolvedFunction + client.executeMethod(httpMethodObject); + //noinspection JSUnresolvedFunction + var status = httpMethodObject.getStatusCode(); + if (status == 200) { + var responseContentDispositionHeader = httpMethodObject.getResponseHeader( + constants["CONTENT_DISPOSITION_IDENTIFIER"]); + if (responseContentDispositionHeader) { + return successCallback(httpMethodObject.getResponseBodyAsStream(), + httpMethodObject.getResponseHeaders()); + } else { + return successCallback(httpMethodObject.getResponseBodyAsString(), + httpMethodObject.getResponseHeaders()); + } + } else { + return errorCallback(httpMethodObject.getResponseBodyAsString(), + httpMethodObject.getResponseHeaders()); + } + } catch (e) { + return errorCallback(response); + } finally { + //noinspection JSUnresolvedFunction + if (method != constants["HTTP_GET"]) { + method.releaseConnection(); + } + } + }; /** * This method invokes return initiateHTTPClientRequest for get calls. @@ -349,8 +359,8 @@ var invokers = function () { */ publicHTTPClientInvokers["get"] = function (url, successCallback, errorCallback, headers) { var requestPayload = null; - return privateMethods. - initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, requestPayload, headers); + return privateMethods.initiateHTTPClientRequest(constants["HTTP_GET"], url, successCallback, errorCallback, + requestPayload, headers); }; /** @@ -362,8 +372,8 @@ var invokers = function () { * @param headers a list of name value pairs for additional http headers. */ publicHTTPClientInvokers["post"] = function (url, payload, successCallback, errorCallback, headers) { - return privateMethods. - initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, payload, headers); + return privateMethods.initiateHTTPClientRequest(constants["HTTP_POST"], url, successCallback, errorCallback, + payload, headers); }; /** @@ -375,8 +385,8 @@ var invokers = function () { * @param headers a list of name value pairs for additional http headers. */ publicHTTPClientInvokers["put"] = function (url, payload, successCallback, errorCallback, headers) { - return privateMethods. - initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, payload, headers); + return privateMethods.initiateHTTPClientRequest(constants["HTTP_PUT"], url, successCallback, errorCallback, + payload, headers); }; /** @@ -388,8 +398,8 @@ var invokers = function () { */ publicHTTPClientInvokers["delete"] = function (url, successCallback, errorCallback, headers) { var requestPayload = null; - return privateMethods. - initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, requestPayload, headers); + return privateMethods.initiateHTTPClientRequest(constants["HTTP_DELETE"], url, successCallback, errorCallback, + requestPayload, headers); }; var publicMethods = {}; From ccf4b6492cb6d630090aa566058953216ccce7dc Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Fri, 23 Sep 2016 12:45:45 +0530 Subject: [PATCH 02/21] Fixing devices listing issue --- .../cdmf.page.devices/public/js/listing.js | 370 ++++++++++-------- 1 file changed, 217 insertions(+), 153 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js index 571d8085ad..820b183646 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/public/js/listing.js @@ -87,21 +87,21 @@ $(document).ready(function () { /* for device list sorting drop down */ $(".ctrl-filter-type-switcher").popover({ - html : true, - content : function () { - return $("#content-filter-types").html(); - } - }); + html: true, + content: function () { + return $("#content-filter-types").html(); + } + }); - $(".ast-container").on("click", ".claim-btn", function(e){ + $(".ast-container").on("click", ".claim-btn", function (e) { e.stopPropagation(); var deviceId = $(this).data("deviceid"); var serviceURL = "/temp-controller-agent/enrollment/claim?username=" + currentUser; var deviceIdentifier = {id: deviceId, type: "TemperatureController"}; - invokerUtil.put(serviceURL, deviceIdentifier, function(message){ + invokerUtil.put(serviceURL, deviceIdentifier, function (message) { console.log(message); - }, function(message){ - console.log(message.content); + }, function (message) { + console.log(message.content); }); }); }); @@ -166,15 +166,15 @@ function toTitleCase(str) { }); } -function loadDevices(searchType, searchParam){ +function loadDevices(searchType, searchParam) { var serviceURL; if (groupName && groupOwner && $.hasPermission("LIST_OWN_DEVICES")) { - serviceURL = "/devicemgt_admin/groups/owner/" + groupOwner + "/name/" + groupName + "/devices"; + serviceURL = "/api/device-mgt/v1.0/groups/owner/" + groupOwner + "/name/" + groupName + "/devices"; } else if ($.hasPermission("LIST_DEVICES")) { - serviceURL = "/devicemgt_admin/devices"; + serviceURL = "/api/device-mgt/v1.0/devices"; } else if ($.hasPermission("LIST_OWN_DEVICES")) { //Get authenticated users devices - serviceURL = "/devicemgt_admin/users/devices?username=" + currentUser; + serviceURL = "/api/device-mgt/v1.0/users/devices?username=" + currentUser; } else { $("#loading-content").remove(); $('#device-table').addClass('hidden'); @@ -197,10 +197,10 @@ function loadDevices(searchType, searchParam){ return {}; } - function getDeviceTypeLabel(type){ + function getDeviceTypeLabel(type) { var deviceTypes = deviceListing.data("deviceTypes"); - for (var i = 0; i < deviceTypes.length; i++){ - if (deviceTypes[i].type == type){ + for (var i = 0; i < deviceTypes.length; i++) { + if (deviceTypes[i].type == type) { return deviceTypes[i].label; } } @@ -227,29 +227,21 @@ function loadDevices(searchType, searchParam){ return type; } - $('#device-grid').datatables_extended ({ - serverSide: true, - processing: false, - searching: true, - ordering: false, - filter: false, - pageLength : 16, - ajax: { url : '/devicemgt/api/devices', data : {url : serviceURL}, - dataSrc: function ( json ) { - $('#device-grid').removeClass('hidden'); - $("#loading-content").remove(); - var $list = $("#device-table :input[type='search']"); - $list.each(function(){ - $(this).addClass("hidden"); - }); - return json.data; - } + var columns = [ + { + targets: 0, + data: 'name', + class: 'remove-padding icon-only content-fill', + render: function (data, type, row, meta) { + return '
'; + } }, - columnDefs: [ - { targets: 0, data: 'name', className: 'remove-padding icon-only content-fill' , render: function ( data, type, row, meta ) { - return '
'; - }}, - { targets: 1, data: 'name', className: 'fade-edge' , render: function ( name, type, row, meta ) { + { + targets: 1, + data: 'name', + class: 'fade-edge', + render: function (name, type, row, meta) { var model = getPropertyValue(row.properties, 'DEVICE_MODEL'); var vendor = getPropertyValue(row.properties, 'VENDOR'); var html = '

' + name + '

'; @@ -257,11 +249,17 @@ function loadDevices(searchType, searchParam){ html += '
(' + vendor + '-' + model + ')
'; } return html; - }}, - { targets: 2, data: 'enrolmentInfo.owner', className: 'fade-edge remove-padding-top'}, - { - targets: 3, data: 'enrolmentInfo.status', className: 'fade-edge remove-padding-top', - render: function ( status, type, row, meta ) { + } + }, + {targets: 2, + data: 'user', + class: 'fade-edge remove-padding-top', + }, + { + targets: 3, + data: 'status', + class: 'fade-edge remove-padding-top', + render: function (status, type, row, meta) { var html; switch (status) { case 'ACTIVE' : @@ -278,106 +276,171 @@ function loadDevices(searchType, searchParam){ break; } return html; - }}, - { - targets: 4, data: 'type', className: 'fade-edge remove-padding-top', - render: function ( status, type, row, meta ) { - return getDeviceTypeLabel(row.type); - } - }, - { - targets: 5, data: 'enrolmentInfo.ownership', className: 'fade-edge remove-padding-top', - render: function (status, type, row, meta) { - if (getDeviceTypeCategory(row.type) == 'mobile') { - return row.enrolmentInfo.ownership; - } else { - return null; - } + } + }, + { + targets: 4, + data: 'deviceType', + class: 'fade-edge remove-padding-top', + render: function (status, type, row, meta) { + return getDeviceTypeLabel(row.deviceType); + } + }, + { + targets: 5, + data: 'ownership', + class: 'fade-edge remove-padding-top', + render: function (status, type, row, meta) { + if (getDeviceTypeCategory(row.deviceType) == 'mobile') { + return row.enrolmentInfo.ownership; + } else { + return null; } - }, - { targets: 6, data: 'enrolmentInfo.status' , className: 'text-right content-fill text-left-on-grid-view no-wrap' , - render: function ( status, type, row, meta ) { - var deviceType = row.type; + } + }, + { + targets: 6, + data: 'status', + class: 'text-right content-fill text-left-on-grid-view no-wrap', + render: function (status, type, row, meta) { + var deviceType = row.deviceType; var deviceIdentifier = row.deviceIdentifier; var html = ''; if (status != 'REMOVED') { - html = '' + + html = + '' + + ''; - html += '' + - '' + + html += '' + + + '' + + ''; if (!groupName || !groupOwner) { - html += '' + - '' + - ''; + html += + '' + + '' + + ''; } - html += '' + - '' + - '' + - ''; - html += '' + - '' + - '' + - ''; + html += + '' + + '' + + '' + + ''; + html += + '' + + '' + + '' + + ''; } return html; - }} - ], - "createdRow": function( row, data, dataIndex ) { - $(row).attr('data-type', 'selectable'); - $(row).attr('data-deviceid', data.deviceIdentifier); - $(row).attr('data-devicetype', data.type); - var model = getPropertyValue(data.properties, 'DEVICE_MODEL'); - var vendor = getPropertyValue(data.properties, 'VENDOR'); - var owner = data.enrolmentInfo.owner; - var status = data.enrolmentInfo.status; - var ownership = data.enrolmentInfo.ownership; - var deviceType = data.type; - var category = getDeviceTypeCategory(deviceType); - $.each($('td', row), function (colIndex) { - switch(colIndex) { - case 1: - $(this).attr('data-search', model + ',' + vendor); - $(this).attr('data-display', model); - break; - case 2: - $(this).attr('data-grid-label', "Owner"); - $(this).attr('data-search', owner); - $(this).attr('data-display', owner); - break; - case 3: - $(this).attr('data-grid-label', "Status"); - $(this).attr('data-search', status); - $(this).attr('data-display', status); - break; - case 4: - $(this).attr('data-grid-label', "Type"); - $(this).attr('data-search', deviceType); - $(this).attr('data-display', getDeviceTypeLabel(deviceType)); - break; - case 5: - if (category == 'mobile') { - $(this).attr('data-grid-label', "Ownership"); - $(this).attr('data-search', ownership); - $(this).attr('data-display', ownership); - } - break; + } + } + ]; + + var fnCreatedRow = function (row, data, dataIndex) { + $(row).attr('data-type', 'selectable'); + $(row).attr('data-deviceid', data.deviceIdentifier); + $(row).attr('data-devicetype', data.type); + var model = getPropertyValue(data.properties, 'DEVICE_MODEL'); + var vendor = getPropertyValue(data.properties, 'VENDOR'); + var owner = data.user; + var status = data.status; + var ownership = data.ownership; + var deviceType = data.type; + var category = getDeviceTypeCategory(deviceType); + $.each($('td', row), function (colIndex) { + switch (colIndex) { + case 1: + $(this).attr('data-search', model + ',' + vendor); + $(this).attr('data-display', model); + break; + case 2: + $(this).attr('data-grid-label', "Owner"); + $(this).attr('data-search', owner); + $(this).attr('data-display', owner); + break; + case 3: + $(this).attr('data-grid-label', "Status"); + $(this).attr('data-search', status); + $(this).attr('data-display', status); + break; + case 4: + $(this).attr('data-grid-label', "Type"); + $(this).attr('data-search', deviceType); + $(this).attr('data-display', getDeviceTypeLabel(deviceType)); + break; + case 5: + if (category == 'mobile') { + $(this).attr('data-grid-label', "Ownership"); + $(this).attr('data-search', ownership); + $(this).attr('data-display', ownership); + } + break; + } + }); + }; + + var dataFilter = function (data) { + data = JSON.parse(data); + var objects = []; + + $(data.devices).each(function (index) { + objects.push( + { + model: getPropertyValue(data.devices[index].properties, "DEVICE_MODEL"), + vendor: getPropertyValue(data.devices[index].properties, "VENDOR"), + user: data.devices[index].enrolmentInfo.owner, + status: data.devices[index].enrolmentInfo.status, + ownership: data.devices[index].enrolmentInfo.ownership, + deviceType: data.devices[index].type, + deviceIdentifier: data.devices[index].deviceIdentifier, + name: data.devices[index].name } - }); - }, - "fnDrawCallback": function( oSettings ) { + ); + }); + + var json = { + "recordsTotal": data.count, + "recordsFiltered": data.count, + "data": objects + }; + return JSON.stringify(json); + }; + + $('#device-grid').datatables_extended_serverside_paging( + null, + serviceURL, + dataFilter, + columns, + fnCreatedRow, + function () { $(".icon .text").res_text(0.2); + $('#device-grid').removeClass('hidden'); + $("#loading-content").remove(); attachDeviceEvents(); + }, { + "placeholder": "Search By Device Name", + "searchKey": "name" } - }); + ); + $(deviceCheckbox).click(function () { addDeviceSelectedClass(this); }); @@ -403,7 +466,7 @@ $(document).ready(function () { var permissionList = $("#permission").data("permission"); for (var key in permissionList) { - if (permissionList.hasOwnProperty(key)){ + if (permissionList.hasOwnProperty(key)) { $.setPermission(key); } } @@ -412,29 +475,29 @@ $(document).ready(function () { /* for device list sorting drop down */ $(".ctrl-filter-type-switcher").popover({ - html : true, - content : function () { - return $("#content-filter-types").html(); - } - }); + html: true, + content: function () { + return $("#content-filter-types").html(); + } + }); /* for data tables*/ $('[data-toggle="tooltip"]').tooltip(); $("[data-toggle=popover]").popover(); - $(".ctrl-filter-type-switcher").popover ({ - html : true, - content: function() { - return $('#content-filter-types').html(); - } - }); - - $('#nav').affix ({ - offset: { - top: $('header').height() - } - }); + $(".ctrl-filter-type-switcher").popover({ + html: true, + content: function () { + return $('#content-filter-types').html(); + } + }); + + $('#nav').affix({ + offset: { + top: $('header').height() + } + }); }); @@ -464,7 +527,7 @@ function showPopup() { function hidePopup() { $(modalPopupContent).html(''); $(modalPopup).modal('hide'); - $('body').removeClass('modal-open').css('padding-right','0px'); + $('body').removeClass('modal-open').css('padding-right', '0px'); $('.modal-backdrop').remove(); } @@ -483,16 +546,17 @@ function attachDeviceEvents() { var deviceId = $(this).data("deviceid"); var deviceType = $(this).data("devicetype"); $(modalPopupContent).html($('#group-device-modal-content').html()); - $('#user-groups').html('
'); + $('#user-groups').html( + '
'); $("a#group-device-yes-link").hide(); showPopup(); var serviceURL; if ($.hasPermission("LIST_ALL_GROUPS")) { - serviceURL = "/devicemgt_admin/groups/all"; + serviceURL = "/api/device-mgt/v1.0/groups/all"; } else if ($.hasPermission("LIST_GROUPS")) { //Get authenticated users groups - serviceURL = "/devicemgt_admin/groups/user/" + currentUser + "/all"; + serviceURL = "/api/device-mgt/v1.0/groups/user/" + currentUser + "/all"; } invokerUtil.get(serviceURL, function (data) { @@ -507,7 +571,7 @@ function attachDeviceEvents() { $("a#group-device-yes-link").show(); $("a#group-device-yes-link").click(function () { var selectedGroup = $('#assign-group-selector').val(); - serviceURL = "/devicemgt_admin/groups/owner/" + selectedGroup + "/devices"; + serviceURL = "/api/device-mgt/v1.0/groups/owner/" + selectedGroup + "/devices"; var device = {"id": deviceId, "type": deviceType}; invokerUtil.post(serviceURL, device, function (data) { $(modalPopupContent).html($('#group-associate-device-200-content').html()); @@ -545,7 +609,7 @@ function attachDeviceEvents() { $("a.remove-device-link").click(function () { var deviceId = $(this).data("deviceid"); var deviceType = $(this).data("devicetype"); - var serviceURL = "/devicemgt_admin/devices/type/" + deviceType + "/id/" + deviceId; + var serviceURL = "/api/device-mgt/v1.0/devices/type/" + deviceType + "/id/" + deviceId; $(modalPopupContent).html($('#remove-device-modal-content').html()); showPopup(); @@ -576,7 +640,7 @@ function attachDeviceEvents() { var deviceId = $(this).data("deviceid"); var deviceType = $(this).data("devicetype"); var deviceName = $(this).data("devicename"); - var serviceURL = "/devicemgt_admin/devices/type/" + deviceType + "/id/" + deviceId; + var serviceURL = "/api/device-mgt/v1.0/devices/type/" + deviceType + "/id/" + deviceId; $(modalPopupContent).html($('#edit-device-modal-content').html()); $('#edit-device-name').val(deviceName); @@ -630,6 +694,6 @@ function displayDeviceErrors(jqXHR) { function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), - results = regex.exec(location.search); + results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } From f2af4bd078396ae6289312e66e152d058abc6c97 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Sat, 24 Sep 2016 01:35:59 +0530 Subject: [PATCH 03/21] Fixing undefined exception when device properties not available --- .../devicemgt/app/units/cdmf.unit.device.view/view.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js index a3a0037dcb..be80c2e4a6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js @@ -27,7 +27,7 @@ function onRequest(context) { if (device) { var viewModel = {}; - var deviceInfo = device.properties.DEVICE_INFO; + var deviceInfo = (device.properties) ? device.properties.DEVICE_INFO : null; if (deviceInfo != undefined && String(deviceInfo.toString()).length > 0) { deviceInfo = parse(stringify(deviceInfo)); if (device.type == "ios") { From b5b4f508b02e1c72ab10b358ac619a24d00bf93a Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 14:53:04 +0530 Subject: [PATCH 04/21] Fixing NPE when fetching opeartion --- .../notification/mgt/PushNotificationBasedOperationManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java index 7ba75c60c0..6f0f020482 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/push/notification/mgt/PushNotificationBasedOperationManager.java @@ -46,7 +46,7 @@ public class PushNotificationBasedOperationManager implements OperationManager { Activity activity = this.operationManager.addOperation(operation, devices); for (DeviceIdentifier deviceId : devices) { try { - this.notificationProvider.execute(new NotificationContext(deviceId)); + this.notificationProvider.execute(new NotificationContext(deviceId, operation)); } catch (PushNotificationExecutionFailedException e) { throw new OperationManagementException("Error occurred while sending push notification to device", e); } From a61be7a7ec72a70bab6fb3a5fd2090353717a523 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 14:56:34 +0530 Subject: [PATCH 05/21] Enable group management api --- .../service/api/GroupManagementService.java | 153 +++++++------- .../admin/GroupManagementAdminService.java | 152 +++++++------- .../impl/GroupManagementServiceImpl.java | 197 +++++++++--------- .../GroupManagementAdminServiceImpl.java | 62 +++--- .../src/main/webapp/WEB-INF/cxf-servlet.xml | 2 +- 5 files changed, 295 insertions(+), 271 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java index cf5b2882fa..f21d1c9a4b 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/GroupManagementService.java @@ -18,85 +18,96 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.api; -import org.wso2.carbon.apimgt.annotations.api.Scope; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -//@Path("/groups") -//@Produces(MediaType.APPLICATION_JSON) -//@Consumes(MediaType.APPLICATION_JSON) +@API(name = "Group Management", version = "1.0.0", context = "/api/device-mgt/v1.0/groups", tags = {"devicemgt_admin"}) + +@Path("/groups") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) public interface GroupManagementService { -// @GET -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) -// Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, -// @QueryParam("limit") int limit); -// -// @POST -// @Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/add"}) -// Response createGroup(DeviceGroup group); -// -// @Path("/{groupName}") -// @GET -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/view"}) -// Response getGroup(@PathParam("groupName") String groupName); -// -// @Path("/{groupName}") -// @PUT -// @Permission(scope = "group-modify", permissions = {"/permission/admin/device-mgt/user/groups/update"}) -// Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup); -// -// @Path("/{groupName}") -// @DELETE -// @Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/remove"}) -// Response deleteGroup(@PathParam("groupName") String groupName); -// -// @Path("/{groupName}/share-with-user") -// @POST -// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/share"}) -// Response shareGroupWithUser(@PathParam("groupName") String groupName, String targetUser); -// -// @Path("/{groupName}/share-with-role") -// @POST -// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/share"}) -// Response shareGroupWithRole(@PathParam("groupName") String groupName, String targetRole); -// -// @Path("/{groupName}/remove-share-with-user") -// @POST -// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/unshare"}) -// Response removeShareWithUser(@PathParam("groupName") String groupName, String targetUser); -// -// @Path("/{groupName}/remove-share-with-role") -// @POST -// @Permission(scope = "group-share", permissions = {"/permission/admin/device-mgt/user/groups/unshare"}) -// Response removeShareWithRole(@PathParam("groupName") String groupName, String targetUser); -// -// @GET -// @Path("/{groupName}/users") -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) -// Response getUsersOfGroup(@PathParam("groupName") String groupName); -// -// @GET -// @Path("/{groupName}/devices") -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/groups/roles"}) -// Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, -// @QueryParam("limit") int limit); -// -// @POST -// @Path("/{groupName}/devices") -// @Produces("application/json") -// @Permission(scope = "group-add", permissions = {"/permission/admin/device-mgt/user/groups/devices/add"}) -// Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier); -// -// @DELETE -// @Path("/{groupName}/devices") -// @Permission(scope = "group-remove", permissions = {"/permission/admin/device-mgt/user/groups/devices/remove"}) -// Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, -// @QueryParam("id") String id); + @GET + @Permission(name = "View Group", permission = "/permission/admin/device-mgt/user/groups/list") + Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, + @QueryParam("limit") int limit); + + @POST + @Permission(name = "Add Group", permission = "/permission/admin/device-mgt/user/groups/add") + Response createGroup(DeviceGroup group); + + @Path("/{groupName}") + @GET + @Permission(name = "View Group", permission = "/permission/admin/device-mgt/user/groups/view") + Response getGroup(@PathParam("groupName") String groupName); + + @Path("/{groupName}") + @PUT + @Permission(name = "Update Group", permission = "/permission/admin/device-mgt/user/groups/update") + Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup); + + @Path("/{groupName}") + @DELETE + @Permission(name = "Remove Groups", permission = "/permission/admin/device-mgt/user/groups/remove") + Response deleteGroup(@PathParam("groupName") String groupName); + + @Path("/{groupName}/share-with-user") + @POST + @Permission(name = "Share Group to a User", permission = "/permission/admin/device-mgt/user/groups/share") + Response shareGroupWithUser(@PathParam("groupName") String groupName, String targetUser); + + @Path("/{groupName}/share-with-role") + @POST + @Permission(name = "Share Group to a Role", permission = "/permission/admin/device-mgt/user/groups/share") + Response shareGroupWithRole(@PathParam("groupName") String groupName, String targetRole); + + @Path("/{groupName}/remove-share-with-user") + @POST + @Permission(name = "Unshare a Group", permission = "/permission/admin/device-mgt/user/groups/unshare") + Response removeShareWithUser(@PathParam("groupName") String groupName, String targetUser); + + @Path("/{groupName}/remove-share-with-role") + @POST + @Permission(name = "Unshare a Group", permission = "/permission/admin/device-mgt/user/groups/unshare") + Response removeShareWithRole(@PathParam("groupName") String groupName, String targetUser); + + @GET + @Path("/{groupName}/users") + @Permission(name = "Get Users of Group", permission = "/permission/admin/device-mgt/user/groups/list") + Response getUsersOfGroup(@PathParam("groupName") String groupName); + + @GET + @Path("/{groupName}/devices") + @Permission(name = "Get Devices of Group", permission = "/permission/admin/device-mgt/groups/roles") + Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, + @QueryParam("limit") int limit); + + @POST + @Path("/{groupName}/devices") + @Produces("application/json") + @Permission(name = "Add Device to a Group", permission = "/permission/admin/device-mgt/user/groups/devices/add") + Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier); + @DELETE + @Path("/{groupName}/devices") + @Permission(name = "Remove Devices from Group", + permission = "/permission/admin/device-mgt/user/groups/devices/remove") + Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, + @QueryParam("id") String id); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java index 0580d8504d..885005944a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/api/admin/GroupManagementAdminService.java @@ -18,82 +18,92 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.api.admin; -import io.swagger.annotations.*; -import org.wso2.carbon.apimgt.annotations.api.Scope; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.ResponseHeader; +import org.wso2.carbon.apimgt.annotations.api.API; +import org.wso2.carbon.apimgt.annotations.api.Permission; import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.Date; -//@Path("/admin/groups") -//@Produces(MediaType.APPLICATION_JSON) -//@Consumes(MediaType.APPLICATION_JSON) -//@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + -// "'internal' components to log in as an admin user and do a selected number of operations. " + -// "Further, this is strictly restricted to admin users only ") -public interface GroupManagementAdminService { - -// @GET -// @ApiOperation( -// produces = MediaType.APPLICATION_JSON, -// httpMethod = "GET", -// value = "Get groups by the name.", -// notes = "Get devices the name of device and tenant.", -// response = DeviceGroupWrapper.class, -// responseContainer = "List", -// tags = "Group Management Administrative Service") -// @ApiResponses(value = { -// @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", -// response = DeviceGroupWrapper.class, -// responseContainer = "List", -// responseHeaders = { -// @ResponseHeader( -// name = "Content-Type", -// description = "The content type of the body"), -// @ResponseHeader( -// name = "ETag", -// description = "Entity Tag of the response resource.\n" + -// "Used by caches, or in conditional requests."), -// @ResponseHeader( -// name = "Last-Modified", -// description = "Date and time the resource has been modified the last time.\n" + -// "Used by caches, or in conditional requests."), -// }), -// @ApiResponse( -// code = 304, -// message = "Not Modified. \n Empty body because the client has already the latest version of the requested resource."), -// @ApiResponse( -// code = 406, -// message = "Not Acceptable.\n The requested media type is not supported"), -// @ApiResponse( -// code = 500, -// message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") -// }) -// @Permission(scope = "group-view", permissions = {"/permission/admin/device-mgt/user/groups/list"}) -// Response getGroupsOfUser( -// @ApiParam( -// name = "username", -// value = "Username of the user.", -// required = true) -// @QueryParam("username") String username, -// @ApiParam( -// name = "If-Modified-Since", -// value = "Timestamp of the last modified date", -// required = false) -// @HeaderParam("If-Modified-Since") String timestamp, -// @ApiParam( -// name = "offset", -// value = "Starting point within the complete list of items qualified.", -// required = false) -// @QueryParam("offset") int offset, -// @ApiParam( -// name = "limit", -// value = "Maximum size of resource array to return.", -// required = false) -// @QueryParam("limit") int limit); -// +@API(name = "Group Management Admin", version = "1.0.0", context = "/api/device-mgt/v1.0/admin/groups", tags = {"devicemgt_admin"}) +@Path("/admin/groups") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Api(value = "Group Management Administrative Service", description = "This an API intended to be used by " + + "'internal' components to log in as an admin user and do a selected number of operations. " + + "Further, this is strictly restricted to admin users only ") +public interface GroupManagementAdminService { + @GET + @ApiOperation( + produces = MediaType.APPLICATION_JSON, + httpMethod = "GET", + value = "Get groups by the name.", + notes = "Get devices the name of device and tenant.", + response = DeviceGroupWrapper.class, + responseContainer = "List", + tags = "Group Management Administrative Service") + @ApiResponses(value = { + @ApiResponse(code = 200, message = "OK. \n Successfully fetched the list of groups.", + response = DeviceGroupWrapper.class, + responseContainer = "List", + responseHeaders = { + @ResponseHeader( + name = "Content-Type", + description = "The content type of the body"), + @ResponseHeader( + name = "ETag", + description = "Entity Tag of the response resource.\n" + + "Used by caches, or in conditional requests."), + @ResponseHeader( + name = "Last-Modified", + description = "Date and time the resource has been modified the last time.\n" + + "Used by caches, or in conditional requests."), + }), + @ApiResponse( + code = 304, + message = "Not Modified. \n Empty body because the client has already the latest version of the " + + "requested resource."), + @ApiResponse( + code = 406, + message = "Not Acceptable.\n The requested media type is not supported"), + @ApiResponse( + code = 500, + message = "Internal Server ErrorResponse. \n Server error occurred while fetching the group list.") + }) + @Permission(name = "View All Groups", permission = "/permission/admin/device-mgt/user/groups/list") + Response getGroupsOfUser( + @ApiParam( + name = "username", + value = "Username of the user.", + required = true) + @QueryParam("username") String username, + @ApiParam( + name = "If-Modified-Since", + value = "Timestamp of the last modified date", + required = false) + @HeaderParam("If-Modified-Since") String timestamp, + @ApiParam( + name = "offset", + value = "Starting point within the complete list of items qualified.", + required = false) + @QueryParam("offset") int offset, + @ApiParam( + name = "limit", + value = "Maximum size of resource array to return.", + required = false) + @QueryParam("limit") int limit); } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java index 0b12ebb687..10e6fef2c9 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/GroupManagementServiceImpl.java @@ -18,10 +18,6 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl; -import org.wso2.carbon.device.mgt.common.DeviceIdentifier; -import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroup; -import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; -import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; @@ -33,105 +29,108 @@ import org.wso2.carbon.device.mgt.jaxrs.service.api.GroupManagementService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; import org.wso2.carbon.policy.mgt.common.DeviceGroupWrapper; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.ArrayList; import java.util.List; -//@Path("/groups") -//@Produces(MediaType.APPLICATION_JSON) -//@Consumes(MediaType.APPLICATION_JSON) +@Path("/groups") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) public class GroupManagementServiceImpl implements GroupManagementService { -// private static final Log log = LogFactory.getLog(GroupManagementServiceImpl.class); -// -// @Override -// public Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, -// @QueryParam("limit") int limit) { -// try { -// List groupWrappers = new ArrayList<>(); -// GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); -// List deviceGroups = service.getGroups(user); -// int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); -// for (DeviceGroup dg : deviceGroups) { -// DeviceGroupWrapper gw = new DeviceGroupWrapper(); -// gw.setId(dg.getId()); -// gw.setOwner(dg.getOwner()); -// gw.setName(dg.getName()); -// gw.setTenantId(tenantId); -// groupWrappers.add(gw); -// } -// return Response.status(Response.Status.OK).entity(groupWrappers).build(); -// } catch (GroupManagementException e) { -// String error = "ErrorResponse occurred while getting the groups related to users for policy."; -// log.error(error, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); -// } -// } -// -// @Override -// public Response createGroup(DeviceGroup group) { -// return null; -// } -// -// @Override -// public Response getGroup(@PathParam("groupName") String groupName) { -// return null; -// } -// -// @Override -// public Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup) { -// return null; -// } -// -// @Override -// public Response deleteGroup(@PathParam("groupName") String groupName) { -// return null; -// } -// -// @Override -// public Response shareGroupWithUser(String groupName, String targetUser) { -// return null; -// } -// -// @Override -// public Response shareGroupWithRole(String groupName, String targetRole) { -// return null; -// } -// -// @Override -// public Response removeShareWithUser(@PathParam("groupName") String groupName, -// @QueryParam("username") String targetUser) { -// return null; -// } -// -// @Override -// public Response removeShareWithRole(@PathParam("groupName") String groupName, -// @QueryParam("roleName") String targetUser) { -// return null; -// } -// -// @Override -// public Response getUsersOfGroup(@PathParam("groupName") String groupName) { -// return null; -// } -// -// @Override -// public Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, -// @QueryParam("limit") int limit) { -// return null; -// } -// -// @Override -// public Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier) { -// return null; -// } -// -// @Override -// public Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, -// @QueryParam("id") String id) { -// return null; -// } - -} + private static final Log log = LogFactory.getLog(GroupManagementServiceImpl.class); + + @Override + public Response getGroups(@QueryParam("user") String user, @QueryParam("offset") int offset, + @QueryParam("limit") int limit) { + try { + List groupWrappers = new ArrayList<>(); + GroupManagementProviderService service = DeviceMgtAPIUtils.getGroupManagementProviderService(); + List deviceGroups = service.getGroups(user); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + for (DeviceGroup dg : deviceGroups) { + DeviceGroupWrapper gw = new DeviceGroupWrapper(); + gw.setId(dg.getId()); + gw.setOwner(dg.getOwner()); + gw.setName(dg.getName()); + gw.setTenantId(tenantId); + groupWrappers.add(gw); + } + return Response.status(Response.Status.OK).entity(groupWrappers).build(); + } catch (GroupManagementException e) { + String error = "ErrorResponse occurred while getting the groups related to users for policy."; + log.error(error, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error).build(); + } + } + + @Override + public Response createGroup(DeviceGroup group) { + return null; + } + + @Override + public Response getGroup(@PathParam("groupName") String groupName) { + return null; + } + + @Override + public Response updateGroup(@PathParam("groupName") String groupName, DeviceGroup deviceGroup) { + return null; + } + + @Override + public Response deleteGroup(@PathParam("groupName") String groupName) { + return null; + } + + @Override + public Response shareGroupWithUser(String groupName, String targetUser) { + return null; + } + + @Override + public Response shareGroupWithRole(String groupName, String targetRole) { + return null; + } + + @Override + public Response removeShareWithUser(@PathParam("groupName") String groupName, + @QueryParam("username") String targetUser) { + return null; + } + + @Override + public Response removeShareWithRole(@PathParam("groupName") String groupName, + @QueryParam("roleName") String targetUser) { + return null; + } + + @Override + public Response getUsersOfGroup(@PathParam("groupName") String groupName) { + return null; + } + + @Override + public Response getDevicesOfGroup(@PathParam("groupName") String groupName, @QueryParam("offset") int offset, + @QueryParam("limit") int limit) { + return null; + } + + @Override + public Response addDeviceToGroup(@PathParam("groupName") String groupName, DeviceIdentifier deviceIdentifier) { + return null; + } + + @Override + public Response removeDeviceFromGroup(@PathParam("groupName") String groupName, @QueryParam("type") String type, + @QueryParam("id") String id) { + return null; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java index 7573df0f5e..9cf5253c2c 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/java/org/wso2/carbon/device/mgt/jaxrs/service/impl/admin/GroupManagementAdminServiceImpl.java @@ -18,7 +18,6 @@ */ package org.wso2.carbon.device.mgt.jaxrs.service.impl.admin; -import io.swagger.annotations.ApiParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.device.mgt.common.PaginationResult; @@ -26,37 +25,42 @@ import org.wso2.carbon.device.mgt.common.group.mgt.GroupManagementException; import org.wso2.carbon.device.mgt.jaxrs.service.api.admin.GroupManagementAdminService; import org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils; -import javax.ws.rs.*; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; -import java.util.Date; -//@Path("/admin/groups") -//@Produces(MediaType.APPLICATION_JSON) -//@Consumes(MediaType.APPLICATION_JSON) +@Path("/admin/groups") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) public class GroupManagementAdminServiceImpl implements GroupManagementAdminService { -// -// private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); -// -// @Override -// public Response getGroupsOfUser( -// @QueryParam("username") String username, -// @HeaderParam("If-Modified-Since") String timestamp, -// @QueryParam("offset") int offset, -// @QueryParam("limit") int limit) { -// try { -// PaginationResult result = -// DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); -// if (result != null && result.getRecordsTotal() > 0) { -// return Response.status(Response.Status.OK).entity(result).build(); -// } else { -// return Response.status(Response.Status.NOT_FOUND).build(); -// } -// } catch (GroupManagementException e) { -// String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; -// log.error(msg, e); -// return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); -// } -// } + + private static final Log log = LogFactory.getLog(GroupManagementAdminServiceImpl.class); + + @GET + @Override + public Response getGroupsOfUser( + @QueryParam("username") String username, + @HeaderParam("If-Modified-Since") String timestamp, + @QueryParam("offset") int offset, + @QueryParam("limit") int limit) { + try { + PaginationResult result = + DeviceMgtAPIUtils.getGroupManagementProviderService().getGroups(username, offset, limit); + if (result != null && result.getRecordsTotal() > 0) { + return Response.status(Response.Status.OK).entity(result).build(); + } else { + return Response.status(Response.Status.NOT_FOUND).build(); + } + } catch (GroupManagementException e) { + String msg = "ErrorResponse occurred while retrieving the groups of user '" + username + "'"; + log.error(msg, e); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build(); + } + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml index 8405fb99fc..a5f5ed308a 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml +++ b/components/device-mgt/org.wso2.carbon.device.mgt.api/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -73,7 +73,7 @@ - + From 86a45fec2eb73d23ee54af5af58bf66e1813cb65 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 14:57:10 +0530 Subject: [PATCH 06/21] Fixes to mqtt notification strategy when message body is null --- .../provider/mqtt/MQTTNotificationStrategy.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java index 29d623b349..fae2658228 100644 --- a/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java +++ b/components/device-mgt-extensions/org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt/src/main/java/org/wso2/carbon/device/mgt/extensions/push/notification/provider/mqtt/MQTTNotificationStrategy.java @@ -21,6 +21,7 @@ package org.wso2.carbon.device.mgt.extensions.push.notification.provider.mqtt; 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.operation.mgt.Operation; import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext; import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy; import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig; @@ -77,17 +78,22 @@ public class MQTTNotificationStrategy implements NotificationStrategy { @Override public void execute(NotificationContext ctx) throws PushNotificationExecutionFailedException { Map dynamicProperties = new HashMap<>(); - Properties properties = ctx.getOperation().getProperties(); + Operation operation = ctx.getOperation(); + Properties properties = operation.getProperties(); if (properties != null && properties.get(MQTT_ADAPTER_TOPIC) != null) { dynamicProperties.put("topic", (String) properties.get(MQTT_ADAPTER_TOPIC)); } else { String topic = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain(true) + "/" - + ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/" + ctx.getOperation().getType(); + + ctx.getDeviceId().getType() + "/" + ctx.getDeviceId().getId() + "/" + operation.getType() + + "/" + operation.getCode(); dynamicProperties.put("topic", topic); + if (operation.getPayLoad() == null) { + operation.setPayLoad(""); + } } MQTTDataHolder.getInstance().getOutputEventAdapterService().publish(mqttAdapterName, dynamicProperties, - ctx.getOperation().getPayLoad()); + operation.getPayLoad()); } @Override From cef865f53ac18fa54ce901735b641eb07163b7b9 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 17:13:43 +0530 Subject: [PATCH 07/21] Parsing deviceType configs with %https.ip% and %http.ip% --- .../jaggeryapps/devicemgt/app/modules/utility.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js index 3af4f59e6a..3b96ff0056 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/modules/utility.js @@ -24,6 +24,7 @@ utility = function () { var log = new Log("/app/modules/utility.js"); var JavaClass = Packages.java.lang.Class; var PrivilegedCarbonContext = Packages.org.wso2.carbon.context.PrivilegedCarbonContext; + var server = require("carbon")["server"]; var getOsgiService = function (className) { return PrivilegedCarbonContext.getThreadLocalCarbonContext().getOSGiService(JavaClass.forName(className)); @@ -38,8 +39,8 @@ utility = function () { PrivilegedCarbonContext.startTenantFlow(); context = PrivilegedCarbonContext.getThreadLocalCarbonContext(); context.setTenantDomain(carbon.server.tenantDomain({ - tenantId: userInfo.tenantId - })); + tenantId: userInfo.tenantId + })); context.setTenantId(userInfo.tenantId); context.setUsername(userInfo.username || null); }; @@ -62,7 +63,7 @@ utility = function () { publicMethods.getDeviceTypeConfig = function (deviceType) { var unitName = publicMethods.getTenantedDeviceUnitName(deviceType, "type-view"); - + if (deviceType in deviceTypeConfigMap) { return deviceTypeConfigMap[deviceType]; } @@ -71,7 +72,10 @@ utility = function () { if (deviceTypeConfigFile.isExists()) { try { deviceTypeConfigFile.open("r"); - deviceTypeConfig = parse(deviceTypeConfigFile.readAll()); + var config = deviceTypeConfigFile.readAll(); + config = config.replace("%https.ip%", server.address("https")); + config = config.replace("%http.ip%", server.address("http")); + deviceTypeConfig = parse(config); } catch (err) { log.error("Error while reading device config file for `" + deviceType + "`: " + err); } finally { From 4c4eba93d8a7498d31fe211cd9953d02574690b0 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 17:15:12 +0530 Subject: [PATCH 08/21] Returning correct representation of the device to template. --- .../devicemgt/app/units/cdmf.unit.device.view/view.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js index be80c2e4a6..8ba043981f 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.view/view.js @@ -23,7 +23,7 @@ function onRequest(context) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"]; - var device = deviceModule.viewDevice(deviceType, deviceId); + var device = deviceModule.viewDevice(deviceType, deviceId)["content"]; if (device) { var viewModel = {}; From 1bef7a38efd3ff7736e5e99ce1a84827eaeb2abf Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 18:08:06 +0530 Subject: [PATCH 09/21] Minor style fix for wr-hidden-operations --- .../app/units/cdmf.unit.ui.theme/public/css/custom-desktop.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.theme/public/css/custom-desktop.css b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.theme/public/css/custom-desktop.css index 288b74b8e6..fe75cb54f0 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.theme/public/css/custom-desktop.css +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.ui.theme/public/css/custom-desktop.css @@ -4562,7 +4562,7 @@ a.wr-side-panel-toggle-btn.selected { position: absolute; top: 0; bottom: 0; - left: -900px; + left: -1000px; z-index: 10000; -moz-transition: left 0.4s ease; transition: left 0.4s ease 0s; From 77720dd61a4faccdfc13360902699abaa00e47b3 Mon Sep 17 00:00:00 2001 From: Rasika Perera Date: Mon, 26 Sep 2016 18:25:11 +0530 Subject: [PATCH 10/21] Fixing devices listing page styling issue. --- .../app/pages/cdmf.page.devices/devices.hbs | 148 ++++++++++-------- 1 file changed, 80 insertions(+), 68 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs index fafc053374..80db7095c6 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs +++ b/components/device-mgt/org.wso2.carbon.device.mgt.ui/src/main/resources/jaggeryapps/devicemgt/app/pages/cdmf.page.devices/devices.hbs @@ -138,11 +138,11 @@ -
+
-
+