fixed analytics issues

revert-70aa11f8
ayyoob 8 years ago
parent 75d6813d8a
commit 56faa75861

@ -111,6 +111,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
private static final String OAUTH_MQTT_ADAPTER_TYPE = "oauth-mqtt";
private static final String OAUTH_HTTP_ADAPTER_TYPE = "oauth-http";
private static final String DEFAULT_DEVICE_ID_ATTRIBUTE = "deviceId";
private static final String DEFAULT_META_DEVICE_ID_ATTRIBUTE = "meta_deviceId";
private static KeyStore keyStore;
private static KeyStore trustStore;
@ -163,9 +164,6 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
EventAttributeList eventAttributeList = new EventAttributeList();
List<Attribute> attributes = new ArrayList<>();
for (EventStreamAttributeDto eventStreamAttributeDto : eventStreamAttributeDtos) {
if (DEFAULT_DEVICE_ID_ATTRIBUTE.equals(eventStreamAttributeDto.getAttributeName())) {
continue;
}
attributes.add(new Attribute(eventStreamAttributeDto.getAttributeName()
, AttributeType.valueOf(eventStreamAttributeDto.getAttributeType().toUpperCase())));
}
@ -176,11 +174,13 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
eventReceiverAdminServiceStub = getEventReceiverAdminServiceStub();
EventReceiverConfigurationDto eventReceiverConfigurationDto = eventReceiverAdminServiceStub
.getActiveEventReceiverConfiguration(getReceiverName(deviceType, tenantDomain));
if (eventReceiverConfigurationDto != null) {
String eventAdapterType = eventReceiverConfigurationDto.getFromAdapterConfigurationDto()
.getEventAdapterType();
if (OAUTH_MQTT_ADAPTER_TYPE.equals(eventAdapterType)) {
deviceTypeEvent.setTransportType(TransportType.MQTT);
}
}
return Response.ok().entity(deviceTypeEvent).build();
} catch (AxisFault e) {
log.error("failed to retrieve event definitions for tenantDomain:" + tenantDomain, e);
@ -285,7 +285,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
}
String eventReceiverName = getReceiverName(deviceType, tenantDomain);
String eventPublisherName = deviceType.trim().toLowerCase() + "_websocket_publisher";
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher";
String streamName = getStreamDefinition(deviceType, tenantDomain);
eventStreamAdminServiceStub = getEventStreamAdminServiceStub();
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamName + ":" + DEFAULT_STREAM_VERSION) == null) {
@ -360,7 +360,8 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
}
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND _timestamp : [" + fromDate + " TO " + toDate + "]";
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId
+ " AND _timestamp : [" + fromDate + " TO " + toDate + "]";
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String sensorTableName = getTableName(getStreamDefinition(deviceType, tenantDomain));
try {
@ -397,7 +398,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
@Path("/last-known/{type}/{deviceId}")
@Override
public Response getLastKnownData(@PathParam("deviceId") String deviceId, @PathParam("type") String deviceType) {
String query = "deviceId:" + deviceId;
String query = DEFAULT_META_DEVICE_ID_ATTRIBUTE + ":" + deviceId;
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
String sensorTableName = getTableName(getStreamDefinition(deviceType, tenantDomain));
try {
@ -436,6 +437,25 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
throws RemoteException, UserStoreException, JWTClientException {
EventReceiverAdminServiceStub receiverAdminServiceStub = getEventReceiverAdminServiceStub();
try {
EventReceiverConfigurationDto eventReceiverConfigurationDto = receiverAdminServiceStub
.getActiveEventReceiverConfiguration(getReceiverName(deviceType, requestedTenantDomain));
if (eventReceiverConfigurationDto != null) {
String eventAdapterType = eventReceiverConfigurationDto.getFromAdapterConfigurationDto()
.getEventAdapterType();
if (OAUTH_MQTT_ADAPTER_TYPE.equals(eventAdapterType)) {
if (transportType == TransportType.MQTT) {
return;
}
} else if (OAUTH_HTTP_ADAPTER_TYPE.equals(eventAdapterType)) {
if (transportType == TransportType.HTTP) {
return;
}
}
// remove mqtt event reciever before publishing
receiverAdminServiceStub.undeployActiveEventReceiverConfiguration(eventRecieverName);
}
String adapterType = OAUTH_MQTT_ADAPTER_TYPE;
BasicInputAdapterPropertyDto basicInputAdapterPropertyDtos[];
if (transportType == TransportType.MQTT) {
@ -448,7 +468,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
} else {
adapterType = OAUTH_HTTP_ADAPTER_TYPE;
basicInputAdapterPropertyDtos = new BasicInputAdapterPropertyDto[1];
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("contentValidator", "iot-mqtt");
basicInputAdapterPropertyDtos[0] = getBasicInputAdapterPropertyDto("contentValidator", "iot-http");
}
if (receiverAdminServiceStub.getActiveEventReceiverConfiguration(eventRecieverName) == null) {
receiverAdminServiceStub.deployJsonEventReceiverConfiguration(eventRecieverName, streamNameWithVersion
@ -468,7 +488,9 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
eventStreamDefinitionDto.setName(streamName);
eventStreamDefinitionDto.setVersion(version);
EventStreamAttributeDto eventStreamAttributeDtos[] =
new EventStreamAttributeDto[eventAttributes.getList().size() + 1];
new EventStreamAttributeDto[eventAttributes.getList().size()];
EventStreamAttributeDto metaStreamAttributeDtos[] =
new EventStreamAttributeDto[1];
int i = 0;
for (Attribute attribute : eventAttributes.getList()) {
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
@ -481,8 +503,9 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
EventStreamAttributeDto eventStreamAttributeDto = new EventStreamAttributeDto();
eventStreamAttributeDto.setAttributeName(DEFAULT_DEVICE_ID_ATTRIBUTE);
eventStreamAttributeDto.setAttributeType(AttributeType.STRING.toString());
eventStreamAttributeDtos[i] = eventStreamAttributeDto;
metaStreamAttributeDtos[0] = eventStreamAttributeDto;
eventStreamDefinitionDto.setPayloadData(eventStreamAttributeDtos);
eventStreamDefinitionDto.setMetaData(metaStreamAttributeDtos);
String streamId = streamName + ":" + version;
if (eventStreamAdminServiceStub.getStreamDefinitionDto(streamId) != null) {
eventStreamAdminServiceStub.editEventStreamDefinitionAsDto(eventStreamDefinitionDto, streamId);
@ -521,7 +544,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
i++;
}
AnalyticsTableRecord analyticsTableRecord = new AnalyticsTableRecord();
analyticsTableRecord.setColumnName(DEFAULT_DEVICE_ID_ATTRIBUTE);
analyticsTableRecord.setColumnName(DEFAULT_META_DEVICE_ID_ATTRIBUTE);
analyticsTableRecord.setColumnType(AttributeType.STRING.toString().toUpperCase());
analyticsTableRecord.setFacet(false);
analyticsTableRecord.setIndexed(true);
@ -540,7 +563,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
throws RemoteException, UserStoreException, JWTClientException {
EventPublisherAdminServiceStub eventPublisherAdminServiceStub = getEventPublisherAdminServiceStub();
try {
String eventPublisherName = deviceType.trim().toLowerCase() + "_websocket_publisher";
String eventPublisherName = deviceType.trim().replace(" ", "_") + "_websocket_publisher";
if (eventPublisherAdminServiceStub.getActiveEventPublisherConfiguration(eventPublisherName) == null) {
eventPublisherAdminServiceStub.deployJsonEventPublisherConfiguration(eventPublisherName
, streamNameWithVersion, DEFAULT_WEBSOCKET_PUBLISHER_ADAPTER_TYPE, null, null
@ -747,7 +770,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
}
private String getStreamDefinition(String deviceType, String tenantDomain) {
return tenantDomain.toLowerCase() + "." + deviceType.toLowerCase();
return "iot.per.device.stream." + tenantDomain + "." + deviceType.replace(" ", ".");
}
private String getTableName(String streamName) {
@ -755,7 +778,7 @@ public class DeviceEventManagementServiceImpl implements DeviceEventManagementSe
}
private String getReceiverName(String deviceType, String tenantDomain) {
return deviceType.trim().toLowerCase() + "-" + tenantDomain.toLowerCase() + "-receiver";
return deviceType.replace(" ", "_").trim() + "-" + tenantDomain + "-receiver";
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {

@ -98,6 +98,16 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
}
try {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService();
if (device.getType() == null || device.getDeviceIdentifier() == null) {
String errorMessage = "The payload of the device enrollment is incorrect.";
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
}
Device existingDevice = dms.getDevice(new DeviceIdentifier(device.getType(), device.getType()));
if (existingDevice != null && existingDevice.getEnrolmentInfo() != null && existingDevice
.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
String errorMessage = "An active enrolment exists";
return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage).build();
}
device.getEnrolmentInfo().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser());
device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis());
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());

@ -93,7 +93,7 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
@Override
@GET
@Path("/all")
@Path("/config")
public Response getDeviceTypes() {
try {
List<DeviceType> deviceTypes = DeviceMgtAPIUtils.getDeviceManagementService().getDeviceTypes();
@ -111,7 +111,7 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
@Override
@GET
@Path("/all/{type}")
@Path("/config/{type}")
public Response getDeviceTypeByName(@PathParam("type") String type) {
if (type != null && type.length() > 0) {
try {
@ -138,12 +138,14 @@ public class DeviceTypeManagementServiceImpl implements DeviceTypeManagementServ
*/
private DeviceType clearMetaEntryInfo(DeviceType deviceType) {
DeviceTypeMetaDefinition metaDefinition = deviceType.getDeviceTypeMetaDefinition();
if (metaDefinition != null) {
metaDefinition.setInitialOperationConfig(null);
if (metaDefinition.getPushNotificationConfig() != null) {
metaDefinition.setPushNotificationConfig(new PushNotificationConfig(metaDefinition.
getPushNotificationConfig().getType(), false, null));
}
deviceType.setDeviceTypeMetaDefinition(metaDefinition);
}
return deviceType;
}

@ -304,6 +304,9 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
public OperationManager getOperationManager(String deviceType, int tenantId) {
//Priority need to be given to the tenant before public.
DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType, tenantId);
if (getDeviceManagementService(deviceType, tenantId) == null) {
return null;
}
OperationManager operationManager = operationManagerRepository.getOperationManager(deviceTypeIdentifier);
if (operationManager == null) {
deviceTypeIdentifier = new DeviceTypeServiceIdentifier(deviceType);
@ -330,7 +333,7 @@ public class DeviceManagementPluginRepository implements DeviceManagerStartupLis
DeviceTypeServiceIdentifier deviceTypeIdentifier = new DeviceTypeServiceIdentifier(
provider.getType(), tenantId);
DeviceManagementServiceHolder existingProvider = providers.get(deviceTypeIdentifier);
if (existingProvider == null) {
if (existingProvider != null) {
removeDeviceManagementProvider(provider);
}
}

@ -29,12 +29,12 @@ public class DeviceTypeServiceIdentifier implements Serializable {
private static final int DEFAULT_SHARE_WITH_ALL_TENANTS_ID = -1;
public DeviceTypeServiceIdentifier(String deviceType, int tenantId) {
this.deviceType = deviceType.toLowerCase();
this.deviceType = deviceType;
this.tenantId = tenantId;
}
public DeviceTypeServiceIdentifier(String deviceType) {
this.deviceType = deviceType.toLowerCase();
this.deviceType = deviceType;
this.tenantId = DEFAULT_SHARE_WITH_ALL_TENANTS_ID;
}

@ -167,6 +167,20 @@ if (!user) {
}else {
response.sendError(403);
}
} else if (uriMatcher.match("/{context}/api/devices/agent/{type}/{deviceId}/config")) {
log.error("matching");
elements = uriMatcher.elements();
deviceId = elements.deviceId;
type = elements.type;
operation = elements.operation;
if (userModule.isAuthorized("/permission/admin/device-mgt/devices/owning-device")) {
result = deviceModule.getDeviceAgentConfig(type, deviceId);
if (!result) {
response.sendError(500);
}
} else {
response.sendError(403);
}
} else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) {
elements = uriMatcher.elements();
deviceId = elements.deviceId;

@ -25,7 +25,8 @@ deviceModule = function () {
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var batchProvider = require("/app/modules/batch-provider-api.js")["batchProviders"];
var process = require("process");
var carbon = require("carbon");
var publicMethods = {};
var privateMethods = {};
@ -305,6 +306,15 @@ deviceModule = function () {
return response;
};
publicMethods.getDeviceTypesConfig = function () {
var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types/config";
var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
if (response.status == "success") {
response.content = parse(response.content);
}
return response;
};
/*
@Updated
*/
@ -344,5 +354,63 @@ deviceModule = function () {
}
);
};
publicMethods.getDeviceAgentConfig = function (type, deviceId) {
var carbonUser = session.get(constants["USER_SESSION_KEY"]);
if (!carbonUser) {
log.error("User object was not found in the session");
throw constants["ERRORS"]["USER_NOT_FOUND"];
}
var userName = carbonUser.username + "@" + carbonUser.domain;
var config = {};
config.type = type;
config.deviceId = deviceId;
// register a tenant based app at API Manager
var applicationName = type.replace(" ", "") + "_" + carbonUser.domain;
var requestURL = (devicemgtProps["oauthProvider"]["appRegistration"]
["apiManagerClientAppRegistrationServiceURL"]).replace("/tenants","");
var payload = {applicationName:applicationName, tags:["device_management"],
isAllowedToAllDomains:false, validityPeriod: 3600};
serviceInvokers.XMLHttp.post(
requestURL, payload, function (responsePayload) {
var app = JSON.parse(responsePayload.responseText);
config.clientId = app["client_id"];
config.clientSecret = app["client_secret"];
if (config.clientId && config.clientSecret) {
var JWTClientManagerServicePackagePath =
"org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService";
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var JWTClientManagerService = carbon.server.osgiService(JWTClientManagerServicePackagePath);
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type
var deviceScope = "device_" + type.replace(" ", "") + "_" + deviceId;
var tokenInfo = jwtClient.getAccessToken(config.clientId, config.clientSecret,
userName, deviceScope);
config.accessToken = tokenInfo.getAccessToken();
config.refreshToken = tokenInfo.getRefreshToken();
if (config.accessToken == null) {
return null;
}
config.mqttGateway = "tcp://" + process.getProperty("mqtt.broker.host") + ":" + process.getProperty("mqtt.broker.port");
config.httpsGateway = "https://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.https.port");
config.httpGateway = "http://" + process.getProperty("iot.gateway.host") + ":" + process.getProperty("iot.gateway.http.port");
return config;
} else {
return null;
}
return config;
},
function (responsePayload) {
log.error(responsePayload);
return null;
}
);
return config;
};
return publicMethods;
}();

@ -103,9 +103,7 @@
</div>
<div class="col-xs-4">
<textarea aria-describedby="basic-addon1" type="text" id="feature-description"
placeholder="description"data-error-msg="invalid feature description"class="form-control" rows="1" cols="30">
{{this.description}}
</textarea>
placeholder="description" data-error-msg="invalid feature description" class="form-control" rows="1" cols="30">{{this.description}}</textarea>
</div>
<button type="button" class="btn btn-default remove_feature_button"><i class="fa fa-minus"></i></button>
</div>

@ -35,7 +35,7 @@ function onRequest(context) {
var deviceType = request.getParameter("type");
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/device-types/all/" + deviceType;
+ "/device-types/config/" + deviceType;
displayData.name = deviceType;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,

@ -25,8 +25,7 @@
{{#zone "overview-section"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Device Overview - {{label}}</div>
{{device.type}}sdf
Device Overview - {{device.type}}</div>
{{unit "cdmf.unit.default.device.overview-section" device=device}}
{{/zone}}
@ -63,7 +62,7 @@
{{#if attributes}}
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div class="panel-heading">Realtime Statistics</div>
<div class="panel-heading">Device Event</div>
{{unit "cdmf.unit.default.device.type.realtime.analytics-view" device=device attributes=attributes}}
</div>
{{/if}}

@ -24,7 +24,6 @@ function onRequest(context) {
var deviceId = request.getParameter("id");
var attributes = [];
var featureList = [];
log.error(featureList);
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/events/" + deviceType;
serviceInvokers.XMLHttp.get(
@ -50,7 +49,6 @@ function onRequest(context) {
+ "/device-types/" + deviceType + "/features";
serviceInvokers.XMLHttp.get(featureEndpoint, function (responsePayload) {
var features = JSON.parse(responsePayload.responseText);
new Log().error(responsePayload.responseText);
var feature;
for (var i = 0; i < features.length; i++) {
feature = {};

@ -18,12 +18,13 @@
{{unit "cdmf.unit.lib.rickshaw-graph"}}
<div id="div-chart" data-websocketurl="{{websocketEndpoint}}" data-attributes="{{attributes}}">
<span id="time-mode">{{#if timestamp}}Last Known:{{timestamp}}{{/if}}</span>
<table class="table table-responsive table-striped" id="members">
<tbody>
{{#each attributes}}
{{#each events}}
<tr role="row" class="odd">
<td class="sorting_1" style="padding:10px 15px;">{{this}}</td>
<td id="{{this}}-value" style="padding:10px 15px;">-</td>
<td class="sorting_1" style="padding:10px 15px;">{{this.key}}</td>
<td id="{{this.key}}-value" style="padding:10px 15px;">{{#if this.value}}{{this.value}}{{else}}-{{/if}}</td>
</tr>
{{/each}}
</tbody>

@ -15,12 +15,15 @@
* specific language governing permissions and limitations
* under the License.
*/
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
function onRequest(context) {
var log = new Log("stats.js");
var carbonServer = require("carbon").server;
var device = context.unit.params.device;
var attributes = context.unit.params.attributes;
var events = [];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var constants = require("/app/modules/constants.js");
@ -40,15 +43,43 @@ function onRequest(context) {
token = tokenPair.accessToken;
}
if (tenantDomain == "carbon.super") {
websocketEndpoint = websocketEndpoint + "/secured-websocket/" + tenantDomain + "." + device.type + "/1.0.0?"
websocketEndpoint = websocketEndpoint + "/secured-websocket/iot.per.device.stream." + tenantDomain + "." + device.type + "/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
} else {
websocketEndpoint = websocketEndpoint + "/t/" + tenantDomain + "/secured-websocket/" + tenantDomain
websocketEndpoint = websocketEndpoint + "/t/" + tenantDomain + "/secured-websocket/iot.per.device.stream." + tenantDomain
+ "." + device.type + "/1.0.0?" + "deviceId=" + device.deviceIdentifier + "&deviceType="
+ device.type + "&websocketToken=" + token;
}
}
var events = [];
var viewModel = {};
viewModel.device = device;
viewModel.websocketEndpoint = websocketEndpoint;
return {"device": device, "websocketEndpoint": websocketEndpoint, "attributes": attributes};
var restAPIEndpoint = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/events/last-known/" + device.type + "/" + device.deviceIdentifier;
serviceInvokers.XMLHttp.get(
restAPIEndpoint,
function (restAPIResponse) {
if (restAPIResponse["status"] == 200 && restAPIResponse["responseText"]) {
var responsePayload = parse(restAPIResponse["responseText"]);
var records = responsePayload["records"];
if (records && records[0] && records[0].values) {
var record = records[0].values;
viewModel.timestamp = new Date(records[0].timestamp);
for (var eventAttribute in attributes){
var event = {};
event.key = attributes[eventAttribute];
event.value = record["" + attributes[eventAttribute]];
events.push(event);
}
}
}
}
);
viewModel.attributes = attributes;
viewModel.events = events;
return viewModel;
}

@ -41,10 +41,12 @@ function connect(target) {
if (ws) {
ws.onmessage = function (webSocketData) {
var data = JSON.parse(webSocketData.data);
console.log(data);
var payloadData = data["event"]["payloadData"];
for (var i = 0; i < attributes.length; i++){
$("#" + attributes[i] +"-value").text(payloadData[attributes[i]]);
}
$("#time-mode").text("Real Time Mode");
};
}
}

@ -434,8 +434,22 @@ $(document).ready(function () {
device,
function (data, textStatus, jqXHR) {
if (jqXHR.status == 200) {
$(successMsg).text("Device added.");
$(successMsgWrapper).removeClass("hidden");
$.ajax({
type: "GET",
url: "/devicemgt/api/devices/agent/" + deviceType + "/" + deviceId + "/config",
success: function(data, status, xhr) {
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(data));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr );
dlAnchorElem.setAttribute("download", deviceId + ".json");
dlAnchorElem.click();
$("#modalDevice").modal('show');
},
error: function(xhr, status, error) {
$(errorMsg).text("Device Created, But failed to download the agent configuration.");
$(errorMsgWrapper).removeClass("hidden");
}
});
}
},
function (jqXHR) {
@ -452,3 +466,9 @@ $(document).ready(function () {
);
});
});
function redirectPage(url) {
var deviceType = $("#deviceTypeName").val();
var deviceId = $("#deviceId").val();
location.href= url + '/' + deviceType + "?id=" + deviceId;
}

@ -172,7 +172,7 @@
<br>
<button id="add-device-btn" class="wr-btn">Create Device</button>
<a id="downloadAnchorElem" style="display:none"></a>
<div id="device-create-success-msg" class="alert hidden" role="alert">
<i class="icon fw fw-success"></i><span></span>
</div>
@ -188,6 +188,20 @@
</button>
</div>
</div>
<div class="modal fade" id="modalDevice" tabindex="-1" role="dialog" aria-labelledby="modalDevice">
<div class="modal-dialog" role="document">
<div class="modal-content clearfix">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fw fw-cancel"></i></button>
<h3 class="modal-title" id="deviceModalLabel">Device Created Succesfully</h3>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="redirectPage('{{@app.context}}/device');">Go To Device Page</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<!-- /content -->
<div id="app-context" data-app-context="{{@app.context}}" class="hidden"></div>
</div>

@ -31,7 +31,7 @@ function onRequest(context) {
return opts.inverse(this);
});
var restAPIEndpoint = deviceMgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"]
+ "/device-types/all/" + deviceType;
+ "/device-types/config/" + deviceType;
displayData.deviceType = deviceType;
displayData.tenantDomain = tenantDomain;
serviceInvokers.XMLHttp.get(
@ -59,7 +59,6 @@ function onRequest(context) {
var eventExample = {};
for (var i = 0; i < typeData.eventAttributes.attributes.length; i++) {
var attribute = typeData.eventAttributes.attributes[i];
new Log().error(attribute.type);
switch (attribute.type) {
case "STRING":
eventExample[attribute.name] = "string";
@ -83,7 +82,10 @@ function onRequest(context) {
}
}
var metaEventExample = {};
metaEventExample.deviceId = "deviceIdentifier";
sample.event.payloadData = eventExample;
sample.event.metaData = metaEventExample;
displayData.eventSample = JSON.stringify(sample);
}
}

@ -32,11 +32,11 @@ function onRequest(context) {
types.isAuthorizedViewGroups = userModule.isAuthorized("/permission/admin/device-mgt/groups/view");
types["types"] = [];
var typesListResponse = deviceModule.getDeviceTypes();
var typesListResponse = deviceModule.getDeviceTypesConfig();
if (typesListResponse["status"] == "success") {
for (var type in typesListResponse["content"]["deviceTypes"]) {
for (var type in typesListResponse["content"]) {
var content = {};
var deviceType = typesListResponse["content"]["deviceTypes"][type];
var deviceType = typesListResponse["content"][type].name;
content["name"] = deviceType;
var configs = utility.getDeviceTypeConfig(deviceType);
var deviceTypeLabel = deviceType;
@ -64,7 +64,10 @@ function onRequest(context) {
}
types["types"].push(content);
} else {
policyWizardSrc = "cdmf.unit.policy.create"
if (!typesListResponse["content"][type].deviceTypeMetaDefinition) {
continue;
}
policyWizardSrc = "cdmf.unit.policy.create";
var policyOperationsTemplateSrc = policyWizardSrc + "/public/templates/" + deviceType + "-policy-operations.hbs";
if (new File(policyOperationsTemplateSrc).isExists()) {
content["template"] = "/public/cdmf.unit.device.type." + deviceType +

Loading…
Cancel
Save