mharindu 9 years ago
commit a254d9efc4

@ -20,6 +20,6 @@
<eventPublisher name="android_sense_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher"> <eventPublisher name="android_sense_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.android.sense" version="1.0.0"/> <from streamName="org.wso2.iot.android.sense" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/> <mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/> <to eventAdapterType="secured-ui"/>
</eventPublisher> </eventPublisher>

@ -27,7 +27,7 @@ function onRequest(context) {
"backendApiUri": devicemgtProps["httpsURL"] + "/android_sense/stats/" "backendApiUri": devicemgtProps["httpsURL"] + "/android_sense/stats/"
}; };
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return { return {

@ -25,7 +25,7 @@ function onRequest(context) {
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return { return {

@ -139,9 +139,7 @@ public class ArduinoServiceImpl implements ArduinoService {
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build(); return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build();
} catch (NoSuchElementException ex) { } catch (NoSuchElementException ex) {
result = "There are no more controls for device " + deviceId + " of owner " + owner; result = "There are no more controls for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) { log.error(result, ex);
log.debug(result);
}
return Response.status(Response.Status.NO_CONTENT.getStatusCode()).entity(result).build(); return Response.status(Response.Status.NO_CONTENT.getStatusCode()).entity(result).build();
} }
} }

@ -29,7 +29,7 @@ function onRequest(context) {
"backendApiUri": devicemgtProps["httpsURL"] + "/arduino/device/stats/" "backendApiUri": devicemgtProps["httpsURL"] + "/arduino/device/stats/"
}; };
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return { return {

@ -25,7 +25,7 @@ function onRequest(context) {
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/arduino/", "autoCompleteParams" : autoCompleteParams}; return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/arduino/", "autoCompleteParams" : autoCompleteParams};

@ -20,6 +20,6 @@
<eventPublisher name="temperature_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher"> <eventPublisher name="temperature_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.temperature" version="1.0.0"/> <from streamName="org.wso2.iot.devices.temperature" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/> <mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/> <to eventAdapterType="secured-ui"/>
</eventPublisher> </eventPublisher>

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.input.adapter.extension; package org.wso2.carbon.device.mgt.iot.input.adapter.extension;
import java.util.Map; import java.util.Map;

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.input.adapter.extension; package org.wso2.carbon.device.mgt.iot.input.adapter.extension;
import java.util.Map; import java.util.Map;

@ -1,3 +1,21 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.input.adapter.extension; package org.wso2.carbon.device.mgt.iot.input.adapter.extension;
import java.util.Map; import java.util.Map;

@ -21,21 +21,17 @@ package org.wso2.carbon.device.mgt.iot.input.adapter.http.oauth.exception;
* This Exception will be thrown, when there any interference with token validation flow. * This Exception will be thrown, when there any interference with token validation flow.
*/ */
public class OAuthTokenValidationException extends Exception { public class OAuthTokenValidationException extends Exception {
private String errMessage;
public OAuthTokenValidationException(String msg, Exception nestedEx) { public OAuthTokenValidationException(String msg, Exception nestedEx) {
super(msg, nestedEx); super(msg, nestedEx);
setErrorMessage(msg);
} }
public OAuthTokenValidationException(String message, Throwable cause) { public OAuthTokenValidationException(String message, Throwable cause) {
super(message, cause); super(message, cause);
setErrorMessage(message);
} }
public OAuthTokenValidationException(String msg) { public OAuthTokenValidationException(String msg) {
super(msg); super(msg);
setErrorMessage(msg);
} }
public OAuthTokenValidationException() { public OAuthTokenValidationException() {
@ -45,12 +41,4 @@ public class OAuthTokenValidationException extends Exception {
public OAuthTokenValidationException(Throwable cause) { public OAuthTokenValidationException(Throwable cause) {
super(cause); super(cause);
} }
public String getErrorMessage() {
return errMessage;
}
public void setErrorMessage(String errMessage) {
this.errMessage = errMessage;
}
} }

@ -42,7 +42,7 @@ public class PropertyUtils {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance(); ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET)); String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(CARBON_CONFIG_PORT_OFFSET));
try { try {
if ((portOffset != null)) { if (portOffset != null) {
return Integer.parseInt(portOffset.trim()); return Integer.parseInt(portOffset.trim());
} else { } else {
return CARBON_DEFAULT_PORT_OFFSET; return CARBON_DEFAULT_PORT_OFFSET;

@ -55,21 +55,6 @@
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>

@ -16,13 +16,14 @@
* under the License. * under the License.
*/ */
import oauth.OAuthTokenValdiator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.Authenticator;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.Authorizer;
import util.ServiceHolder; import util.ServiceHolder;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import util.AuthenticationInfo;
import javax.websocket.CloseReason; import javax.websocket.CloseReason;
import javax.websocket.OnClose; import javax.websocket.OnClose;
@ -56,22 +57,28 @@ public class SuperTenantSubscriptionEndpoint extends SubscriptionEndpoint {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName); log.debug("WebSocket opened, for Session id: " + session.getId() + ", for the Stream:" + streamName);
} }
AuthenticationInfo authenticationInfo = OAuthTokenValdiator.getInstance().validateToken(session); Authenticator authenticator = ServiceHolder.getWebsocketValidationService().getAuthenticator();
//TODO Authorization AuthenticationInfo authenticationInfo = authenticator.isAutenticated(session);
if (authenticationInfo != null && authenticationInfo.isAuthenticated()) { if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
try { Authorizer authorizer = ServiceHolder.getWebsocketValidationService().getAuthorizer();
PrivilegedCarbonContext.startTenantFlow(); boolean isAuthorized = authorizer.isAuthorized(authenticationInfo, session, streamName);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(MultitenantConstants.SUPER_TENANT_ID); if (isAuthorized) {
ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName, try {
version, session); PrivilegedCarbonContext.startTenantFlow();
} finally { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(
PrivilegedCarbonContext.endTenantFlow(); MultitenantConstants.SUPER_TENANT_ID);
ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName,
version,
session);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} }
} else { } else {
try { try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access")); session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
} catch (IOException e) { } catch (IOException e) {
log.error("Failed to disconnect the unauthorized client."); log.error("Failed to disconnect the unauthorized client.", e);
} }
} }
} }

@ -16,12 +16,13 @@
* under the License. * under the License.
*/ */
import oauth.OAuthTokenValdiator;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.Authenticator;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.Authorizer;
import util.ServiceHolder; import util.ServiceHolder;
import util.AuthenticationInfo;
import javax.websocket.CloseReason; import javax.websocket.CloseReason;
import javax.websocket.OnClose; import javax.websocket.OnClose;
@ -56,22 +57,27 @@ public class TenantSubscriptionEndpoint extends SubscriptionEndpoint {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("WebSocket opened, for Session id: "+session.getId()+", for the Stream:"+streamName); log.debug("WebSocket opened, for Session id: "+session.getId()+", for the Stream:"+streamName);
} }
AuthenticationInfo authenticationInfo = OAuthTokenValdiator.getInstance().validateToken(session); Authenticator authenticator = ServiceHolder.getWebsocketValidationService().getAuthenticator();
//TODO Authorization AuthenticationInfo authenticationInfo = authenticator.isAutenticated(session);
if (authenticationInfo != null && authenticationInfo.isAuthenticated()) { if (authenticationInfo != null && authenticationInfo.isAuthenticated()) {
try { Authorizer authorizer = ServiceHolder.getWebsocketValidationService().getAuthorizer();
PrivilegedCarbonContext.startTenantFlow(); boolean isAuthorized = authorizer.isAuthorized(authenticationInfo, session, streamName);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tdomain, true); if (isAuthorized) {
ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName, try {
version, session); PrivilegedCarbonContext.startTenantFlow();
} finally { PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tdomain, true);
PrivilegedCarbonContext.endTenantFlow(); ServiceHolder.getInstance().getUiOutputCallbackControllerService().subscribeWebsocket(streamName,
version,
session);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
} }
} else { } else {
try { try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access")); session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT, "Unauthorized Access"));
} catch (IOException e) { } catch (IOException e) {
log.error("Failed to disconnect the unauthorized client."); log.error("Failed to disconnect the unauthorized client.", e);
} }
} }
} }
@ -86,7 +92,8 @@ public class TenantSubscriptionEndpoint extends SubscriptionEndpoint {
@OnMessage @OnMessage
public void onMessage (Session session, String message, @PathParam("streamname") String streamName, @PathParam("tdomain") String tdomain) { public void onMessage (Session session, String message, @PathParam("streamname") String streamName, @PathParam("tdomain") String tdomain) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Received and dropped message from client. Message: " + message+", for Session id: "+session.getId()+", for tenant domain"+tdomain+", for the Adaptor:"+streamName); log.debug("Received and dropped message from client. Message: " + message + ", for Session id: " +
session.getId() + ", for tenant domain" + tdomain + ", for the Adaptor:" + streamName);
} }
} }

