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

@ -98,6 +98,16 @@ public class DeviceManagementServiceImpl implements DeviceManagementService {
} }
try { try {
DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); 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().setOwner(DeviceMgtAPIUtils.getAuthenticatedUser());
device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis()); device.getEnrolmentInfo().setDateOfEnrolment(System.currentTimeMillis());
device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis()); device.getEnrolmentInfo().setDateOfLastUpdate(System.currentTimeMillis());

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

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

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

@ -167,6 +167,20 @@ if (!user) {
}else { }else {
response.sendError(403); 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}")) { } else if (uriMatcher.match("{context}/api/devices/{type}/{deviceId}/{operation}")) {
elements = uriMatcher.elements(); elements = uriMatcher.elements();
deviceId = elements.deviceId; deviceId = elements.deviceId;

@ -25,7 +25,8 @@ deviceModule = function () {
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"]; var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];
var batchProvider = require("/app/modules/batch-provider-api.js")["batchProviders"]; var batchProvider = require("/app/modules/batch-provider-api.js")["batchProviders"];
var process = require("process");
var carbon = require("carbon");
var publicMethods = {}; var publicMethods = {};
var privateMethods = {}; var privateMethods = {};
@ -305,6 +306,15 @@ deviceModule = function () {
return response; 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 @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; return publicMethods;
}(); }();

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

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

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

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

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

@ -15,12 +15,15 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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) { function onRequest(context) {
var log = new Log("stats.js"); var log = new Log("stats.js");
var carbonServer = require("carbon").server; var carbonServer = require("carbon").server;
var device = context.unit.params.device; var device = context.unit.params.device;
var attributes = context.unit.params.attributes; var attributes = context.unit.params.attributes;
var events = [];
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"]; var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var userModule = require("/app/modules/business-controllers/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
@ -40,15 +43,43 @@ function onRequest(context) {
token = tokenPair.accessToken; token = tokenPair.accessToken;
} }
if (tenantDomain == "carbon.super") { 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; + "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
} else { } 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 + "/1.0.0?" + "deviceId=" + device.deviceIdentifier + "&deviceType="
+ device.type + "&websocketToken=" + token; + device.type + "&websocketToken=" + token;
} }
} }
var events = [];
var viewModel = {};
viewModel.device = device;
viewModel.websocketEndpoint = websocketEndpoint;
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);
}
}
return {"device": device, "websocketEndpoint": websocketEndpoint, "attributes": attributes}; }
}
);
viewModel.attributes = attributes;
viewModel.events = events;
return viewModel;
} }

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

@ -434,8 +434,22 @@ $(document).ready(function () {
device, device,
function (data, textStatus, jqXHR) { function (data, textStatus, jqXHR) {
if (jqXHR.status == 200) { if (jqXHR.status == 200) {
$(successMsg).text("Device added."); $.ajax({
$(successMsgWrapper).removeClass("hidden"); 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) { 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> <br>
<button id="add-device-btn" class="wr-btn">Create Device</button> <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"> <div id="device-create-success-msg" class="alert hidden" role="alert">
<i class="icon fw fw-success"></i><span></span> <i class="icon fw fw-success"></i><span></span>
</div> </div>
@ -188,6 +188,20 @@
</button> </button>
</div> </div>
</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 --> <!-- /content -->
<div id="app-context" data-app-context="{{@app.context}}" class="hidden"></div> <div id="app-context" data-app-context="{{@app.context}}" class="hidden"></div>
</div> </div>

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

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

Loading…
Cancel
Save