Merge branch 'master' of https://github.com/wso2/carbon-device-mgt-plugins into entgra-master

# Conflicts:
#	components/analytics/iot-analytics/org.wso2.carbon.device.mgt.cdmf.analytics/pom.xml
#	components/analytics/iot-analytics/org.wso2.carbon.device.mgt.iot.analytics/pom.xml
#	components/analytics/iot-analytics/org.wso2.carbon.iot.device.statistics.dashboard/pom.xml
#	components/analytics/iot-analytics/org.wso2.carbon.iot.geo.dashboard/pom.xml
#	components/analytics/iot-analytics/pom.xml
#	components/analytics/pom.xml
#	components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.analytics/pom.xml
#	components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.api/pom.xml
#	components/device-types/androidsense-plugin/org.wso2.carbon.device.mgt.iot.androidsense.ui/pom.xml
#	components/device-types/androidsense-plugin/pom.xml
#	components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.analytics/pom.xml
#	components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.api/pom.xml
#	components/device-types/arduino-plugin/org.wso2.carbon.device.mgt.iot.arduino.ui/pom.xml
#	components/device-types/arduino-plugin/pom.xml
#	components/device-types/pom.xml
#	components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics/pom.xml
#	components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.api/pom.xml
#	components/device-types/raspberrypi-plugin/org.wso2.carbon.device.mgt.iot.raspberrypi.ui/pom.xml
#	components/device-types/raspberrypi-plugin/pom.xml
#	components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl/pom.xml
#	components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics/pom.xml
#	components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.api/pom.xml
#	components/device-types/virtual-fire-alarm-plugin/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui/pom.xml
#	components/device-types/virtual-fire-alarm-plugin/pom.xml
#	components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.osgiconnector/pom.xml
#	components/extensions/appm-connector/org.wso2.carbon.appmgt.mdm.restconnector/pom.xml
#	components/extensions/appm-connector/pom.xml
#	components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.extension/pom.xml
#	components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.http/pom.xml
#	components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.mqtt/pom.xml
#	components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.thrift/pom.xml
#	components/extensions/cdmf-transport-adapters/input/org.wso2.carbon.device.mgt.input.adapter.xmpp/pom.xml
#	components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.http/pom.xml
#	components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.mqtt/pom.xml
#	components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket.endpoint/pom.xml
#	components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.websocket/pom.xml
#	components/extensions/cdmf-transport-adapters/output/org.wso2.carbon.device.mgt.output.adapter.xmpp/pom.xml
#	components/extensions/cdmf-transport-adapters/pom.xml
#	components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.api/pom.xml
#	components/extensions/mb-extensions/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization/pom.xml
#	components/extensions/mb-extensions/pom.xml
#	components/extensions/pom.xml
#	components/extensions/pull-notification-listeners/org.wso2.carbon.device.mgt.mqtt.notification.listener/pom.xml
#	components/extensions/pull-notification-listeners/pom.xml
#	components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session.endpoint/pom.xml
#	components/extensions/remote-session-extension/org.wso2.carbon.device.mgt.extensions.remote.session/pom.xml
#	components/extensions/remote-session-extension/pom.xml
#	components/extensions/siddhi-extensions/org.wso2.extension.siddhi.device/pom.xml
#	components/extensions/siddhi-extensions/org.wso2.extension.siddhi.execution.json/pom.xml
#	components/extensions/siddhi-extensions/org.wso2.gpl.siddhi.extension.geo.script/pom.xml
#	components/extensions/siddhi-extensions/pom.xml
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/pom.xml
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceManagementProviderServiceMock.java
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.emulator/pom.xml
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/pom.xml
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.ui/src/main/resources/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android.type-view/public/assets/android-agent.apk
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.v09.api/pom.xml
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android.v09.api/src/test/java/org/wso2/carbon/mdm/services/android/mocks/DeviceManagementProviderServiceMock.java
#	components/mobile-plugins/android-plugin/org.wso2.carbon.device.mgt.mobile.android/pom.xml
#	components/mobile-plugins/android-plugin/pom.xml
#	components/mobile-plugins/pom.xml
#	components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.api/pom.xml
#	components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows.ui/pom.xml
#	components/mobile-plugins/windows-plugin/org.wso2.carbon.device.mgt.mobile.windows/pom.xml
#	components/mobile-plugins/windows-plugin/pom.xml
#	components/test-coverage/pom.xml
#	features/analytics-feature/org.wso2.carbon.device.mgt.cdmf.analytics.feature/pom.xml
#	features/analytics-feature/org.wso2.carbon.device.mgt.iot.analytics.feature/pom.xml
#	features/analytics-feature/org.wso2.carbon.iot.device.statistics.dashboard.feature/pom.xml
#	features/analytics-feature/org.wso2.carbon.iot.geo.dashboard.feature/pom.xml
#	features/analytics-feature/pom.xml
#	features/device-types-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.analytics.feature/pom.xml
#	features/device-types-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.backend.feature/pom.xml
#	features/device-types-feature/androidsense-plugin-feature/org.wso2.carbon.device.mgt.iot.androidsense.ui.feature/pom.xml
#	features/device-types-feature/androidsense-plugin-feature/pom.xml
#	features/device-types-feature/arduino-plugin-feature/org.wso2.carbon.device.mgt.iot.arduino.analytics.feature/pom.xml
#	features/device-types-feature/arduino-plugin-feature/org.wso2.carbon.device.mgt.iot.arduino.backend.feature/pom.xml
#	features/device-types-feature/arduino-plugin-feature/org.wso2.carbon.device.mgt.iot.arduino.ui.feature/pom.xml
#	features/device-types-feature/arduino-plugin-feature/pom.xml
#	features/device-types-feature/pom.xml
#	features/device-types-feature/raspberrypi-plugin-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.analytics.feature/pom.xml
#	features/device-types-feature/raspberrypi-plugin-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.backend.feature/pom.xml
#	features/device-types-feature/raspberrypi-plugin-feature/org.wso2.carbon.device.mgt.iot.raspberrypi.ui.feature/pom.xml
#	features/device-types-feature/raspberrypi-plugin-feature/pom.xml
#	features/device-types-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics.feature/pom.xml
#	features/device-types-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend.feature/pom.xml
#	features/device-types-feature/virtual-fire-alarm-plugin-feature/org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui.feature/pom.xml
#	features/device-types-feature/virtual-fire-alarm-plugin-feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.andes.extensions.device.mgt.api.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.andes.extensions.device.mgt.mqtt.authorization.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.appmgt.mdm.osgiconnector.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.appmgt.mdm.restconnector.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.device.mgt.adapter.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.device.mgt.notification.listener.feature/pom.xml
#	features/extensions-feature/org.wso2.carbon.device.mgt.remote.session.feature/pom.xml
#	features/extensions-feature/org.wso2.extension.siddhi.device.feature/pom.xml
#	features/extensions-feature/org.wso2.extension.siddhi.execution.json.feature/pom.xml
#	features/extensions-feature/org.wso2.gpl.siddhi.extension.geo.script.feature/pom.xml
#	features/extensions-feature/pom.xml
#	features/mobile-plugins-feature/android-plugin-feature/org.wso2.carbon.device.mgt.mobile.android.feature/pom.xml
#	features/mobile-plugins-feature/android-plugin-feature/pom.xml
#	features/mobile-plugins-feature/pom.xml
#	features/mobile-plugins-feature/windows-plugin-feature/org.wso2.carbon.device.mgt.mobile.windows.feature/pom.xml
#	features/mobile-plugins-feature/windows-plugin-feature/pom.xml
#	pom.xml
revert-dabc3590
Charitha Goonetilleke 6 years ago
commit 618cc1b854