@ -1,22 +1,26 @@
package util; package util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerService; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerService;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.service.WebsocketValidationService;
public class ServiceHolder { public class ServiceHolder {
private static ServiceHolder instance; private static ServiceHolder instance;
private UIOutputCallbackControllerService uiOutputCallbackControllerService; private UIOutputCallbackControllerService uiOutputCallbackControllerService;
private static final Log log = LogFactory.getLog(ServiceHolder.class);
private ServiceHolder(){ private ServiceHolder(){
uiOutputCallbackControllerService = (UIOutputCallbackControllerService) PrivilegedCarbonContext uiOutputCallbackControllerService = (UIOutputCallbackControllerService) PrivilegedCarbonContext
.getThreadLocalCarbonContext().getOSGiService(UIOutputCallbackControllerService.class, null); .getThreadLocalCarbonContext().getOSGiService(UIOutputCallbackControllerService.class, null);
} }
public synchronized static ServiceHolder getInstance(){ public synchronized static ServiceHolder getInstance() {
if (instance==null){ if (instance == null) {
instance= new ServiceHolder(); instance = new ServiceHolder();
} }
return instance; return instance;
} }
@ -24,4 +28,16 @@ public class ServiceHolder {
public UIOutputCallbackControllerService getUiOutputCallbackControllerService() { public UIOutputCallbackControllerService getUiOutputCallbackControllerService() {
return uiOutputCallbackControllerService; return uiOutputCallbackControllerService;
} }
public static WebsocketValidationService getWebsocketValidationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
WebsocketValidationService deviceManagementProviderService =
(WebsocketValidationService) ctx.getOSGiService(WebsocketValidationService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Websocket Validation service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
} }

@ -1,34 +1,31 @@
/* /*
* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* * *
* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * WSO2 Inc. licenses this file to you under the Apache License,
* * * Version 2.0 (the "License"); you may not use this file except
* * WSO2 Inc. licenses this file to you under the Apache License, * in compliance with the License.
* * Version 2.0 (the "License"); you may not use this file except * You may obtain a copy of the License at
* * in compliance with the License. *
* * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0
* * *
* * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing,
* * * software distributed under the License is distributed on an
* * Unless required by applicable law or agreed to in writing, * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* * software distributed under the License is distributed on an * KIND, either express or implied. See the License for the
* * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * specific language governing permissions and limitations
* * KIND, either express or implied. See the License for the * under the License.
* * specific language governing permissions and limitations */
* * under the License.
* *
*
*/
package util; package util;
/** /**
* This class contains the constants related to ui client. * This class contains the constants related to ui client.
*/ */
public class UIConstants { public final class UIConstants {
private UIConstants() { private UIConstants() {
} }
public static final String ADAPTER_UI_COLON = ":"; public static final String ADAPTER_UI_COLON = ":";
public static final String MAXIMUM_TOTAL_HTTP_CONNECTION = "maximumTotalHttpConnection"; public static final String MAXIMUM_TOTAL_HTTP_CONNECTION = "maximumTotalHttpConnection";
public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost"; public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost";

@ -63,6 +63,18 @@
<groupId>org.wso2.carbon.analytics-common</groupId> <groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.stream.core</artifactId> <artifactId>org.wso2.carbon.event.stream.core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.oauth.stub</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -123,8 +135,17 @@
org.wso2.carbon.databridge.commons, org.wso2.carbon.databridge.commons,
org.wso2.carbon.event.stream.core, org.wso2.carbon.event.stream.core,
org.wso2.carbon.event.stream.core.exception, org.wso2.carbon.event.stream.core.exception,
org.wso2.carbon.utils org.wso2.carbon.utils,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers; version=0.0.0,
org.w3c.dom,
org.wso2.carbon.identity.oauth2.stub,
org.wso2.carbon.identity.oauth2.stub.dto,
org.wso2.carbon.user.api,
org.wso2.carbon.utils.multitenancy
</Import-Package> </Import-Package>
<DynamicImport-Package>*</DynamicImport-Package>
</instructions> </instructions>
</configuration> </configuration>
</plugin> </plugin>

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
@ -34,7 +33,7 @@ import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException; import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterRuntimeException;
import org.wso2.carbon.event.output.adapter.core.exception.TestConnectionNotSupportedException; import org.wso2.carbon.event.output.adapter.core.exception.TestConnectionNotSupportedException;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebSocketSessionUtil; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebSocketSessionRequest;
import org.wso2.carbon.event.stream.core.EventStreamService; import org.wso2.carbon.event.stream.core.EventStreamService;
import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException; import org.wso2.carbon.event.stream.core.exception.EventStreamConfigurationException;
@ -78,7 +77,6 @@ public class UIEventAdapter implements OutputEventAdapter {
@Override @Override
public void init() throws OutputEventAdapterException { public void init() throws OutputEventAdapterException {
tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
//ExecutorService will be assigned if it is null //ExecutorService will be assigned if it is null
@ -198,7 +196,6 @@ public class UIEventAdapter implements OutputEventAdapter {
@Override @Override
public void publish(Object message, Map<String, String> dynamicProperties) { public void publish(Object message, Map<String, String> dynamicProperties) {
Event event = (Event) message; Event event = (Event) message;
StringBuilder eventBuilder = new StringBuilder("["); StringBuilder eventBuilder = new StringBuilder("[");
@ -257,7 +254,7 @@ public class UIEventAdapter implements OutputEventAdapter {
streamSpecificEvents.add(eventValues); streamSpecificEvents.add(eventValues);
// fetch all valid sessions checked against any queryParameters provided when subscribing. // fetch all valid sessions checked against any queryParameters provided when subscribing.
CopyOnWriteArrayList<WebSocketSessionUtil> validSessions = getValidSessions(event); CopyOnWriteArrayList<WebSocketSessionRequest> validSessions = getValidSessions(event);
try { try {
executorService.execute(new WebSocketSender(validSessions, eventString)); executorService.execute(new WebSocketSender(validSessions, eventString));
@ -275,7 +272,6 @@ public class UIEventAdapter implements OutputEventAdapter {
@Override @Override
public void destroy() { public void destroy() {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
ConcurrentHashMap<String, String> tenantSpecificAdapterMap = UIEventAdaptorServiceDataHolder ConcurrentHashMap<String, String> tenantSpecificAdapterMap = UIEventAdaptorServiceDataHolder
@ -331,15 +327,15 @@ public class UIEventAdapter implements OutputEventAdapter {
* @param event the current event received and that which needs to be published to subscribed sessions. * @param event 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. * @return a list of all validated web-socket sessions against the queryString values.
*/ */
private CopyOnWriteArrayList<WebSocketSessionUtil> getValidSessions(Event event) { private CopyOnWriteArrayList<WebSocketSessionRequest> getValidSessions(Event event) {
CopyOnWriteArrayList<WebSocketSessionUtil> validSessions = new CopyOnWriteArrayList<>(); CopyOnWriteArrayList<WebSocketSessionRequest> validSessions = new CopyOnWriteArrayList<>();
UIOutputCallbackControllerServiceImpl uiOutputCallbackControllerServiceImpl = UIOutputCallbackControllerServiceImpl uiOutputCallbackControllerServiceImpl =
UIEventAdaptorServiceDataHolder.getUIOutputCallbackRegisterServiceImpl(); UIEventAdaptorServiceDataHolder.getUIOutputCallbackRegisterServiceImpl();
// get all subscribed web-socket sessions. // get all subscribed web-socket sessions.
CopyOnWriteArrayList<WebSocketSessionUtil> webSocketSessionUtils = CopyOnWriteArrayList<WebSocketSessionRequest> webSocketSessionUtils =
uiOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId); uiOutputCallbackControllerServiceImpl.getSessions(tenantId, streamId);
if (webSocketSessionUtils != null) { if (webSocketSessionUtils != null) {
for (WebSocketSessionUtil webSocketSessionUtil : webSocketSessionUtils) { for (WebSocketSessionRequest webSocketSessionUtil : webSocketSessionUtils) {
boolean isValidSession = validateEventAgainstSessionFilters(event, webSocketSessionUtil); boolean isValidSession = validateEventAgainstSessionFilters(event, webSocketSessionUtil);
if (isValidSession) { if (isValidSession) {
validSessions.add(webSocketSessionUtil); validSessions.add(webSocketSessionUtil);
@ -360,7 +356,7 @@ public class UIEventAdapter implements OutputEventAdapter {
* @param webSocketSessionUtil the session which needs validated for its authenticity to receive this event. * @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". * @return "true" if the session is valid to receive the event else "false".
*/ */
private boolean validateEventAgainstSessionFilters(Event event, WebSocketSessionUtil webSocketSessionUtil) { private boolean validateEventAgainstSessionFilters(Event event, WebSocketSessionRequest webSocketSessionUtil) {
// fetch the queryString Key:Value pair map of the given session. // fetch the queryString Key:Value pair map of the given session.
Map<String, String> queryParamValuePairs = webSocketSessionUtil.getQueryParamValuePairs(); Map<String, String> queryParamValuePairs = webSocketSessionUtil.getQueryParamValuePairs();
@ -412,9 +408,9 @@ public class UIEventAdapter implements OutputEventAdapter {
private class WebSocketSender implements Runnable { private class WebSocketSender implements Runnable {
private String message; private String message;
private CopyOnWriteArrayList<WebSocketSessionUtil> webSocketSessionUtils; private CopyOnWriteArrayList<WebSocketSessionRequest> webSocketSessionUtils;
public WebSocketSender(CopyOnWriteArrayList<WebSocketSessionUtil> webSocketSessionUtils, String message) { public WebSocketSender(CopyOnWriteArrayList<WebSocketSessionRequest> webSocketSessionUtils, String message) {
this.webSocketSessionUtils = webSocketSessionUtils; this.webSocketSessionUtils = webSocketSessionUtils;
this.message = message; this.message = message;
} }
@ -434,8 +430,8 @@ public class UIEventAdapter implements OutputEventAdapter {
public void run() { public void run() {
if (webSocketSessionUtils != null) { if (webSocketSessionUtils != null) {
doLogDroppedMessage = true; doLogDroppedMessage = true;
for (WebSocketSessionUtil webSocketSessionUtil : webSocketSessionUtils) { for (WebSocketSessionRequest webSocketSessionUtil : webSocketSessionUtils) {
synchronized (WebSocketSessionUtil.class) { synchronized (WebSocketSessionRequest.class) {
try { try {
webSocketSessionUtil.getSession().getBasicRemote().sendText(message); webSocketSessionUtil.getSession().getBasicRemote().sendText(message);
} catch (IOException e) { } catch (IOException e) {

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
@ -19,10 +18,9 @@
*/ */
package org.wso2.carbon.device.mgt.iot.output.adapter.ui; package org.wso2.carbon.device.mgt.iot.output.adapter.ui;
import com.google.gson.JsonObject;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.internal.UIEventAdaptorServiceDataHolder; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.internal.UIEventAdaptorServiceDataHolder;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebSocketSessionUtil; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebSocketSessionRequest;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.UIEventAdapterConstants; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.UIEventAdapterConstants;
import javax.websocket.Session; import javax.websocket.Session;
@ -36,7 +34,7 @@ import java.util.concurrent.LinkedBlockingDeque;
*/ */
public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackControllerService { public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackControllerService {
private ConcurrentHashMap<Integer, ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionUtil>>> private ConcurrentHashMap<Integer, ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionRequest>>>
outputEventAdaptorSessionMap; outputEventAdaptorSessionMap;
public UIOutputCallbackControllerServiceImpl() { public UIOutputCallbackControllerServiceImpl() {
@ -58,7 +56,7 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo
version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION;
} }
String streamId = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version; String streamId = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version;
ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionUtil>> tenantSpecificAdaptorMap = ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionRequest>> tenantSpecificAdaptorMap =
outputEventAdaptorSessionMap.get(tenantId); outputEventAdaptorSessionMap.get(tenantId);
if (tenantSpecificAdaptorMap == null) { if (tenantSpecificAdaptorMap == null) {
tenantSpecificAdaptorMap = new ConcurrentHashMap<>(); tenantSpecificAdaptorMap = new ConcurrentHashMap<>();
@ -66,7 +64,7 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo
tenantSpecificAdaptorMap = outputEventAdaptorSessionMap.get(tenantId); tenantSpecificAdaptorMap = outputEventAdaptorSessionMap.get(tenantId);
} }
} }
CopyOnWriteArrayList<WebSocketSessionUtil> adapterSpecificSessions = tenantSpecificAdaptorMap.get(streamId); CopyOnWriteArrayList<WebSocketSessionRequest> adapterSpecificSessions = tenantSpecificAdaptorMap.get(streamId);
if (adapterSpecificSessions == null) { if (adapterSpecificSessions == null) {
adapterSpecificSessions = new CopyOnWriteArrayList<>(); adapterSpecificSessions = new CopyOnWriteArrayList<>();
if (null != tenantSpecificAdaptorMap.putIfAbsent(streamId, adapterSpecificSessions)) { if (null != tenantSpecificAdaptorMap.putIfAbsent(streamId, adapterSpecificSessions)) {
@ -74,7 +72,7 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo
} }
} }
WebSocketSessionUtil webSocketSessionUtil = new WebSocketSessionUtil(session); WebSocketSessionRequest webSocketSessionUtil = new WebSocketSessionRequest(session);
adapterSpecificSessions.add(webSocketSessionUtil); adapterSpecificSessions.add(webSocketSessionUtil);
} }
@ -85,8 +83,8 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo
* @param streamId - Stream name and version which user register to. * @param streamId - Stream name and version which user register to.
* @return the sessions list. * @return the sessions list.
*/ */
public CopyOnWriteArrayList<WebSocketSessionUtil> getSessions(int tenantId, String streamId) { public CopyOnWriteArrayList<WebSocketSessionRequest> getSessions(int tenantId, String streamId) {
ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionUtil>> tenantSpecificAdaptorMap ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionRequest>> tenantSpecificAdaptorMap
= outputEventAdaptorSessionMap.get(tenantId); = outputEventAdaptorSessionMap.get(tenantId);
if (tenantSpecificAdaptorMap != null) { if (tenantSpecificAdaptorMap != null) {
return tenantSpecificAdaptorMap.get(streamId); return tenantSpecificAdaptorMap.get(streamId);
@ -125,15 +123,15 @@ public class UIOutputCallbackControllerServiceImpl implements UIOutputCallbackCo
version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION; version = UIEventAdapterConstants.ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION;
} }
String id = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version; String id = streamName + UIEventAdapterConstants.ADAPTER_UI_COLON + version;
ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionUtil>> tenantSpecificAdaptorMap ConcurrentHashMap<String, CopyOnWriteArrayList<WebSocketSessionRequest>> tenantSpecificAdaptorMap
= outputEventAdaptorSessionMap.get(tenantId); = outputEventAdaptorSessionMap.get(tenantId);
if (tenantSpecificAdaptorMap != null) { if (tenantSpecificAdaptorMap != null) {
CopyOnWriteArrayList<WebSocketSessionUtil> adapterSpecificSessions = tenantSpecificAdaptorMap.get(id); CopyOnWriteArrayList<WebSocketSessionRequest> adapterSpecificSessions = tenantSpecificAdaptorMap.get(id);
if (adapterSpecificSessions != null) { if (adapterSpecificSessions != null) {
WebSocketSessionUtil sessionToRemove = null; WebSocketSessionRequest sessionToRemove = null;
Iterator<WebSocketSessionUtil> iterator = adapterSpecificSessions.iterator(); Iterator<WebSocketSessionRequest> iterator = adapterSpecificSessions.iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
WebSocketSessionUtil webSocketSessionUtil = iterator.next(); WebSocketSessionRequest webSocketSessionUtil = iterator.next();
if (session.getId().equals(webSocketSessionUtil.getSession().getId())) { if (session.getId().equals(webSocketSessionUtil.getSession().getId())) {
sessionToRemove = webSocketSessionUtil; sessionToRemove = webSocketSessionUtil;
break; break;

@ -12,7 +12,9 @@
* *
*/ */
package util; package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication;
import java.util.Map;
/** /**
* This is returned after authentication. * This is returned after authentication.
@ -25,6 +27,12 @@ public class AuthenticationInfo {
private boolean authenticated; private boolean authenticated;
private String username; private String username;
private String tenantDomain; private String tenantDomain;
/**
* To hold authentication related properties eg: scopes in oauth
*/
private Map<String, Object> properties;
/** /**
* returns whether the client is authenticated * returns whether the client is authenticated
*/ */
@ -57,4 +65,12 @@ public class AuthenticationInfo {
public void setTenantDomain(String tenantDomain) { public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain; this.tenantDomain = tenantDomain;
} }
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
} }

@ -0,0 +1,30 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication;
import javax.websocket.Session;
/**
* This interface is used to authenticate a websocket session
*/
public interface Authenticator {
/**
* Check whether the client is authenticated to connect.
* @param session user object.
* @return AuthenicationInfo which contains authentication client information.
*/
AuthenticationInfo isAutenticated(Session session);
}

@ -0,0 +1,26 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.oauth.OAuthTokenValdiator;
import javax.websocket.Session;
public class OAuthAuthenticator implements Authenticator {
@Override
public AuthenticationInfo isAutenticated(Session session) {
return OAuthTokenValdiator.getInstance().validateToken(session);
}
}

@ -12,13 +12,17 @@
* *
*/ */
package oauth; package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.oauth;
import org.apache.axis2.context.ServiceContext; import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.transport.http.HTTPConstants; import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.impl.GenericObjectPool; import org.apache.commons.pool.impl.GenericObjectPool;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.config.Property;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.config.WebsocketConfig;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.constants.WebsocketConstants;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;
import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken; import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken;
@ -26,14 +30,14 @@ import org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import util.AuthenticationInfo;
import javax.websocket.Session; import javax.websocket.Session;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException; import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
/** /**
@ -68,7 +72,8 @@ public class OAuthTokenValdiator {
Properties properties = getWebSocketConfig(); Properties properties = getWebSocketConfig();
this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(properties)); this.stubs = new GenericObjectPool(new OAuthTokenValidaterStubFactory(properties));
} catch (IOException e) { } catch (IOException e) {
log.error("Failed to parse the web socket config file " + WEBSOCKET_CONFIG_LOCATION); log.error("Failed to parse the web socket org.wso2.carbon.device.mgt.iot.output.adapter.ui.config file " +
WEBSOCKET_CONFIG_LOCATION, e);
} }
} }
@ -152,6 +157,12 @@ public class OAuthTokenValdiator {
String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser); String tenantDomain = MultitenantUtils.getTenantDomain(authorizedUser);
authenticationInfo.setUsername(username); authenticationInfo.setUsername(username);
authenticationInfo.setTenantDomain(tenantDomain); authenticationInfo.setTenantDomain(tenantDomain);
String scopes[] = tokenValidationResponse.getScope();
if (scopes != null) {
Map<String, Object> properties = new HashMap<>();
properties.put(WebsocketConstants.SCOPE_IDENTIFIER, scopes);
authenticationInfo.setProperties(properties);
}
} else { } else {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Token validation failed for token: " + token); log.debug("Token validation failed for token: " + token);
@ -169,12 +180,10 @@ public class OAuthTokenValdiator {
*/ */
private Properties getWebSocketConfig() throws IOException { private Properties getWebSocketConfig() throws IOException {
Properties properties = new Properties(); Properties properties = new Properties();
File configFile =new File(WEBSOCKET_CONFIG_LOCATION); List<Property> propertyList = WebsocketConfig.getInstance().getWebsocketValidationConfigs().getAuthenticator()
if (configFile.exists()) { .getProperties().getProperty();
InputStream fileInputStream = new FileInputStream(configFile); for (Property property : propertyList) {
if (fileInputStream != null) { properties.put(property.getName(), property.getValue());
properties.load(fileInputStream);
}
} }
return properties; return properties;
} }

@ -15,9 +15,8 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package oauth; package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.oauth;
import oauth.exception.OAuthTokenValidationException;
import org.apache.axis2.AxisFault; import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants; import org.apache.axis2.Constants;
import org.apache.axis2.client.Options; import org.apache.axis2.client.Options;
@ -31,10 +30,13 @@ import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams; import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.BasePoolableObjectFactory; import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.oauth.exception.OAuthTokenValidationException;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.constants.WebsocketConstants;
import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; import org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub;
import util.UIConstants;
import java.io.IOException; import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -46,7 +48,7 @@ import java.util.Properties;
* This follows object pool pattern to manage the stub for oauth validation service. * This follows object pool pattern to manage the stub for oauth validation service.
*/ */
public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory { public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
private static final Logger log = Logger.getLogger(OAuthTokenValidaterStubFactory.class); private static final Log log = LogFactory.getLog(OAuthTokenValidaterStubFactory.class);
private HttpClient httpClient; private HttpClient httpClient;
Properties tokenValidationProperties; Properties tokenValidationProperties;
@ -91,7 +93,7 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
private OAuth2TokenValidationServiceStub generateStub() throws OAuthTokenValidationException { private OAuth2TokenValidationServiceStub generateStub() throws OAuthTokenValidationException {
OAuth2TokenValidationServiceStub stub; OAuth2TokenValidationServiceStub stub;
try { try {
URL hostURL = new URL(tokenValidationProperties.getProperty((UIConstants.TOKEN_VALIDATION_ENDPOINT_URL))); URL hostURL = new URL(tokenValidationProperties.getProperty((WebsocketConstants.TOKEN_VALIDATION_ENDPOINT_URL)));
if (hostURL != null) { if (hostURL != null) {
stub = new OAuth2TokenValidationServiceStub(hostURL.toString()); stub = new OAuth2TokenValidationServiceStub(hostURL.toString());
if (stub != null) { if (stub != null) {
@ -102,8 +104,8 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
HttpTransportProperties.Authenticator auth = HttpTransportProperties.Authenticator auth =
new HttpTransportProperties.Authenticator(); new HttpTransportProperties.Authenticator();
auth.setPreemptiveAuthentication(true); auth.setPreemptiveAuthentication(true);
String username = tokenValidationProperties.getProperty(UIConstants.USERNAME); String username = tokenValidationProperties.getProperty(WebsocketConstants.USERNAME);
String password = tokenValidationProperties.getProperty(UIConstants.PASSWORD); String password = tokenValidationProperties.getProperty(WebsocketConstants.PASSWORD);
auth.setPassword(username); auth.setPassword(username);
auth.setUsername(password); auth.setUsername(password);
Options options = client.getOptions(); Options options = client.getOptions();
@ -167,9 +169,9 @@ public class OAuthTokenValidaterStubFactory extends BasePoolableObjectFactory {
private HttpClient createHttpClient() { private HttpClient createHttpClient() {
HttpConnectionManagerParams params = new HttpConnectionManagerParams(); HttpConnectionManagerParams params = new HttpConnectionManagerParams();
params.setDefaultMaxConnectionsPerHost(Integer.parseInt(tokenValidationProperties.getProperty( params.setDefaultMaxConnectionsPerHost(Integer.parseInt(tokenValidationProperties.getProperty(
UIConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST))); WebsocketConstants.MAXIMUM_HTTP_CONNECTION_PER_HOST)));
params.setMaxTotalConnections(Integer.parseInt(tokenValidationProperties.getProperty( params.setMaxTotalConnections(Integer.parseInt(tokenValidationProperties.getProperty(
UIConstants.MAXIMUM_TOTAL_HTTP_CONNECTION))); WebsocketConstants.MAXIMUM_TOTAL_HTTP_CONNECTION)));
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
connectionManager.setParams(params); connectionManager.setParams(params);
return new HttpClient(connectionManager); return new HttpClient(connectionManager);

@ -15,27 +15,23 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * under the License.
*/ */
package oauth.exception; package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.oauth.exception;
/** /**
* This Exception will be thrown, when there any interference with token validation flow. * This Exception will be thrown, when there any interference with token validation flow.
*/ */
public class OAuthTokenValidationException extends Exception { public class OAuthTokenValidationException extends Exception {
private String errMessage;
public OAuthTokenValidationException(String msg, Exception nestedEx) { public OAuthTokenValidationException(String msg, Exception nestedEx) {
super(msg, nestedEx); super(msg, nestedEx);
setErrorMessage(msg);
} }
public OAuthTokenValidationException(String message, Throwable cause) { public OAuthTokenValidationException(String message, Throwable cause) {
super(message, cause); super(message, cause);
setErrorMessage(message);
} }
public OAuthTokenValidationException(String msg) { public OAuthTokenValidationException(String msg) {
super(msg); super(msg);
setErrorMessage(msg);
} }
public OAuthTokenValidationException() { public OAuthTokenValidationException() {
@ -46,11 +42,4 @@ public class OAuthTokenValidationException extends Exception {
super(cause); super(cause);
} }
public String getErrorMessage() {
return errMessage;
}
public void setErrorMessage(String errMessage) {
this.errMessage = errMessage;
}
} }

@ -0,0 +1,39 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.AuthenticationInfo;
import javax.websocket.Session;
import java.util.Map;
/**
* Check whether the client is authorized to connect.
*/
public interface Authorizer {
/**
* Check whether the client is authorized to connect with the stream.
* @param authenticationInfo authenticated client information.
* @param session request session of the client.
* @param stream stream name of the client connecting to.
* @return true if authorized else return false.
*/
boolean isAuthorized(AuthenticationInfo authenticationInfo, Session session, String stream);
}

@ -0,0 +1,55 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.AuthenticationInfo;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.constants.WebsocketConstants;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebSocketSessionRequest;
import javax.websocket.Session;
import java.util.Map;
/**
* This authorizer crossvalidates the request with device id and device type.
*/
public class DeviceAuthorizer implements Authorizer {
private static final String STATS_SCOPE_IDENTIFIER = "stats";
private static final String DEVICE_MGT_SCOPE_IDENTIFIER = "device-mgt";
@Override
public boolean isAuthorized(AuthenticationInfo authenticationInfo, Session session, String stream) {
WebSocketSessionRequest webSocketSessionRequest = new WebSocketSessionRequest(session);
Map<String, String> queryParams = webSocketSessionRequest.getQueryParamValuePairs();
String deviceId = queryParams.get("deviceId");
String deviceType = queryParams.get("deviceType");
Object scopeObject = authenticationInfo.getProperties().get(WebsocketConstants.SCOPE_IDENTIFIER);
if (deviceId != null && !deviceId.isEmpty() && deviceType != null && !deviceType.isEmpty()
&& scopeObject != null) {
String scopes[] = (String[]) scopeObject;
String requiredScope = DEVICE_MGT_SCOPE_IDENTIFIER + ":" + deviceType + ":" + deviceId + ":"
+ STATS_SCOPE_IDENTIFIER;
for (String scope : scopes) {
if (requiredScope.equals(scope)) {
return true;
}
}
}
return false;
}
}

@ -0,0 +1,107 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Authenticator complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="Authenticator">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Properties" type="{}Properties"/>
* &lt;/sequence>
* &lt;attribute name="class" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Authenticator", propOrder = {
"properties"
})
public class Authenticator {
@XmlElement(name = "Properties", required = false)
protected Properties properties;
@XmlAttribute(name = "class")
protected String clazz;
/**
* Gets the value of the properties property.
*
* @return
* possible object is
* {@link Properties }
*
*/
public Properties getProperties() {
return properties;
}
/**
* Sets the value of the properties property.
*
* @param value
* allowed object is
* {@link Properties }
*
*/
public void setProperties(Properties value) {
this.properties = value;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
}

@ -0,0 +1,107 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for Authorizer complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="Authorizer">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Properties" type="{}Properties"/>
* &lt;/sequence>
* &lt;attribute name="class" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Authorizer", propOrder = {
"properties"
})
public class Authorizer {
@XmlElement(name = "Properties", required = false)
protected Properties properties;
@XmlAttribute(name = "class")
protected String clazz;
/**
* Gets the value of the properties property.
*
* @return
* possible object is
* {@link Properties }
*
*/
public Properties getProperties() {
return properties;
}
/**
* Sets the value of the properties property.
*
* @param value
* allowed object is
* {@link Properties }
*
*/
public void setProperties(Properties value) {
this.properties = value;
}
/**
* Gets the value of the clazz property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClazz() {
return clazz;
}
/**
* Sets the value of the clazz property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClazz(String value) {
this.clazz = value;
}
}

@ -0,0 +1,86 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Java class for Properties complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="Properties">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Property" type="{}Property" maxOccurs="unbounded" minOccurs="0"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Properties", propOrder = {
"property"
})
public class Properties {
@XmlElement(name = "Property")
protected List<Property> property;
/**
* Gets the value of the property property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the property property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getProperty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Property }
*
*
*/
public List<Property> getProperty() {
if (property == null) {
property = new ArrayList<Property>();
}
return this.property;
}
}

@ -0,0 +1,104 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for Property complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="Property">
* &lt;simpleContent>
* &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>string">
* &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;/extension>
* &lt;/simpleContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Property", propOrder = {
"value"
})
public class Property {
@XmlValue
protected String value;
@XmlAttribute(name = "name")
protected String name;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the name property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
}

@ -0,0 +1,71 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.util.WebsocketUtils;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
/**
* This class represents the configuration that are needed for scopes to permission map.
*/
public class WebsocketConfig {
private static WebsocketConfig config = new WebsocketConfig();
private WebsocketValidationConfigs websocketValidationConfigs;
private static final String WEBSOCKET_VALIDATION_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "websocket-validation.xml";
private WebsocketConfig() {
}
public static WebsocketConfig getInstance() {
return config;
}
public void init() throws WebsocketValidationConfigurationFailedException {
try {
File deviceMgtConfig = new File(WEBSOCKET_VALIDATION_CONFIG_PATH);
Document doc = WebsocketUtils.convertToDocument(deviceMgtConfig);
/* Un-marshaling DeviceMGtScope configuration */
JAXBContext ctx = JAXBContext.newInstance(WebsocketValidationConfigs.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
websocketValidationConfigs = (WebsocketValidationConfigs) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new WebsocketValidationConfigurationFailedException("Error occurred while un-marshalling Websocket" +
" Config", e);
}
}
public WebsocketValidationConfigs getWebsocketValidationConfigs() {
return websocketValidationConfigs;
}
public void setWebsocketValidationConfigs(WebsocketValidationConfigs websocketValidationConfigs) {
websocketValidationConfigs = websocketValidationConfigs;
}
}

@ -0,0 +1,106 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for WebsocketValidationConfigs complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="WebsocketValidationConfigs">
* &lt;complexContent>
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* &lt;sequence>
* &lt;element name="Authenticator" type="{}Authenticator"/>
* &lt;element name="Authorizer" type="{}Authorizer"/>
* &lt;/sequence>
* &lt;/restriction>
* &lt;/complexContent>
* &lt;/complexType>
* </pre>
*
*
*/
@XmlRootElement(name = "WebsocketValidationConfigs")
@XmlAccessorType(XmlAccessType.FIELD)
public class WebsocketValidationConfigs {
@XmlElement(name = "Authenticator", required = true)
protected Authenticator authenticator;
@XmlElement(name = "Authorizer", required = true)
protected Authorizer authorizer;
/**
* Gets the value of the authenticator property.
*
* @return
* possible object is
* {@link Authenticator }
*
*/
public Authenticator getAuthenticator() {
return authenticator;
}
/**
* Sets the value of the authenticator property.
*
* @param value
* allowed object is
* {@link Authenticator }
*
*/
public void setAuthenticator(Authenticator value) {
this.authenticator = value;
}
/**
* Gets the value of the authorizer property.
*
* @return
* possible object is
* {@link Authorizer }
*
*/
public Authorizer getAuthorizer() {
return authorizer;
}
/**
* Sets the value of the authorizer property.
*
* @param value
* allowed object is
* {@link Authorizer }
*
*/
public void setAuthorizer(Authorizer value) {
this.authorizer = value;
}
}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.config;
public class WebsocketValidationConfigurationFailedException extends Exception {
private static final long serialVersionUID = -3151279329290703928L;
public WebsocketValidationConfigurationFailedException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public WebsocketValidationConfigurationFailedException(String message, Throwable cause) {
super(message, cause);
}
public WebsocketValidationConfigurationFailedException(String msg) {
super(msg);
}
public WebsocketValidationConfigurationFailedException() {
super();
}
public WebsocketValidationConfigurationFailedException(Throwable cause) {
super(cause);
}
}

@ -0,0 +1,35 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.constants;
/**
* This holds the constants related to this feature
*/
public class WebsocketConstants {
private WebsocketConstants() {
}
public static final String SCOPE_IDENTIFIER = "scopes";
public static final String MAXIMUM_TOTAL_HTTP_CONNECTION = "maximumTotalHttpConnection";
public static final String MAXIMUM_HTTP_CONNECTION_PER_HOST = "maximumHttpConnectionPerHost";
public static final String TOKEN_VALIDATION_ENDPOINT_URL = "tokenValidationEndpoint";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
}

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
@ -31,10 +30,10 @@ import java.util.concurrent.LinkedBlockingDeque;
public final class UIEventAdaptorServiceDataHolder { public final class UIEventAdaptorServiceDataHolder {
private static UIOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl; private static UIOutputCallbackControllerServiceImpl UIOutputCallbackRegisterServiceImpl;
private static ConcurrentHashMap<Integer,ConcurrentHashMap<String, String>> private static ConcurrentHashMap<Integer, ConcurrentHashMap<String, String>>
tenantSpecificOutputEventStreamAdapterMap = new ConcurrentHashMap<Integer,ConcurrentHashMap<String, String>>(); tenantSpecificOutputEventStreamAdapterMap = new ConcurrentHashMap<>();
private static ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>> private static ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>>
tenantSpecificStreamEventMap = new ConcurrentHashMap<Integer, ConcurrentHashMap<String, LinkedBlockingDeque<Object>>>(); tenantSpecificStreamEventMap = new ConcurrentHashMap<>();
private static EventStreamService eventStreamService; private static EventStreamService eventStreamService;
public static void registerEventStreamService(EventStreamService eventBuilderService) { public static void registerEventStreamService(EventStreamService eventBuilderService) {

@ -1,5 +1,4 @@
/* /*
*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* WSO2 Inc. licenses this file to you under the Apache License, * WSO2 Inc. licenses this file to you under the Apache License,
@ -24,6 +23,12 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIEventAdapterFactory; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIEventAdapterFactory;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerServiceImpl; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerServiceImpl;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.Authenticator;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.Authorizer;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.config.WebsocketConfig;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.config.WebsocketValidationConfigurationFailedException;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.service.WebsocketValidationService;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.service.WebsocketValidationServiceImpl;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterFactory;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerService; import org.wso2.carbon.device.mgt.iot.output.adapter.ui.UIOutputCallbackControllerService;
import org.wso2.carbon.event.stream.core.EventStreamService; import org.wso2.carbon.event.stream.core.EventStreamService;
@ -58,8 +63,37 @@ public class UILocalEventAdapterServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Successfully deployed the output ui adapter service"); log.debug("Successfully deployed the output ui adapter service");
} }
try {
WebsocketConfig.getInstance().init();
WebsocketValidationServiceImpl websocketValidationService = new WebsocketValidationServiceImpl();
String authenticatorClassName = WebsocketConfig.getInstance().getWebsocketValidationConfigs()
.getAuthenticator().getClazz();
String authorizerClassName = WebsocketConfig.getInstance().getWebsocketValidationConfigs()
.getAuthorizer().getClazz();
if (authenticatorClassName != null && !authenticatorClassName.isEmpty()) {
Class<? extends Authenticator> authenticatorClass = Class.forName(authenticatorClassName)
.asSubclass(Authenticator.class);
Authenticator authenticator = authenticatorClass.newInstance();
websocketValidationService.setAuthenticator(authenticator);
}
if (authorizerClassName != null && !authorizerClassName.isEmpty()) {
Class<? extends Authorizer> authorizerClass = Class.forName(authorizerClassName)
.asSubclass(Authorizer.class);
Authorizer authorizer = authorizerClass.newInstance();
websocketValidationService.setAuthorizer(authorizer);
}
context.getBundleContext().registerService(
WebsocketValidationService.class.getName(), websocketValidationService, null);
} catch (WebsocketValidationConfigurationFailedException e) {
log.error("Failed to initialize configuration for websocket.", e);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
log.error("Failed to initialize the class authentication and authorization given " +
"in the websocket validation configuration.", e);
}
} catch (RuntimeException e) { } catch (RuntimeException e) {
log.error("Can not create the output ui adapter service ", e); log.error("Can not create the output ui adapter service ", e);
} catch (Throwable e) {
log.error("Error occurred while activating UI Event Adapter Service Component", e);
} }
} }

@ -0,0 +1,33 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.service;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.Authenticator;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.Authorizer;
/**
* This returns the configured authenticator and authorizer for websocket.
*/
public interface WebsocketValidationService {
Authenticator getAuthenticator();
Authorizer getAuthorizer();
}

@ -0,0 +1,48 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.service;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.Authenticator;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.Authorizer;
/**
* This returns the configured authenticator and authorizer for websocket.
*/
public class WebsocketValidationServiceImpl implements WebsocketValidationService{
private Authenticator authenticator;
private Authorizer authorizer;
@Override
public Authenticator getAuthenticator() {
return authenticator;
}
@Override
public Authorizer getAuthorizer() {
return authorizer;
}
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
public void setAuthorizer(Authorizer authorizer) {
this.authorizer = authorizer;
}
}

@ -1,22 +1,21 @@
/* /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* *
* Copyright (c) 2014-2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
* *
* WSO2 Inc. licenses this file to you under the Apache License, * http://www.apache.org/licenses/LICENSE-2.0
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* *
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.util; package org.wso2.carbon.device.mgt.iot.output.adapter.ui.util;
/** /**
@ -27,7 +26,7 @@ public class UIEventAdapterConstants {
private UIEventAdapterConstants() { private UIEventAdapterConstants() {
} }
public static final String ADAPTER_TYPE_UI = "iot-ui"; public static final String ADAPTER_TYPE_UI = "secured-ui";
public static final String ADAPTER_USAGE_TIPS_PREFIX = "ui.usage.tips_prefix"; public static final String ADAPTER_USAGE_TIPS_PREFIX = "ui.usage.tips_prefix";
public static final String ADAPTER_USAGE_TIPS_POSTFIX = "ui.usage.tips_postfix"; public static final String ADAPTER_USAGE_TIPS_POSTFIX = "ui.usage.tips_postfix";
public static final String ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION = "1.0.0"; public static final String ADAPTER_UI_DEFAULT_OUTPUT_STREAM_VERSION = "1.0.0";

@ -1,5 +1,22 @@
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.util; /*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -13,15 +30,15 @@ import java.util.Map;
* of the Session object derived from processing some of the (default) existing attributes. * of the Session object derived from processing some of the (default) existing attributes.
* Ex: Query-String's [Key:Value] Map derived from the queryString attribute of the original class. * Ex: Query-String's [Key:Value] Map derived from the queryString attribute of the original class.
*/ */
public class WebSocketSessionUtil { public class WebSocketSessionRequest {
private static final Log log = LogFactory.getLog(WebSocketSessionUtil.class); private static final Log log = LogFactory.getLog(WebSocketSessionRequest.class);
private static final String QUERY_STRING_SEPERATOR = "&"; private static final String QUERY_STRING_SEPERATOR = "&";
private static final String QUERY_KEY_VALUE_SEPERATOR = "="; private static final String QUERY_KEY_VALUE_SEPERATOR = "=";
private Map<String, String> queryParamValuePairs = null; private Map<String, String> queryParamValuePairs = null;
private Session session; private Session session;
public WebSocketSessionUtil(Session session) { public WebSocketSessionRequest(Session session) {
this.session = session; this.session = session;
setQueryParamValuePairs(); setQueryParamValuePairs();
} }
@ -42,19 +59,15 @@ public class WebSocketSessionUtil {
if (session.getQueryString() != null) { if (session.getQueryString() != null) {
String queryString = session.getQueryString(); String queryString = session.getQueryString();
String[] allQueryParamPairs = queryString.split(QUERY_STRING_SEPERATOR); String[] allQueryParamPairs = queryString.split(QUERY_STRING_SEPERATOR);
for (String keyValuePair : allQueryParamPairs) { for (String keyValuePair : allQueryParamPairs) {
String[] thisQueryParamPair = keyValuePair.split(QUERY_KEY_VALUE_SEPERATOR); String[] thisQueryParamPair = keyValuePair.split(QUERY_KEY_VALUE_SEPERATOR);
if (thisQueryParamPair.length != 2) { if (thisQueryParamPair.length != 2) {
log.warn("Invalid query string [" + queryString + "] passed in."); log.warn("Invalid query string [" + queryString + "] passed in.");
break; break;
} }
if (queryParamValuePairs == null) { if (queryParamValuePairs == null) {
queryParamValuePairs = new HashMap<>(); queryParamValuePairs = new HashMap<>();
} }
queryParamValuePairs.put(thisQueryParamPair[0], thisQueryParamPair[1]); queryParamValuePairs.put(thisQueryParamPair[0], thisQueryParamPair[1]);
} }
} }

@ -0,0 +1,45 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.output.adapter.ui.util;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.iot.output.adapter.ui.config.WebsocketValidationConfigurationFailedException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
/**
* This class holds util methods used by OAuth extension bundle.
*/
public class WebsocketUtils {
public static Document convertToDocument(File file) throws WebsocketValidationConfigurationFailedException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new WebsocketValidationConfigurationFailedException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
}

@ -23,7 +23,7 @@ var uriMatcher = new URIMatcher(String(uri));
var log = new Log("api/policy-api.jag"); var log = new Log("api/policy-api.jag");
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var policyModule = require("/app/modules/policy.js").policyModule; var policyModule = require("/app/modules/business-controllers/policy.js")["policyModule"];
var deviceType, deviceId; var deviceType, deviceId;

@ -18,7 +18,7 @@
function onRequest(context) { function onRequest(context) {
var log = new Log("operation.js"); var log = new Log("operation.js");
var operationModule = require("/app/modules/operation.js").operationModule; var operationModule = require("/app/modules/business-controllers/operation.js")["operationModule"];
var device = context.unit.params.device; var device = context.unit.params.device;
var autoCompleteParams = context.unit.params.autoCompleteParams; var autoCompleteParams = context.unit.params.autoCompleteParams;
var controlOperations = operationModule.getControlOperations(device.type); var controlOperations = operationModule.getControlOperations(device.type);

@ -19,7 +19,7 @@
function onRequest(context) { function onRequest(context) {
var log = new Log("policy-view-edit-unit backend js"); var log = new Log("policy-view-edit-unit backend js");
log.debug("calling policy-view-edit-unit"); log.debug("calling policy-view-edit-unit");
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
context.roles = userModule.getRoles().content; context.roles = userModule.getRoles().content;
return context; return context;
} }

@ -19,7 +19,7 @@
function onRequest(context) { function onRequest(context) {
var log = new Log("policy-view-edit-unit backend js"); var log = new Log("policy-view-edit-unit backend js");
log.debug("calling policy-view-edit-unit"); log.debug("calling policy-view-edit-unit");
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
context.roles = userModule.getRoles().content; context.roles = userModule.getRoles().content;
return context; return context;
} }

@ -22,7 +22,7 @@ function onRequest(context) {
var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType"; var DTYPE_CONF_DEVICE_TYPE_KEY = "deviceType";
var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label"; var DTYPE_CONF_DEVICE_TYPE_LABEL_KEY = "label";
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var utility = require('/app/modules/utility.js').utility; var utility = require('/app/modules/utility.js').utility;
var response = userModule.getRoles(); var response = userModule.getRoles();
var wizardPage = {}; var wizardPage = {};

@ -34,7 +34,7 @@ public class DeviceTypeConfigServiceImpl implements DeviceTypeConfigService {
String deviceType = deviceManagementConfiguration.getDeviceType(); String deviceType = deviceManagementConfiguration.getDeviceType();
String tenantDomain = deviceManagementConfiguration.getDeviceManagementConfigRepository() String tenantDomain = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getProvisioningConfig().getTenantDomain(); .getProvisioningConfig().getTenantDomain();
if ( deviceType != null && !deviceType.isEmpty() && tenantDomain != null if (deviceType != null && !deviceType.isEmpty() && tenantDomain != null
&& !tenantDomain.isEmpty()) { && !tenantDomain.isEmpty()) {
deviceTypeConfigurationMap.put(new DeviceTypeConfigIdentifier(deviceType, tenantDomain), deviceTypeConfigurationMap.put(new DeviceTypeConfigIdentifier(deviceType, tenantDomain),
deviceManagementConfiguration); deviceManagementConfiguration);

@ -28,9 +28,13 @@ import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfigur
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants; import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal.RaspberrypiManagementDataHolder; import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal.RaspberrypiManagementDataHolder;
import java.util.HashMap;
import java.util.Map;
public class RaspberrypiManagerService implements DeviceManagementService { public class RaspberrypiManagerService implements DeviceManagementService {
private DeviceManager deviceManager; private DeviceManager deviceManager;
private PushNotificationConfig pushNotificationConfig;
@Override @Override
public String getType() { public String getType() {
@ -40,6 +44,21 @@ public class RaspberrypiManagerService implements DeviceManagementService {
@Override @Override
public void init() throws DeviceManagementException { public void init() throws DeviceManagementException {
deviceManager = new RaspberrypiManager(); deviceManager = new RaspberrypiManager();
this.pushNotificationConfig = this.populatePushNotificationConfig();
}
private PushNotificationConfig populatePushNotificationConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = RaspberrypiManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(RaspberrypiConstants.DEVICE_TYPE,
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig sourceConfig =
deviceManagementConfiguration.getPushNotificationConfig();
Map<String, String> staticProps = new HashMap<>();
for (org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig.Property
property : sourceConfig.getProperties()) {
staticProps.put(property.getName(), property.getValue());
}
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
} }
@Override @Override
@ -64,7 +83,7 @@ public class RaspberrypiManagerService implements DeviceManagementService {
@Override @Override
public PushNotificationConfig getPushNotificationConfig() { public PushNotificationConfig getPushNotificationConfig() {
return null; return pushNotificationConfig;
} }

@ -29,7 +29,7 @@ function onRequest(context) {
"backendApiUri": devicemgtProps["httpsURL"] + "/raspberrypi/device/stats/" "backendApiUri": devicemgtProps["httpsURL"] + "/raspberrypi/device/stats/"
}; };
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return { return {

@ -25,7 +25,7 @@ function onRequest(context) {
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/raspberrypi/", "autoCompleteParams" : autoCompleteParams}; return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/raspberrypi/", "autoCompleteParams" : autoCompleteParams};

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -82,6 +83,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
private static final String MQTT_PROTOCOL = "MQTT"; private static final String MQTT_PROTOCOL = "MQTT";
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;
private static final String DEVICE_MGT_SCOPE_IDENTIFIER = "device-mgt";
private static Log log = LogFactory.getLog(VirtualFireAlarmServiceImpl.class); private static Log log = LogFactory.getLog(VirtualFireAlarmServiceImpl.class);
@POST @POST
@ -309,10 +311,13 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true); VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
} }
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "cdmf/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId; String device = "{ \"scope\":\"mqtt-publisher mqtt-subscriber\", \"deviceIdentifiers\":[{\"id\":\""+deviceId+"\", " +
"\"type\":\""+VirtualFireAlarmConstants.DEVICE_TYPE+"\"}]}";
Map<String, String> params = new HashMap<String, String>();
params.put("device", Base64.encodeBase64String(device.getBytes()));
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, apiApplicationKey.getConsumerSecret(), owner,
scopes); null, params);
String accessToken = accessTokenInfo.getAccessToken(); String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken(); String refreshToken = accessTokenInfo.getRefreshToken();
XmppAccount newXmppAccount = new XmppAccount(); XmppAccount newXmppAccount = new XmppAccount();

@ -45,7 +45,7 @@ public class XmppConfig {
List<PushNotificationConfig.Property> properties = deviceManagementConfiguration.getPushNotificationConfig() List<PushNotificationConfig.Property> properties = deviceManagementConfiguration.getPushNotificationConfig()
.getProperties(); .getProperties();
String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider(); String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider();
if (provider.equals("XMPP")) { if ("XMPP".equals(provider)) {
enabled = true; enabled = true;
} }
if (enabled) { if (enabled) {

@ -29,7 +29,7 @@ function onRequest(context) {
"backendApiUri": devicemgtProps["httpsURL"] + "/virtual_firealarm/device/stats/" "backendApiUri": devicemgtProps["httpsURL"] + "/virtual_firealarm/device/stats/"
}; };
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { } else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return { return {

@ -25,7 +25,7 @@ function onRequest(context) {
]; ];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") { if (device && device.status != "error") {
return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/virtual_firealarm/", "autoCompleteParams" : autoCompleteParams}; return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/virtual_firealarm/", "autoCompleteParams" : autoCompleteParams};

@ -22,12 +22,23 @@ function onRequest(context) {
var devicemgtProps = require("/app/conf/reader/main.js")["conf"]; var devicemgtProps = require("/app/conf/reader/main.js")["conf"];
var constants = require("/app/modules/constants.js"); var constants = require("/app/modules/constants.js");
var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss"); var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER); var jwtService = carbon.server.osgiService('org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
var token = ""; var jwtClient = jwtService.getJWTClient();
if (tokenPair) { var encodedClientKeys = session.get(constants.ENCODED_CLIENT_KEYS_IDENTIFIER);
token = tokenPair.accessToken; if (encodedClientKeys) {
var tokenUtil = require("/app/modules/util.js").util;
var resp = tokenUtil.decode(encodedClientKeys).split(",");
var user = session.get(constants.USER_SESSION_KEY);
var deviceParam = "{\"scope\":\"stats\",\"deviceIdentifiers\":[{\"id\":\""+device.deviceIdentifier+" \", \"type\":\""+device.type+"\"}]}";
var encodedScope = tokenUtil.encode(deviceParam);
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], user.username, null,
"{\"device\": \"" +encodedScope+"\"}");
var token = "";
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.devices.temperature/1.0.0?" +
"token=" + token + "&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
} }
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.devices.temperature/1.0.0?" +
"token="+ token +"&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
return {"device": device, "websocketEndpoint" : websocketEndpoint}; return {"device": device, "websocketEndpoint" : websocketEndpoint};
} }

@ -57,11 +57,6 @@ public class GlobalThrowableMapper implements ExceptionMapper {
if (e instanceof NotFoundException) { if (e instanceof NotFoundException) {
return ((NotFoundException) e).getResponse(); return ((NotFoundException) e).getResponse();
} }
if (e instanceof ConstraintViolationException) {
log.error("Constraint violation", e);
return Response.status(Response.Status.BAD_REQUEST).header("Content-Type", "application/json")
.entity(400l).build();
}
if (e instanceof UnexpectedServerErrorException) { if (e instanceof UnexpectedServerErrorException) {
log.error("Unexpected server error", e); log.error("Unexpected server error", e);
return ((UnexpectedServerErrorException) e).getResponse(); return ((UnexpectedServerErrorException) e).getResponse();
@ -70,9 +65,15 @@ public class GlobalThrowableMapper implements ExceptionMapper {
return ((ParameterValidationException) e).getResponse(); return ((ParameterValidationException) e).getResponse();
} }
if (e instanceof IllegalArgumentException) { if (e instanceof IllegalArgumentException) {
log.error("Illegal exception.", e); ErrorDTO errorDetail = new ErrorDTO();
return Response.status(Response.Status.BAD_REQUEST).header("Content-Type", "application/json") errorDetail.setCode((long) 400);
.entity(400l).build(); errorDetail.setMoreInfo("");
errorDetail.setMessage("");
errorDetail.setDescription(e.getMessage());
return Response
.status(Response.Status.BAD_REQUEST)
.entity(errorDetail)
.build();
} }
if (e instanceof ClientErrorException) { if (e instanceof ClientErrorException) {
log.error("Client error", e); log.error("Client error", e);

@ -129,8 +129,14 @@ public class AndroidAPIUtils {
DeviceIDHolder deviceIDHolder = deviceUtils.validateDeviceIdentifiers(deviceIDs); DeviceIDHolder deviceIDHolder = deviceUtils.validateDeviceIdentifiers(deviceIDs);
List<DeviceIdentifier> validDeviceIds = deviceIDHolder.getValidDeviceIDList(); List<DeviceIdentifier> validDeviceIds = deviceIDHolder.getValidDeviceIDList();
Activity activity = getDeviceManagementService().addOperation( Activity activity = null;
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, validDeviceIds); if(validDeviceIds.size() > 0) {
activity = getDeviceManagementService().addOperation(
DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_ANDROID, operation, validDeviceIds);
} else {
throw new IllegalArgumentException("Invalid device Identifiers found");
}
// if (activity != null) { // if (activity != null) {
// GCMService gcmService = getGCMService(); // GCMService gcmService = getGCMService();
// if (gcmService.isGCMEnabled()) { // if (gcmService.isGCMEnabled()) {
@ -142,11 +148,7 @@ public class AndroidAPIUtils {
// getGCMService().sendNotification(operation.getCode(), devices); // getGCMService().sendNotification(operation.getCode(), devices);
// } // }
// } // }
if (!deviceIDHolder.getErrorDeviceIdList().isEmpty()) {
throw new BadRequestException(
new ErrorResponse.ErrorResponseBuilder().setCode(400l).setMessage(deviceUtils.
convertErrorMapIntoErrorMessage(deviceIDHolder.getErrorDeviceIdList())).build());
}
return Response.status(Response.Status.CREATED).entity(activity).build(); return Response.status(Response.Status.CREATED).entity(activity).build();
} }

@ -22,7 +22,7 @@ function onRequest(context) {
var deviceId = request.getParameter("id"); var deviceId = request.getParameter("id");
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) { if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule; var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId); var device = deviceModule.viewDevice(deviceType, deviceId);
if (device) { if (device) {

@ -1,6 +1,5 @@
{ {
"appContext": "/emm/", "appContext": "/emm/",
"clientName": "emm",
"webAgentContext" : "/emm-web-agent/", "webAgentContext" : "/emm-web-agent/",
"apiContext": "api", "apiContext": "api",
"httpsURL" : "%https.ip%", "httpsURL" : "%https.ip%",
@ -12,13 +11,23 @@
"enrollmentDir": "/emm-web-agent/enrollment", "enrollmentDir": "/emm-web-agent/enrollment",
"iOSConfigRoot" : "%https.ip%/ios-enrollment/", "iOSConfigRoot" : "%https.ip%/ios-enrollment/",
"iOSAPIRoot" : "%https.ip%/ios/", "iOSAPIRoot" : "%https.ip%/ios/",
"dynamicClientRegistrationEndPoint" : "https://localhost:9443/dynamic-client-web/register/",
"adminService": "%https.ip%", "adminService": "%https.ip%",
"idPServer":"%https.ip%/oauth2/token", "oauthProvider": {
"callBackUrl":"%https.ip%/api/device-mgt/v1.0", "appRegistration": {
"adminUser":"admin@carbon.super", "appType": "webapp",
"adminRole":"admin", "clientName": "emm",
"usernameLength":30, "owner": "admin@carbon.super",
"dynamicClientAppRegistrationServiceURL": "%https.ip%/dynamic-client-web/register",
"apiManagerClientAppRegistrationServiceURL": "%https.ip%/api-application-registration/register/tenants",
"grantType": "password refresh_token urn:ietf:params:oauth:grant-type:saml2-bearer",
"tokenScope": "admin",
"callbackUrl": "%https.ip%/api/device-mgt/v1.0"
},
"tokenServiceURL": "%https.ip%/oauth2/token"
},
"adminUser": "admin@carbon.super",
"adminRole": "admin",
"usernameLength": 30,
"pageSize":10, "pageSize":10,
"ssoConfiguration" : { "ssoConfiguration" : {
"enabled" : false, "enabled" : false,

@ -1,3 +1,4 @@
{{unit "cdmf.unit.lib.qrcode"}}
{{#zone "content"}} {{#zone "content"}}
{{#if permissions.VIEW_DASHBOARD}} {{#if permissions.VIEW_DASHBOARD}}
{{#if permissions.LIST_DEVICES}} {{#if permissions.LIST_DEVICES}}
@ -47,7 +48,7 @@
View View
</a> </a>
{{#if permissions.ADD_POLICY}} {{#if permissions.ADD_POLICY}}
<a href="/emm/policies/add-policy"> <a href="/emm/policy/add">
<span class="fw-stack"> <span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i> <i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i> <i class="fw fw-add fw-stack-1x"></i>
@ -78,7 +79,7 @@
View View
</a> </a>
{{#if permissions.ADD_USER}} {{#if permissions.ADD_USER}}
<a href="/emm/users/add-user"> <a href="/emm/user/add">
<span class="fw-stack"> <span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i> <i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i> <i class="fw fw-add fw-stack-1x"></i>
@ -109,7 +110,7 @@
View View
</a> </a>
{{#if permissions.ADD_ROLE}} {{#if permissions.ADD_ROLE}}
<a href="/emm/roles/add-role"> <a href="/emm/role/add">
<span class="fw-stack"> <span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i> <i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-add fw-stack-1x"></i> <i class="fw fw-add fw-stack-1x"></i>
@ -131,15 +132,12 @@
<div class="content"> <div class="content">
<div class="row"> <div class="row">
<div class="col-lg-5 col-md-6 col-centered"> <div class="col-lg-5 col-md-6 col-centered">
<h3> <h3>Scan QR code to start enrollment</h3>
Scan QR code to start enrollment
</h3>
<h4> <h4>
Please scan the QR code using your mobile device to retrieve enrollment URL. Please scan the QR code using your mobile device to retrieve enrollment URL.
</h4> </h4>
<div class="panel panel-default"> <div class="panel panel-default">
<div class="panel-body col-centered "> <div class="panel-body col-centered text-center">
<div class="qr-code"></div> <div class="qr-code"></div>
</div> </div>
</div> </div>
@ -150,5 +148,4 @@
{{/zone}} {{/zone}}
{{#zone "bottomJs"}} {{#zone "bottomJs"}}
{{js "js/dashboard.js"}} {{js "js/dashboard.js"}}
{{js "js/jquery.qrcode.min.js"}}
{{/zone}} {{/zone}}

@ -17,7 +17,7 @@
*/ */
function onRequest(context) { function onRequest(context) {
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var generalConfig = context.app.conf["generalConfig"]; var generalConfig = context.app.conf["generalConfig"];
context["permissions"] = userModule.getUIPermissions(); context["permissions"] = userModule.getUIPermissions();

@ -56,9 +56,3 @@ $(document).ready(function () {
updateStats("/api/device-mgt/v1.0/roles?offset=0&limit=1", "#role-count"); updateStats("/api/device-mgt/v1.0/roles?offset=0&limit=1", "#role-count");
} }
}); });
function toggleEnrollment() {
$(".modalpopup-content").html($("#qr-code-modal").html());
generateQRCode(".modalpopup-content .qr-code");
showPopup();
}

@ -1,6 +1,6 @@
function onRequest(context) { function onRequest(context) {
// var log = new Log("platform-configuration-unit backend js"); // var log = new Log("platform-configuration-unit backend js");
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var typesListResponse = userModule.getPlatforms(); var typesListResponse = userModule.getPlatforms();
if (typesListResponse["status"] == "success") { if (typesListResponse["status"] == "success") {
context["types"] = typesListResponse["content"]; context["types"] = typesListResponse["content"];

@ -19,7 +19,7 @@
function onRequest(context) { function onRequest(context) {
var log = new Log("policy-view-edit-unit backend js"); var log = new Log("policy-view-edit-unit backend js");
log.debug("calling policy-view-edit-unit"); log.debug("calling policy-view-edit-unit");
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
context.roles = userModule.getRoles().content; context.roles = userModule.getRoles().content;
context.users = userModule.getUsersByUsername().content; context.users = userModule.getUsersByUsername().content;
return context; return context;

@ -19,7 +19,7 @@
function onRequest(context) { function onRequest(context) {
var log = new Log("policy-view-edit-unit backend js"); var log = new Log("policy-view-edit-unit backend js");
log.debug("calling policy-view-edit-unit"); log.debug("calling policy-view-edit-unit");
var userModule = require("/app/modules/user.js").userModule; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
context.roles = userModule.getRoles().content; context.roles = userModule.getRoles().content;
return context; return context;
} }

@ -17,7 +17,7 @@
*/ */
function onRequest(context) { function onRequest(context) {
var userModule = require("/app/modules/user.js")["userModule"]; var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var utility = require('/app/modules/utility.js').utility; var utility = require('/app/modules/utility.js').utility;
var response = userModule.getRoles(); var response = userModule.getRoles();
var wizardPage = {}; var wizardPage = {};

@ -0,0 +1,110 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{#zone "navMenu-icon"}}
<span class="icon fw-stack">
<i class="fw fw-tiles fw-stack-1x toggle-icon-up"></i>
</span>
{{/zone}}
{{#zone "navMenu-items"}}
{{#if permissions.VIEW_DASHBOARD}}
<li>
<a href="{{@app.context}}">
<i class="fw fw-dashboard"></i>
Admin Dashboard
</a>
</li>
{{/if}}
{{#if permissions.LIST_DEVICES_ADMIN}}
<li>
<a href="{{@app.context}}/devices">
<i class="fw fw-mobile"></i>
Device Management
</a>
</li>
{{else}}
{{#if permissions.LIST_OWN_DEVICES}}
<li>
<a href="{{@app.context}}/devices">
<i class="fw fw-mobile"></i>
Device Management
</a>
</li>
{{/if}}
{{/if}}
<li><a><i class="fw fw-user"></i>User Management</a>
<ul>
{{#if permissions.LIST_USERS}}
<li><a href="{{@app.context}}/users"><i class="fw fw-user"></i>Users</a></li>
{{/if}}
{{#if permissions.LIST_ROLES}}
<li><a href="{{@app.context}}/roles"><i class="fw fw-bookmark"></i>Roles</a></li>
{{/if}}
</ul>
</li>
{{#if permissions.LIST_POLICIES}}
<li><a href="{{@app.context}}/policies"><i class="fw fw-policy"></i>Policy Management</a></li>
{{/if}}
<li><a><i class="fw fw-settings"></i>Configuration Management</a>
<ul>
{{#if permissions.TENANT_CONFIGURATION}}
<li><a href="{{@app.context}}/platform-configuration"><i class="fw fw-service"></i>Platform Configurations</a>
</li>
{{/if}}
<!-- todo change the permission and get the related permission -->
{{#if permissions.TENANT_CONFIGURATION}}
<li><a href="{{@app.context}}/certificates"><i class="fw fw-security-policy"></i>Certificate Configurations</a>
</li>
{{/if}}
</ul>
</li>
{{/zone}}
{{#zone "navbarCollapsableRightItems"}}
<ul id="notification-bubble-wrapper" class="nav navbar-nav navbar-right">
<li class="visible-inline-block">
<!--<a href="{{appContext}}notification-listing" title="Failures of operations on the device side will be listed here">-->
<a data-toggle="sidebar" data-target="#right-sidebar" data-container=".page-content"
aria-expanded="false" rel="notifications-sidebar">
<span class="icon fw-stack">
<i class="fw fw-notification fw-stack-1x"></i>
</span>
<span class="hidden-xs">Notifications</span>
<span class="badge notifications" id="notification-bubble"></span>
</a>
</li>
</ul>
{{/zone}}
{{#zone "sidePanes"}}
<div class="sidebar-wrapper" id="right-sidebar" is-authorized="{{isAuthorizedForNotifications}}"
data-side="right" data-width="320" data-sidebar-fixed="true" data-fixed-offset="50" data-spy="affix"
data-offset-top="80">
<ul class="sidebar-messages">
</ul>
<h4 class="text-center"><a href="{{appContext}}notification-listing" class="text-center">Show all notifications</a>
</h4>
</div>
{{/zone}}
{{#zone "bottomJs"}}
<script id="notifications" data-current-user="{{currentUser.username}}"
data-image-resource="{{self.publicURL}}/images/" src="{{self.publicURL}}/templates/notifications.hbs"
type="text/x-handlebars-template"></script>
{{js "js/nav-menu.js"}}
{{/zone}}

@ -0,0 +1,56 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
context.handlebars.registerHelper('equal', function (lvalue, rvalue, options) {
if (arguments.length < 3) {
throw new Error("Handlebars Helper equal needs 2 parameters");
}
if (lvalue != rvalue) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
var mdmProps = require('/app/conf/reader/main.js')["conf"];
var constants = require("/app/modules/constants.js");
var uiPermissions = userModule.getUIPermissions();
context["permissions"] = uiPermissions;
var links = {
"user-mgt": [],
"role-mgt": [],
"policy-mgt": [],
"device-mgt": []
};
// following context.link value comes here based on the value passed at the point
// where units are attached to a page zone.
// eg: {{unit "appbar" pageLink="users" title="User Management"}}
context["currentActions"] = links[context["pageLink"]];
context["enrollmentURL"] = mdmProps["generalConfig"]["host"] + mdmProps["enrollmentDir"];
var isAuthorizedForNotifications =
userModule.isAuthorized("/permission/admin/device-mgt/emm-admin/notifications/view");
var currentUser = session.get(constants["USER_SESSION_KEY"]);
context["isAuthorizedForNotifications"] = isAuthorizedForNotifications;
context["currentUser"] = currentUser;
context["appContext"] = mdmProps["appContext"];
return context;
}

@ -0,0 +1,351 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var modalPopup = ".wr-modalpopup",
modalPopupContainer = modalPopup + " .modalpopup-container",
modalPopupContent = modalPopup + " .modalpopup-content";
var emmAdminBasePath = "/api/device-mgt/v1.0";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
var maxHeight = "max-height";
var marginTop = "margin-top";
var body = "body";
$(modalPopupContent).css(maxHeight, ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css(marginTop, (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
}
/*
* hide popup function.
*/
function hidePopup() {
$(modalPopupContent).html("");
$(modalPopupContent).removeClass("operation-data");
$(modalPopup).hide();
}
var updateNotificationCount = function (data, textStatus, jqXHR) {
if (jqXHR.status == 200 && data) {
var responsePayload = JSON.parse(data);
var newNotificationsCount = responsePayload.count;
if (newNotificationsCount > 0) {
$("#notification-bubble").html(newNotificationsCount);
}
// } else {
// $("#notification-bubble").html("Error");
// }
}
};
function loadNotificationsPanel() {
if ("true" == $("#right-sidebar").attr("is-authorized")) {
var serviceURL = emmAdminBasePath + "/notifications?status=NEW";
invokerUtil.get(serviceURL, updateNotificationCount, hideNotificationCount);
loadNewNotifications();
} else {
$("#notification-bubble-wrapper").remove();
}
}
function hideNotificationCount(jqXHR) {
if (jqXHR.status == 404) {
// this means "no new notifications to show"
$("#notification-bubble").hide();
} else {
$("#notification-bubble").html("Error");
}
}
function loadNewNotifications() {
var messageSideBar = ".sidebar-messages";
if ($("#right-sidebar").attr("is-authorized") == "true") {
var notifications = $("#notifications");
var currentUser = notifications.data("currentUser");
$.template("notification-listing", notifications.attr("src"), function (template) {
var serviceURL = emmAdminBasePath + "/notifications?status=NEW";
var successCallback = function (data, textStatus, jqXHR) {
if (jqXHR.status == 200 && data) {
var viewModel = {};
var responsePayload = JSON.parse(data);
if (responsePayload.notifications) {
viewModel.notifications = responsePayload.notifications;
if (responsePayload.count > 0) {
$(messageSideBar).html(template(viewModel));
} else {
$(messageSideBar).html("<h4 class='text-center'>No new notifications found...</h4>");
}
} else {
$(messageSideBar).html("<h4 class ='message-danger'>Unexpected error occurred while loading new notifications.</h4>");
}
}
};
var errorCallback = function (jqXHR) {
if (jqXHR.status = 500) {
$(messageSideBar).html("<h4 class ='message-danger'>Unexpected error occurred while trying " +
"to retrieve any new notifications.</h4>");
}
};
invokerUtil.get(serviceURL, successCallback, errorCallback);
});
} else {
$(messageSideBar).html("<h4 class ='message-danger'>You are not authorized to view notifications</h4>");
}
}
/**
* Toggle function for
* notification listing sidebar.
* @return {Null}
*/
$.sidebar_toggle = function (action, target, container) {
var elem = '[data-toggle=sidebar]',
button,
containerOffsetLeft,
containerOffsetRight,
targetOffsetLeft,
targetOffsetRight,
targetWidth,
targetSide,
relationship,
pushType,
buttonParent;
var sidebar_window = {
update: function (target, container, button) {
containerOffsetLeft = $(container).data('offset-left') ? $(container).data('offset-left') : 0;
containerOffsetRight = $(container).data('offset-right') ? $(container).data('offset-right') : 0;
targetOffsetLeft = $(target).data('offset-left') ? $(target).data('offset-left') : 0;
targetOffsetRight = $(target).data('offset-right') ? $(target).data('offset-right') : 0;
targetWidth = $(target).data('width');
targetSide = $(target).data("side");
pushType = $(container).parent().is('body') == true ? 'padding' : 'margin';
if (button !== undefined) {
relationship = button.attr('rel') ? button.attr('rel') : '';
buttonParent = $(button).parent();
}
},
show: function () {
if ($(target).data('sidebar-fixed') == true) {
$(target).height($(window).height() - $(target).data('fixed-offset'));
}
$(target).trigger('show.sidebar');
if (targetWidth !== undefined) {
$(target).css('width', targetWidth);
}
$(target).addClass('toggled');
if (button !== undefined) {
if (relationship !== '') {
// Removing active class from all relative buttons
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
}
// Adding active class to button
if (button.attr('data-handle') !== 'close') {
button.addClass("active");
button.attr('aria-expanded', 'true');
}
if (buttonParent.is('li')) {
if (relationship !== '') {
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().
attr('aria-expanded', 'false');
}
buttonParent.addClass("active");
buttonParent.attr('aria-expanded', 'true');
}
}
// Sidebar open function
if (targetSide == 'left') {
if ((button !== undefined) && (button.attr('data-container-divide'))) {
$(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetLeft);
}
$(target).css(targetSide, targetOffsetLeft);
} else if (targetSide == 'right') {
if ((button !== undefined) && (button.attr('data-container-divide'))) {
$(container).css(pushType + '-' + targetSide, targetWidth + targetOffsetRight);
}
$(target).css(targetSide, targetOffsetRight);
}
$(target).trigger('shown.sidebar');
},
hide: function () {
$(target).trigger('hide.sidebar');
$(target).removeClass('toggled');
if (button !== undefined) {
if (relationship !== '') {
// Removing active class from all relative buttons
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').removeClass("active");
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').attr('aria-expanded', 'false');
}
// Removing active class from button
if (button.attr('data-handle') !== 'close') {
button.removeClass("active");
button.attr('aria-expanded', 'false');
}
if ($(button).parent().is('li')) {
if (relationship !== '') {
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().removeClass("active");
$(elem + '[rel=' + relationship + ']:not([data-handle=close])').parent().
attr('aria-expanded', 'false');
}
}
}
// Sidebar close function
if (targetSide == 'left') {
if ((button !== undefined) && (button.attr('data-container-divide'))) {
$(container).css(pushType + '-' + targetSide, targetOffsetLeft);
}
$(target).css(targetSide, -Math.abs(targetWidth + targetOffsetLeft));
} else if (targetSide == 'right') {
if ((button !== undefined) && (button.attr('data-container-divide'))) {
$(container).css(pushType + '-' + targetSide, targetOffsetRight);
}
$(target).css(targetSide, -Math.abs(targetWidth + targetOffsetRight));
}
$(target).trigger('hidden.sidebar');
}
};
if (action === 'show') {
sidebar_window.update(target, container);
sidebar_window.show();
}
if (action === 'hide') {
sidebar_window.update(target, container);
sidebar_window.hide();
}
// binding click function
var body = 'body';
$(body).off('click', elem);
$(body).on('click', elem, function (e) {
e.preventDefault();
button = $(this);
container = button.data('container');
target = button.data('target');
sidebar_window.update(target, container, button);
/**
* Sidebar function on data container divide
* @return {Null}
*/
if (button.attr('aria-expanded') == 'false') {
sidebar_window.show();
} else if (button.attr('aria-expanded') == 'true') {
sidebar_window.hide();
}
});
};
$.fn.collapse_nav_sub = function () {
var navSelector = 'ul.nav';
if (!$(navSelector).hasClass('collapse-nav-sub')) {
$(navSelector + ' > li', this).each(function () {
var position = $(this).offset().left - $(this).parent().scrollLeft();
$(this).attr('data-absolute-position', (position + 5));
});
$(navSelector + ' li', this).each(function () {
if ($('ul', this).length !== 0) {
$(this).addClass('has-sub');
}
});
$(navSelector + ' > li', this).each(function () {
$(this).css({
'left': $(this).data('absolute-position'),
'position': 'absolute'
});
});
$(navSelector + ' li.has-sub', this).on('click', function () {
var elem = $(this);
if (elem.attr('aria-expanded') !== 'true') {
elem.siblings().fadeOut(100, function () {
elem.animate({'left': '15'}, 200, function () {
$(elem).first().children('ul').fadeIn(200);
});
});
elem.siblings().attr('aria-expanded', 'false');
elem.attr('aria-expanded', 'true');
} else {
$(elem).first().children('ul').fadeOut(100, function () {
elem.animate({'left': $(elem).data('absolute-position')}, 200, function () {
elem.siblings().fadeIn(100);
});
});
elem.siblings().attr('aria-expanded', 'false');
elem.attr('aria-expanded', 'false');
}
});
$(navSelector + ' > li.has-sub ul', this).on('click', function (e) {
e.stopPropagation();
});
$(navSelector).addClass('collapse-nav-sub');
}
};
$(document).ready(function () {
loadNotificationsPanel();
$.sidebar_toggle();
$("#right-sidebar").on("click", ".new-notification", function () {
var notificationId = $(this).data("id");
var redirectUrl = $(this).data("url");
var markAsReadNotificationsAPI = "/mdm-admin/notifications/" + notificationId + "/CHECKED";
var messageSideBar = ".sidebar-messages";
invokerUtil.put(
markAsReadNotificationsAPI,
null,
function (data) {
data = JSON.parse(data);
if (data.statusCode == responseCodes["ACCEPTED"]) {
location.href = redirectUrl;
}
}, function () {
var content = "<li class='message message-danger'><h4><i class='icon fw fw-error'></i>Warning</h4>" +
"<p>Unexpected error occurred while loading notification. Please refresh the page and" +
" try again</p></li>";
$(messageSideBar).html(content);
}
);
});
if (typeof $.fn.collapse == 'function') {
$('.navbar-collapse.tiles').on('shown.bs.collapse', function () {
$(this).collapse_nav_sub();
});
}
});

@ -0,0 +1,14 @@
{{#each notifications}}
<li class="message message-info" data-type="selectable" >
<h4>
<i class="icon fw fw-info"></i>
<a href="device?type={{deviceIdentifier.type}}&id={{deviceIdentifier.id}}"
data-id="{{notificationId}}"
data-url="device?type={{deviceIdentifier.type}}&id={{deviceIdentifier.id}}"
class="new-notification" data-click-event="remove-form">
Device Type : {{deviceIdentifier.type}}
</a>
</h4>
<p>{{description}}</p>
</li>
{{/each}}

@ -1,4 +1,4 @@
instructions.configure = \ instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.adapter_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.adapter_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.adapter_${feature.version}/websocket-validation.properties,target:${installFolder}/../../conf/etc/websocket-validation.properties,overwrite:true);\ org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.adapter_${feature.version}/websocket-validation.xml,target:${installFolder}/../../conf/etc/websocket-validation.xml,overwrite:true);\

@ -1,25 +0,0 @@
#
# Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# WSO2 Inc. licenses this file to you under the Apache License,
# Version 2.0 (the "License"); you may not use this file except
# in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#This hold the properties that is used for token validation for the the websocket
tokenValidationEndpoint=https://localhost:9443/services/OAuth2TokenValidationService
username=admin
password=admin
maximumHttpConnectionPerHost=2
maximumTotalHttpConnection=100

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ you may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This configuration file represents the configuration that are needed
for websocket connection validation
-->
<WebsocketValidationConfigs>
<!--Authenticator is holds the information of authticator that is used for websocket-->
<Authenticator class="org.wso2.carbon.device.mgt.iot.output.adapter.ui.authentication.OAuthAuthenticator">
<Properties>
<Property name="tokenValidationEndpoint">https://localhost:9443/services/OAuth2TokenValidationService</Property>
<Property name="username">admin</Property>
<Property name="password">admin</Property>
<Property name="maximumHttpConnectionPerHost">2</Property>
<Property name="maximumTotalHttpConnection">100</Property>
</Properties>
</Authenticator>
<!--Authorizer holds the information of the authorizer that is used authorize a connection.-->
<Authorizer class="org.wso2.carbon.device.mgt.iot.output.adapter.ui.authorization.DeviceAuthorizer"></Authorizer>
</WebsocketValidationConfigs>
Loading…
Cancel
Save