@ -20,17 +20,15 @@ package org.wso2.carbon.device.mgt.output.adapter.websocket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.databridge.commons.Attribute;
import org.wso2.carbon.databridge.commons.Event;
import org.wso2.carbon.databridge.commons.StreamDefinition;
import org.wso2.carbon.device.mgt.output.adapter.websocket.constants.WebsocketConstants;
import org.wso2.carbon.device.mgt.output.adapter.websocket.internal.WebsocketEventAdaptorServiceDataHolder;
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketEventAdapterConstants;
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebSocketSessionRequest;
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebsocketEventAdapterConstants;
import org.wso2.carbon.event.output.adapter.core.EventAdapterUtil;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapter;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
@ -43,7 +41,6 @@ import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationExcep
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingDeque;
@ -68,9 +65,6 @@ public class WebsocketEventAdapter implements OutputEventAdapter {
private boolean doLogDroppedMessage;
private String streamId;
private List<Attribute> streamMetaAttributes;
private List<Attribute> streamCorrelationAttributes;
private List<Attribute> streamPayloadAttributes;
public WebsocketEventAdapter(OutputEventAdapterConfiguration eventAdapterConfiguration, Map<String,
String> globalProperties) {
@ -128,23 +122,15 @@ public class WebsocketEventAdapter implements OutputEventAdapter {
throw new OutputEventAdapterRuntimeException("UI event adapter needs a output stream id");
}
// fetch the "streamDefinition" corresponding to the "streamId" and then fetch the different attribute types
// of the streamDefinition corresponding to the event's streamId. They are required when validating values in
// the events against the streamDef attributes.
StreamDefinition streamDefinition = getStreamDefinition(streamId);
streamMetaAttributes = streamDefinition.getMetaData();
streamCorrelationAttributes = streamDefinition.getCorrelationData();
streamPayloadAttributes = streamDefinition.getPayloadData();
ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>> tenantSpecifcEventOutputAdapterMap =
ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>> tenantSpecificEventOutputAdapterMap =
WebsocketEventAdaptorServiceDataHolder.getTenantSpecificOutputEventStreamAdapterMap();
ConcurrentHashMap<String, String> streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId);
ConcurrentHashMap<String, String> streamSpecifAdapterMap = tenantSpecificEventOutputAdapterMap.get(tenantId);
if (streamSpecifAdapterMap == null) {
streamSpecifAdapterMap = new ConcurrentHashMap<>();
if (null != tenantSpecifcEventOutputAdapterMap.putIfAbsent(tenantId, streamSpecifAdapterMap)) {
streamSpecifAdapterMap = tenantSpecifcEventOutputAdapterMap.get(tenantId);
if (null != tenantSpecificEventOutputAdapterMap.putIfAbsent(tenantId, streamSpecifAdapterMap)) {
streamSpecifAdapterMap = tenantSpecificEventOutputAdapterMap.get(tenantId);
}
}
@ -200,61 +186,10 @@ public class WebsocketEventAdapter implements OutputEventAdapter {
@Override
public void publish(Object message, Map<String, String> dynamicProperties) {
String eventString;
if (streamSpecificEvents.size() == queueSize) {
streamSpecificEvents.removeFirst();
}
if (message instanceof Event) {
Event event = (Event) message;
StringBuilder eventBuilder = new StringBuilder("[");
eventBuilder.append(event.getTimeStamp());
if (event.getMetaData() != null) {
eventBuilder.append(",");
Object[] metaData = event.getMetaData();
for (int i = 0; i < metaData.length; i++) {
eventBuilder.append("\"");
eventBuilder.append(metaData[i]);
eventBuilder.append("\"");
if (i != (metaData.length - 1)) {
eventBuilder.append(",");
}
}
}
if (event.getCorrelationData() != null) {
Object[] correlationData = event.getCorrelationData();
eventBuilder.append(",");
for (int i = 0; i < correlationData.length; i++) {
eventBuilder.append("\"");
eventBuilder.append(correlationData[i]);
eventBuilder.append("\"");
if (i != (correlationData.length - 1)) {
eventBuilder.append(",");
}
}
}
if (event.getPayloadData() != null) {
Object[] payloadData = event.getPayloadData();
eventBuilder.append(",");
for (int i = 0; i < payloadData.length; i++) {
eventBuilder.append("\"");
eventBuilder.append(payloadData[i]);
eventBuilder.append("\"");
if (i != (payloadData.length - 1)) {
eventBuilder.append(",");
}
}
}
eventBuilder.append("]");
eventString = eventBuilder.toString();
} else {
eventString = message.toString();
}
String eventString = message.toString();
Object[] eventValues = new Object[WebsocketEventAdapterConstants.INDEX_TWO];
eventValues[WebsocketEventAdapterConstants.INDEX_ZERO] = eventString;
@ -262,7 +197,7 @@ public class WebsocketEventAdapter implements OutputEventAdapter {
streamSpecificEvents.add(eventValues);
// fetch all valid sessions checked against any queryParameters provided when subscribing.
CopyOnWriteArrayList<WebSocketSessionRequest> validSessions = getValidSessions(message);
CopyOnWriteArrayList<WebSocketSessionRequest> validSessions = getValidSessions(eventString);
try {
executorService.execute(new WebSocketSender(validSessions, eventString));
@ -332,132 +267,37 @@ public class WebsocketEventAdapter implements OutputEventAdapter {
* Fetches all valid web-socket sessions from the entire pool of subscribed sessions. The validity is checked
* against any queryString provided when subscribing to the web-socket endpoint.
*
* @param event the current event received and that which needs to be published to subscribed sessions.
* @param eventString the current event received and that which needs to be published to subscribed sessions.
* @return a list of all validated web-socket sessions against the queryString values.
*/
private CopyOnWriteArrayList<WebSocketSessionRequest> getValidSessions(Object event) {
private CopyOnWriteArrayList<WebSocketSessionRequest> getValidSessions(String eventString) {
CopyOnWriteArrayList<WebSocketSessionRequest> validSessions = new CopyOnWriteArrayList<>();
WebsocketOutputCallbackControllerServiceImpl websocketOutputCallbackControllerServiceImpl =
WebsocketEventAdaptorServiceDataHolder.getUIOutputCallbackRegisterServiceImpl();
// get all subscribed web-socket sessions.
CopyOnWriteArrayList<WebSocketSessionRequest> webSocketSessionUtils =
CopyOnWriteArrayList<WebSocketSessionRequest> webSocketSessionRequests =
websocketOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId);
if (webSocketSessionUtils != null) {
for (WebSocketSessionRequest webSocketSessionUtil : webSocketSessionUtils) {
boolean isValidSession;
if (event instanceof Event) {
isValidSession = validateEventAgainstSessionFilters((Event) event, webSocketSessionUtil);
} else {
isValidSession = validateJsonMessageAgainstEventFilters(event.toString(), webSocketSessionUtil);
}
if (isValidSession) {
validSessions.add(webSocketSessionUtil);
if (webSocketSessionRequests != null) {
for (WebSocketSessionRequest webSocketSessionRequest : webSocketSessionRequests) {
if (validateJsonMessageAgainstEventFilters(eventString, webSocketSessionRequest)) {
validSessions.add(webSocketSessionRequest);
}
}
}
return validSessions;
}
/**
* Processes the given session's validity to receive the current "event" against any queryParams that was used at
* the time when the web-socket-session is subscribed. This method can be extended to validate the event against
* any additional attribute of the given session too.
*
* @param event the current event received and that which needs to be published to subscribed
* sessions.
* @param webSocketSessionUtil the session which needs validated for its authenticity to receive this event.
* @return "true" if the session is valid to receive the event else "false".
*/
private boolean validateEventAgainstSessionFilters(Event event, WebSocketSessionRequest webSocketSessionUtil) {
// fetch the queryString Key:Value pair map of the given session.
Map<String, String> queryParamValuePairs = webSocketSessionUtil.getQueryParamValuePairs();
if (queryParamValuePairs != null && !queryParamValuePairs.isEmpty()) {
// fetch the different attribute values received as part of the current event.
Object[] eventMetaData = event.getMetaData();
Object[] eventCorrelationData = event.getCorrelationData();
Object[] eventPayloadData = event.getPayloadData();
if (streamMetaAttributes != null) {
for (int i = 0; i < streamMetaAttributes.size(); i++) {
String attributeName = streamMetaAttributes.get(i).getName();
String queryValue = queryParamValuePairs.get(attributeName);
if (queryValue != null &&
(eventMetaData == null || !eventMetaData[i].toString().equals(queryValue))) {
return false;
}
}
}
if (streamCorrelationAttributes != null) {
for (int i = 0; i < streamCorrelationAttributes.size(); i++) {
String attributeName = streamCorrelationAttributes.get(i).getName();
String queryValue = queryParamValuePairs.get(attributeName);
if (queryValue != null &&
(eventCorrelationData == null || !eventCorrelationData[i].toString().equals(queryValue))) {
return false;
}
}
}
if (streamPayloadAttributes != null) {
for (int i = 0; i < streamPayloadAttributes.size(); i++) {
String attributeName = streamPayloadAttributes.get(i).getName();
String queryValue = queryParamValuePairs.get(attributeName);
if (queryValue != null && (eventPayloadData == null || !eventPayloadData[i].toString().equals(
queryValue))) {
return false;
}
}
}
}
return true;
}
private boolean validateJsonMessageAgainstEventFilters(String jsonMessage, WebSocketSessionRequest webSocketSessionRequest) {
private boolean validateJsonMessageAgainstEventFilters(String eventString, WebSocketSessionRequest webSocketSessionRequest) {
Map<String, String> queryParamValuePairs = webSocketSessionRequest.getQueryParamValuePairs();
if (queryParamValuePairs != null && !queryParamValuePairs.isEmpty()) {
// fetch the different attribute values received as part of the current event.
Set<String> queryParams = queryParamValuePairs.keySet();
for (String aQueryParam : queryParams) {
try {
String queryValue = queryParamValuePairs.get(aQueryParam);
if (queryValue != null && !queryValue.trim().isEmpty()) {
JSONObject jsonObject = new JSONObject(jsonMessage);
JSONObject event = jsonObject.getJSONObject(WebsocketConstants.EVENT);
JSONObject data;
if (!event.isNull(WebsocketConstants.META_DATA)) {
data = event.getJSONObject(WebsocketConstants.META_DATA);
if (!data.isNull(aQueryParam)) {
String eventValue = data.get(aQueryParam).toString();
if (eventValue == null || !eventValue.equalsIgnoreCase(queryValue)) {
String deviceId = queryParamValuePairs.get(WebsocketConstants.DEVICE_ID);
String deviceType = queryParamValuePairs.get(WebsocketConstants.DEVICE_TYPE);
JSONObject eventObj = new JSONObject(eventString);
if (deviceId != null && !deviceId.equals(eventObj.getString(WebsocketConstants.DEVICE_ID))) {
return false;
}
}
}
if (!event.isNull(WebsocketConstants.PAYLOAD_DATA)) {
data = event.getJSONObject(WebsocketConstants.PAYLOAD_DATA);
if (!data.isNull(aQueryParam)) {
String eventValue = data.get(aQueryParam).toString();
if (eventValue == null || !eventValue.equalsIgnoreCase(queryValue)) {
if (deviceType != null && !deviceType.equals(eventObj.getString(WebsocketConstants.DEVICE_TYPE))) {
return false;
}
}
}
}
} catch (JSONException e) {
//do nothing - This exception is thrown when the event does not have query parameter.
}
}
}
return true;
}

@ -107,8 +107,8 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
auth.setPreemptiveAuthentication(true);
String username = tokenValidationProperties.get(WebsocketConstants.USERNAME);
String password = tokenValidationProperties.get(WebsocketConstants.PASSWORD);
auth.setPassword(username);
auth.setUsername(password);
auth.setUsername(username);
auth.setPassword(password);
Options options = client.getOptions();
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
@ -116,8 +116,12 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
if (hostURL.getProtocol().equals("https")) {
// set up ssl factory since axis2 https transport is used.
EasySSLProtocolSocketFactory sslProtocolSocketFactory = createProtocolSocketFactory();
Protocol authhttps = new Protocol(hostURL.getProtocol()
, (ProtocolSocketFactory) sslProtocolSocketFactory, hostURL.getPort());
int port = hostURL.getPort();
if (port == -1) {
port = 443;
}
Protocol authhttps = new Protocol(hostURL.getProtocol(),
(ProtocolSocketFactory) sslProtocolSocketFactory, port);
Protocol.registerProtocol(hostURL.getProtocol(), authhttps);
options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, authhttps);
}

@ -21,8 +21,6 @@ import feign.Client;
import feign.Feign;
import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.Response;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract;
@ -37,6 +35,7 @@ import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.
.DeviceAccessAuthorizationAdminService;
import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.DeviceAuthorizationResult;
import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.dto.DeviceIdentifier;
import org.wso2.carbon.device.mgt.output.adapter.websocket.constants.WebsocketConstants;
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.PropertyUtils;
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.WebSocketSessionRequest;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
@ -49,7 +48,6 @@ import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@ -61,8 +59,6 @@ public class DeviceAuthorizer implements Authorizer {
private static DeviceAccessAuthorizationAdminService deviceAccessAuthorizationAdminService;
private static final String CDMF_SERVER_BASE_CONTEXT = "/api/device-mgt/v1.0";
private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl";
private static final String DEVICE_ID = "deviceId";
private static final String DEVICE_TYPE = "deviceType";
private static Log log = LogFactory.getLog(DeviceAuthorizer.class);
public DeviceAuthorizer() {
}
@ -84,8 +80,8 @@ public class DeviceAuthorizer implements Authorizer {
public synchronized boolean isAuthorized(AuthenticationInfo authenticationInfo, Session session, String stream) {
WebSocketSessionRequest webSocketSessionRequest = new WebSocketSessionRequest(session);
Map<String, String> queryParams = webSocketSessionRequest.getQueryParamValuePairs();
String deviceId = queryParams.get(DEVICE_ID);
String deviceType = queryParams.get(DEVICE_TYPE);
String deviceId = queryParams.get(WebsocketConstants.DEVICE_ID);
String deviceType = queryParams.get(WebsocketConstants.DEVICE_TYPE);
if (deviceId != null && !deviceId.isEmpty() && deviceType != null && !deviceType.isEmpty()) {

@ -18,15 +18,14 @@ import feign.Client;
import feign.Feign;
import feign.FeignException;
import feign.Logger;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.Response;
import feign.auth.BasicAuthRequestInterceptor;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import feign.jaxrs.JAXRSContract;
import feign.slf4j.Slf4jLogger;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
@ -38,12 +37,24 @@ import org.wso2.carbon.device.mgt.output.adapter.websocket.authorization.client.
import org.wso2.carbon.device.mgt.output.adapter.websocket.util.PropertyUtils;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import javax.net.ssl.*;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.Map;
@ -68,24 +79,35 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
private static final String CONNECTION_USERNAME = "username";
private static final String CONNECTION_PASSWORD = "password";
private static final String TOKEN_ENDPOINT = "tokenUrl";
private static final String TOKEN_REFRESH_TIME_OFFSET = "tokenRefreshTimeOffset";
private static final String TOKEN_SCOPES = "scopes";
private static final String DEVICE_MGT_SERVER_URL = "deviceMgtServerUrl";
private static final String TOKEN_ENDPOINT_CONTEXT = "tokenUrl";
private static String username;
private static String password;
private static String tokenEndpoint;
private static String deviceMgtServerUrl;
private static String scopes;
private static Map<String, String> globalProperties;
private static String clientHash = "";
/**
* Creates an interceptor that authenticates all requests.
*/
public OAuthRequestInterceptor(Map<String, String> globalProperties) {
this.globalProperties = globalProperties;
try {
InetAddress inetAddress = InetAddress.getLocalHost();
String ip = inetAddress.getHostAddress();
if (ip != null && ip.equals("127.0.0.1")) {
clientHash = ip.replace(".", "");
} else {
clientHash = RandomStringUtils.random(8, true, true);
}
} catch (UnknownHostException e) {
log.warn("Error occurred while generating unique hash for node.");
clientHash = RandomStringUtils.random(8, true, true);
}
if (log.isDebugEnabled()) {
log.debug("Client hash: " + clientHash);
}
try {
deviceMgtServerUrl = getDeviceMgtServerUrl(globalProperties);
refreshTimeOffset = getRefreshTimeOffset(globalProperties) * 1000;
@ -108,7 +130,7 @@ public class OAuthRequestInterceptor implements RequestInterceptor {
if (tokenInfo == null) {
if (apiApplicationKey == null) {
ApiRegistrationProfile apiRegistrationProfile = new ApiRegistrationProfile();
apiRegistrationProfile.setApplicationName(APPLICATION_NAME);
apiRegistrationProfile.setApplicationName(APPLICATION_NAME + "-" + clientHash);
apiRegistrationProfile.setIsAllowedToAllDomains(false);
apiRegistrationProfile.setIsMappingAnExistingOAuthApp(false);
apiRegistrationProfile.setTags(DEVICE_MANAGEMENT_SERVICE_TAG);

@ -33,8 +33,6 @@ public class WebsocketConstants {
public static final String TOKEN_VALIDATION_CONTEX = "/services/OAuth2TokenValidationService";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String TOKEN_PARAM = "token";
public static final String META_DATA = "metaData";
public static final String PAYLOAD_DATA = "payloadData";
public static final String EVENT = "event";
public static final String DEVICE_ID = "deviceId";
public static final String DEVICE_TYPE = "deviceType";
}

@ -107,8 +107,8 @@ public class OAuthTokenValidatorStubFactory extends BasePoolableObjectFactory {
auth.setPreemptiveAuthentication(true);
String username = tokenValidationProperties.get(RemoteSessionConstants.USERNAME);
String password = tokenValidationProperties.get(RemoteSessionConstants.PASSWORD);
auth.setPassword(username);
auth.setUsername(password);
auth.setUsername(username);
auth.setPassword(password);
Options options = client.getOptions();
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, Constants.VALUE_TRUE);
@ -116,8 +116,12 @@ public class OAuthTokenValidatorStubFactory extends BasePoolableObjectFactory {
if (hostURL.getProtocol().equals("https")) {
// set up ssl factory since axis2 https notification is used.
EasySSLProtocolSocketFactory sslProtocolSocketFactory = createProtocolSocketFactory();
Protocol authhttps = new Protocol(hostURL.getProtocol()
, (ProtocolSocketFactory) sslProtocolSocketFactory, hostURL.getPort());
int port = hostURL.getPort();
if (port == -1) {
port = 443;
}
Protocol authhttps = new Protocol(hostURL.getProtocol(),
(ProtocolSocketFactory) sslProtocolSocketFactory, port);
Protocol.registerProtocol(hostURL.getProtocol(), authhttps);
options.setProperty(HTTPConstants.CUSTOM_PROTOCOL_HANDLER, authhttps);
}

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
@ -503,6 +504,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
return 0;
}
@Override
public OperationMonitoringTaskConfig getDeviceMonitoringConfig(String s) {
return null;
}
@Override
public boolean isDeviceMonitoringEnabled(String s) {
return false;

@ -16,7 +16,9 @@
data-type="{{device.type}}"
data-ownership="{{device.ownership}}"
data-owner="{{device.owner}}"
data-status="{{device.status}}">
data-status="{{device.status}}"
data-deviceinfoservice="{{device.deviceInfoServiceAPI}}"
data-devicelocationservice="{{device.deviceLocationServiceAPI}}">
{{device.owner}}'s {{device.name}}
<a id="device-info-tooltip" href="#" data-toggle="tooltip" title="Device Identifier: {{device.deviceIdentifier}}
Firmware Build Date: {{device.osBuildDate}}

@ -24,19 +24,28 @@ function onRequest(context) {
var deviceViewData = {};
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var carbonServer = require("carbon").server;
var constants = require("/app/modules/constants.js")
var constants = require("/app/modules/constants.js");
if (deviceType && deviceId) {
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var response = deviceModule.viewDevice(deviceType, deviceId, owner);
if (response["status"] == "success") {
if (response["status"] === "success") {
deviceViewData["deviceFound"] = true;
deviceViewData["isAuthorized"] = true;
var filteredDeviceData = response["content"];
// creating deviceView information model from filtered device data
// creating deviceView information model from filtered device data
var viewModel = {};
var deviceInfoServiceAPI = devicemgtProps["deviceInfoServiceAPI"];
var deviceLocationServiceAPI = devicemgtProps["deviceLocationServiceAPI"];
if (deviceInfoServiceAPI){
viewModel["deviceInfoServiceAPI"] = deviceInfoServiceAPI.replace("%device-type%", deviceType)
}
if (deviceLocationServiceAPI){
viewModel['deviceLocationServiceAPI'] = deviceLocationServiceAPI.replace("%device-type%", deviceType)
}
if (filteredDeviceData["type"]) {
viewModel["type"] = filteredDeviceData["type"];
viewModel.isNotWindows = true;

@ -26,19 +26,13 @@ var InitiateViewOption = null;
var devStatus = deviceId.data("status");
var payload = [deviceIdentifier];
var operationTable;
var serviceUrl;
var serviceUrlLocal = "/api/device-mgt/android/v1.0/admin/devices/location";
if (deviceType == "ios") {
serviceUrl = "/ios/operation/deviceinfo";
} else if (deviceType == "android") {
//var serviceUrl = "/mdm-android-agent/operation/device-info";
serviceUrl = "/api/device-mgt/android/v1.0/admin/devices/info";
serviceUrlLocal = "/api/device-mgt/android/v1.0/admin/devices/location";
}
if (serviceUrl && ("REMOVED" !== devStatus)) {
if ("REMOVED" !== devStatus) {
var deviceInfoServiceAPI = deviceId.data("deviceinfoservice");
var deviceLocationServiceAPI = deviceId.data("devicelocationservice");
if (deviceInfoServiceAPI) {
invokerUtil.post(
serviceUrl,
deviceInfoServiceAPI,
payload,
// success-callback
function () {
@ -51,8 +45,10 @@ var InitiateViewOption = null;
$(".panel-body").append(defaultInnerHTML);
}
);
}
if (deviceLocationServiceAPI) {
invokerUtil.post(
serviceUrlLocal,
deviceLocationServiceAPI,
payload,
// success-callback
function () {
@ -65,7 +61,7 @@ var InitiateViewOption = null;
$(".panel-body").append(defaultInnerHTML);
}
);
}
}
$(".media.tab-responsive [data-toggle=tab]").on("shown.bs.tab", function (e) {

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.MonitoringOperation;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.PaginationRequest;
import org.wso2.carbon.device.mgt.common.PaginationResult;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
@ -503,6 +504,11 @@ public class DeviceManagementProviderServiceMock implements DeviceManagementProv
return 0;
}
@Override
public OperationMonitoringTaskConfig getDeviceMonitoringConfig(String s) {
return null;
}
@Override
public boolean isDeviceMonitoringEnabled(String s) {
return false;

@ -15,7 +15,9 @@
data-type="{{device.type}}"
data-ownership="{{device.ownership}}"
data-owner="{{device.owner}}"
data-status="{{device.status}}">
data-status="{{device.status}}"
data-deviceinfoservice="{{device.deviceInfoServiceAPI}}"
data-devicelocationservice="{{device.deviceLocationServiceAPI}}">
{{device.owner}}'s {{device.name}}
</h1>
<a id="device-info-tooltip" href="#" data-toggle="tooltip" title="Device Identifier: {{device.deviceIdentifier}}

@ -26,7 +26,7 @@ function onRequest(context) {
if (deviceType && deviceId) {
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var response = deviceModule.viewDevice(deviceType, deviceId, owner);
if (response["status"] == "success") {
if (response["status"] === "success") {
deviceViewData["deviceFound"] = true;
deviceViewData["isAuthorized"] = true;
@ -34,6 +34,15 @@ function onRequest(context) {
// creating deviceView information model from filtered device data
var viewModel = {};
var deviceInfoServiceAPI = devicemgtProps["deviceInfoServiceAPI"];
var deviceLocationServiceAPI = devicemgtProps["deviceLocationServiceAPI"];
if (deviceInfoServiceAPI){
viewModel["deviceInfoServiceAPI"] = deviceInfoServiceAPI.replace("%device-type%", deviceType)
}
if (deviceLocationServiceAPI){
viewModel['deviceLocationServiceAPI'] = deviceLocationServiceAPI.replace("%device-type%", deviceType)
}
if (filteredDeviceData["type"]) {
viewModel["type"] = filteredDeviceData["type"];
viewModel.isNotWindows = true;

@ -26,18 +26,29 @@ var InitiateViewOption = null;
var devStatus = deviceId.data("status");
var payload = [deviceIdentifier];
var operationTable;
var serviceUrl;
if (deviceType == "ios") {
serviceUrl = "/ios/operation/deviceinfo";
} else if (deviceType == "android") {
//var serviceUrl = "/mdm-android-agent/operation/device-info";
serviceUrl = "/api/device-mgt/android/v1.0/admin/devices/info";
if ("REMOVED" !== devStatus) {
var deviceInfoServiceAPI = deviceId.data("deviceinfoservice");
var deviceLocationServiceAPI = deviceId.data("devicelocationservice");
if (deviceInfoServiceAPI) {
invokerUtil.post(
deviceInfoServiceAPI,
payload,
// success-callback
function () {
$(".panel-body").show();
},
// error-callback
function () {
var defaultInnerHTML =
"<br><p class='fw-warning'>Device data may not have been updated. Please refresh to try again.<p>";
$(".panel-body").append(defaultInnerHTML);
}
if (serviceUrl && ("REMOVED" !== devStatus)) {
);
}
if (deviceLocationServiceAPI) {
invokerUtil.post(
serviceUrl,
deviceLocationServiceAPI,
payload,
// success-callback
function () {
@ -51,6 +62,7 @@ var InitiateViewOption = null;
}
);
}
}
$(".media.tab-responsive [data-toggle=tab]").on("shown.bs.tab", function (e) {

@ -52,9 +52,9 @@
<SharedWithAllTenants>true</SharedWithAllTenants>
</ProvisioningConfig>
<!--
isScheduled element used to enable scheduler task to send push notification.
Task will send push notification as batches. So this will reduce sudden request burst when many devices try to
access server after receiving push notification.
isScheduled element used to enable scheduler task to send push notification as batches.
Batch size and scheduler interval can be configured via cdm-config.xml. So this will reduce sudden request
burst when many devices try to access server after receiving push notification.
-->
<!--Configuration for enable firebase push notifications-->
<PushNotificationProviderConfig type="FCM" isScheduled="false">

Loading…
Cancel
Save