Added push notification support for device types

revert-dabc3590
ayyoob 9 years ago
parent 562ac197af
commit 6c24f44abc

@ -21,7 +21,6 @@
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/android_sense/+/data</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>

@ -30,7 +30,9 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
@ -52,6 +54,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* The api for
@ -59,6 +62,7 @@ import java.util.Map;
public class AndroidSenseServiceImpl implements AndroidSenseService {
private static Log log = LogFactory.getLog(AndroidSenseServiceImpl.class);
private static String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
@Path("device/{deviceId}/words")
@POST
@ -68,16 +72,31 @@ public class AndroidSenseServiceImpl implements AndroidSenseService {
AndroidSenseConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + AndroidSenseConstants.DEVICE_TYPE + "/" + deviceId + "/command/words";
dynamicProperties.put(AndroidSenseConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(AndroidSenseConstants.MQTT_ADAPTER_NAME,
dynamicProperties, keywords);
Operation commandOp = new CommandOperation();
commandOp.setCode("keywords");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(keywords);
Properties props = new Properties();
props.setProperty(AndroidSenseConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, AndroidSenseConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(AndroidSenseConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while executing command operation to send keywords";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -89,15 +108,30 @@ public class AndroidSenseServiceImpl implements AndroidSenseService {
AndroidSenseConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + AndroidSenseConstants.DEVICE_TYPE + "/" + deviceId + "/command/threshold";
dynamicProperties.put(AndroidSenseConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(AndroidSenseConstants.MQTT_ADAPTER_NAME,
dynamicProperties, threshold);
Operation commandOp = new CommandOperation();
commandOp.setCode("threshold");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(threshold);
Properties props = new Properties();
props.setProperty(AndroidSenseConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, AndroidSenseConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(AndroidSenseConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while executing command operation to set threashold";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -109,16 +143,31 @@ public class AndroidSenseServiceImpl implements AndroidSenseService {
AndroidSenseConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + AndroidSenseConstants.DEVICE_TYPE + "/" + deviceId + "/command/remove";
dynamicProperties.put(AndroidSenseConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(AndroidSenseConstants.MQTT_ADAPTER_NAME,
dynamicProperties, words);
Operation commandOp = new CommandOperation();
commandOp.setCode("remove");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(words);
Properties props = new Properties();
props.setProperty(AndroidSenseConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, AndroidSenseConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(AndroidSenseConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while executing command operation to remove words";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -236,7 +285,7 @@ public class AndroidSenseServiceImpl implements AndroidSenseService {
if (added) {
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getServerUrl());
}

@ -66,9 +66,8 @@
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.core.util,
org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception,
org.wso2.carbon.ndatasource.core
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal,
@ -110,8 +109,8 @@
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -25,18 +25,6 @@ public class AndroidSenseConstants {
public final static String DEVICE_TYPE = "android_sense";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "ANDROID_DEVICE_ID";
//Android Sense Stream definitions.
public static final String ACCELEROMETER_STREAM_DEFINITION = "org.wso2.iot.devices.accelerometer";
public static final String BATTERY_STREAM_DEFINITION = "org.wso2.iot.devices.battery";
public static final String GPS_STREAM_DEFINITION = "org.wso2.iot.devices.gps";
public static final String GRAVITY_STREAM_DEFINITION = "org.wso2.iot.devices.gravity";
public static final String GYROSCOPE_STREAM_DEFINITION = "org.wso2.iot.devices.gyroscope";
public static final String LIGHT_STREAM_DEFINITION = "org.wso2.iot.devices.light";
public static final String MAGNETIC_STREAM_DEFINITION = "org.wso2.iot.devices.magnetic";
public static final String PRESSURE_STREAM_DEFINITION = "org.wso2.iot.devices.pressure";
public static final String PROXIMITY_STREAM_DEFINITION = "org.wso2.iot.devices.proximity";
public static final String ROTATION_STREAM_DEFINITION = "org.wso2.iot.devices.rotation";
public static final String WORD_COUNT_STREAM_DEFINITION = "org.wso2.iot.devices.wordcount";
//Android Sensor names
public static final String SENSOR_ACCELEROMETER = "accelerometer";
@ -51,30 +39,9 @@ public class AndroidSenseConstants {
public static final String SENSOR_ROTATION = "rotation";
public static final String SENSOR_WORDCOUNT = "wordcounter";
//MQTT Subscribe topic
public static final String MQTT_SUBSCRIBE_WORDS_TOPIC = "wso2/+/android_sense/+/data";
public static final String DATA_SOURCE_NAME = "jdbc/AndroidSenseDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants
public static final String MQTT_ADAPTER_NAME = "android_sense_mqtt";
public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt";
public static final String ADAPTER_TOPIC_PROPERTY = "topic";
public static final String MQTT_PORT = "\\$\\{mqtt.broker.port\\}";
public static final String MQTT_BROKER_HOST = "\\$\\{mqtt.broker.host\\}";
public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset";
public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip";
public static final int CARBON_DEFAULT_PORT_OFFSET = 0;
public static final int DEFAULT_MQTT_PORT = 1883;
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String DCR_PROPERTY_KEY = "dcrUrl";
public static final String BROKER_URL_PROPERTY_KEY = "url";
public static final String SCOPES_PROPERTY_KEY = "scopes";
public static final String QOS_PROPERTY_KEY = "qos";
public static final String CLIENT_ID_PROPERTY_KEY = "qos";
public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession";
public static final String TOPIC = "topic";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
}

@ -20,6 +20,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal.AndroidSenseManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -39,11 +41,16 @@ public class AndroidSenseDAOUtil {
}
public static void initAndroidDAO() {
DeviceManagementConfiguration deviceManagementConfiguration = AndroidSenseManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(AndroidSenseConstants.DEVICE_TYPE,
AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(AndroidSenseConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + AndroidSenseConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
}
}

@ -1,46 +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.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import java.io.IOException;
/**
* Startup listener to create an output adapter after server starts up.
*/
public class AndroidSenseStartupListener implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(AndroidSenseStartupListener.class);
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
try {
AndroidSenseUtils.setupMqttOutputAdapter();
} catch (IOException e) {
log.error("Failed to intilaize the virtual firealarm output adapter", e);
}
}
}

@ -24,6 +24,7 @@ import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal.AndroidSenseManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.event.output.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
@ -82,97 +83,24 @@ public class AndroidSenseUtils {
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws AndroidSenseDeviceMgtPluginException {
DeviceManagementConfiguration deviceManagementConfiguration = AndroidSenseManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(AndroidSenseConstants.DEVICE_TYPE,
AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(AndroidSenseConstants.DATA_SOURCE_NAME);
DataSource dataSource = (DataSource) ctx.lookup(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + AndroidSenseConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
} catch (Exception e) {
throw new AndroidSenseDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
public static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(AndroidSenseConstants.MQTT_ADAPTER_NAME,
AndroidSenseConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
AndroidSenseManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + AndroidSenseConstants.MQTT_ADAPTER_NAME, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Create Output Event Adapter Configuration for given configuration.
*
* @param name Output Event Adapter name
* @param type Output Event Adapter type
* @param msgFormat Output Event Adapter message format
* @return OutputEventAdapterConfiguration instance for given configuration
*/
private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);
outputEventAdapterConfiguration.setMessageFormat(msgFormat);
File configFile = new File(AndroidSenseConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
Map<String, String> mqttAdapterProperties = new HashMap<>();
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
mqttAdapterProperties.put(AndroidSenseConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
AndroidSenseConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(AndroidSenseConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(AndroidSenseConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(AndroidSenseConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(AndroidSenseConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(AndroidSenseConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
AndroidSenseConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(AndroidSenseConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
AndroidSenseConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(AndroidSenseConstants.QOS_PROPERTY_KEY, properties.getProperty(
AndroidSenseConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(AndroidSenseConstants.CLIENT_ID_PROPERTY_KEY, "");
outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties);
}
return outputEventAdapterConfiguration;
}
public static String replaceMqttProperty(String urlWithPlaceholders) {
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(AndroidSenseConstants.MQTT_PORT, "" +
(AndroidSenseConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(AndroidSenseConstants.MQTT_BROKER_HOST,
System.getProperty(AndroidSenseConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
return urlWithPlaceholders;
}
private static int getPortOffset() {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
AndroidSenseConstants.CARBON_CONFIG_PORT_OFFSET));
try {
if ((portOffset != null)) {
return Integer.parseInt(portOffset.trim());
} else {
return AndroidSenseConstants.CARBON_DEFAULT_PORT_OFFSET;
}
} catch (NumberFormatException e) {
return AndroidSenseConstants.CARBON_DEFAULT_PORT_OFFSET;
}
}
}

@ -18,15 +18,14 @@
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
/**
* DataHolder class of plugins component.
*/
public class AndroidSenseManagementDataHolder {
private OutputEventAdapterService outputEventAdapterService;
private DeviceTypeConfigService deviceTypeConfigService;
private static AndroidSenseManagementDataHolder thisInstance = new AndroidSenseManagementDataHolder();
private AndroidSenseManagementDataHolder() {
@ -36,13 +35,13 @@ public class AndroidSenseManagementDataHolder {
return thisInstance;
}
public OutputEventAdapterService getOutputEventAdapterService() {
return outputEventAdapterService;
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setOutputEventAdapterService(
OutputEventAdapterService outputEventAdapterService) {
this.outputEventAdapterService = outputEventAdapterService;
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
}

@ -21,30 +21,28 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.AndroidSenseManagerService;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.util.AndroidSenseStartupListener;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.util.AndroidSenseUtils;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.android.internal.AndroidSenseManagementServiceComponent"
* immediate="true"
* @scr.reference name="event.output.adapter.service"
* interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOutputEventAdapterService"
* unbind="unsetOutputEventAdapterService"
* @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="devicetype.configuration.service"
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeConfigService"
* unbind="unsetDeviceTypeConfigService"
*/
public class AndroidSenseManagementServiceComponent {
@ -59,8 +57,6 @@ public class AndroidSenseManagementServiceComponent {
BundleContext bundleContext = ctx.getBundleContext();
androidServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), new AndroidSenseManagerService(), null);
bundleContext.registerService(ServerStartupObserver.class.getName(), new AndroidSenseStartupListener(),
null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
@ -99,22 +95,6 @@ public class AndroidSenseManagementServiceComponent {
}
}
/**
* Initialize the Output EventAdapter Service dependency
*
* @param outputEventAdapterService Output EventAdapter Service reference
*/
protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
AndroidSenseManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
AndroidSenseManagementDataHolder.getInstance().setOutputEventAdapterService(null);
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
@ -126,4 +106,12 @@ public class AndroidSenseManagementServiceComponent {
protected void unsetDataSourceService(DataSourceService dataSourceService) {
//do nothing
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
AndroidSenseManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
AndroidSenseManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

@ -1,60 +0,0 @@
/*
* 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.androidsense.plugin.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.util.AndroidSenseUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MqttConfig {
private static String brokerEndpoint;
private static MqttConfig mqttConfig = new MqttConfig();
private static final Log log = LogFactory.getLog(MqttConfig.class);
private MqttConfig() {
File configFile = new File(AndroidSenseConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
brokerEndpoint = AndroidSenseUtils.replaceMqttProperty(
properties.getProperty(AndroidSenseConstants.BROKER_URL_PROPERTY_KEY));
} catch (IOException e) {
log.error("Failed to read the mqtt.properties file" + e);
}
}
}
public static MqttConfig getInstance() {
return mqttConfig;
}
public String getBrokerEndpoint() {
return brokerEndpoint;
}
}

@ -20,7 +20,6 @@
<from eventAdapterType="oauth-http">
<property name="maximumHttpConnectionPerHost">2</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.http.util.HTTPContentValidator</property>
<property name="contentTransformer">default</property>
<property name="transports">all</property>

@ -34,6 +34,9 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
@ -62,6 +65,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.UUID;
public class ArduinoServiceImpl implements ArduinoService {
@ -80,19 +84,25 @@ public class ArduinoServiceImpl implements ArduinoService {
ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase();
if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId, deviceControlList);
} else {
deviceControlList.add(operation);
}
Operation commandOp = new CommandOperation();
commandOp.setCode("bulb");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(operation);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, ArduinoConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(ArduinoConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.status(Response.Status.OK.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while executing command operation upon ringing the buzzer";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -106,9 +116,11 @@ public class ArduinoServiceImpl implements ArduinoService {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
String result;
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
Operation operation = APIUtil.getDeviceManagementService()
.getNextPendingOperation(new DeviceIdentifier(deviceId, ArduinoConstants.DEVICE_TYPE));
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (deviceControlList == null) {
if (operation == null) {
result = "No controls have been set for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
@ -116,9 +128,13 @@ public class ArduinoServiceImpl implements ArduinoService {
return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(result).build();
} else {
try {
result = deviceControlList.remove();
if (log.isDebugEnabled()) {
log.debug(result);
if (operation.getType() == Operation.Type.COMMAND) {
result = (String) operation.getPayLoad();
if (log.isDebugEnabled()) {
log.debug(result);
}
} else {
result = "No controls have been found";
}
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build();
} catch (NoSuchElementException ex) {
@ -132,6 +148,10 @@ public class ArduinoServiceImpl implements ArduinoService {
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while retriving operation";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -211,6 +231,11 @@ public class ArduinoServiceImpl implements ArduinoService {
}
//create new device id
String deviceId = shortUUID();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
if (apiApplicationKey == null) {
@ -220,18 +245,13 @@ public class ArduinoServiceImpl implements ArduinoService {
ArduinoConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "arduino_device device_type_" + ArduinoConstants.DEVICE_TYPE + " device_" + deviceId;
String scopes = "arduino_device cdmf/" + ArduinoConstants.DEVICE_TYPE + "/" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
ArduinoConstants.DEVICE_TYPE, deviceId, deviceName, accessToken, refreshToken);

@ -70,7 +70,8 @@
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.ndatasource.core
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
@ -112,5 +113,9 @@
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -21,19 +21,11 @@ package org.wso2.carbon.device.mgt.iot.arduino.plugin.constants;
public class ArduinoConstants {
public final static String DEVICE_TYPE = "arduino";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
public final static String DEVICE_PLUGIN_DEVICE_ID = "ARDUINO_DEVICE_ID";
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
public static final String URL_PREFIX = "http://";
public static final String BULB_CONTEXT = "/BULB/";
public static final String SONAR_CONTEXT = "/HUMIDITY/";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
//type of the sensor
public static final String SENSOR_TEMPERATURE = "temperature";
//sensor events summerized table name
public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY";
public static final String DATA_SOURCE_NAME = "jdbc/ArduinoDM_DB";
}

@ -22,6 +22,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.internal.ArduinoManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -41,11 +43,16 @@ public class ArduinoDAOUtil {
}
public static void initArduinoDAO() {
DeviceManagementConfiguration deviceManagementConfiguration = ArduinoManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(ArduinoConstants.DEVICE_TYPE,
ArduinoConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(ArduinoConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + ArduinoConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
}
}

@ -23,6 +23,8 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.internal.ArduinoManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -94,15 +96,20 @@ public class ArduinoUtils {
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws ArduinoDeviceMgtPluginException {
DeviceManagementConfiguration deviceManagementConfiguration = ArduinoManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(ArduinoConstants.DEVICE_TYPE,
ArduinoConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(ArduinoConstants.DATA_SOURCE_NAME);
DataSource dataSource = (DataSource) ctx.lookup(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + ArduinoConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
} catch (Exception e) {
throw new ArduinoDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);

@ -0,0 +1,47 @@
/*
* 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.arduino.plugin.internal;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
/**
* DataHolder class of plugins component.
*/
public class ArduinoManagementDataHolder {
private DeviceTypeConfigService deviceTypeConfigService;
private static ArduinoManagementDataHolder thisInstance = new ArduinoManagementDataHolder();
private ArduinoManagementDataHolder() {
}
public static ArduinoManagementDataHolder getInstance() {
return thisInstance;
}
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
}

@ -27,6 +27,7 @@ import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.ArduinoManagerService;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.util.ArduinoUtils;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
/**
@ -38,6 +39,12 @@ import org.wso2.carbon.ndatasource.core.DataSourceService;
* policy="dynamic"
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="devicetype.configuration.service"
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeConfigService"
* unbind="unsetDeviceTypeConfigService"
*/
public class ArduinoManagementServiceComponent {
@ -103,4 +110,12 @@ public class ArduinoManagementServiceComponent {
protected void unsetDataSourceService(DataSourceService dataSourceService) {
//do nothing
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
ArduinoManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
ArduinoManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

@ -13,5 +13,5 @@ public interface ContentTransformer {
* @param dynamicProperties related to transport.
* @return transformed message
*/
Object transform(Object message, Map<String, String> dynamicProperties);
Object transform(Object message, Map<String, Object> dynamicProperties);
}

@ -25,9 +25,8 @@ import java.util.Map;
*/
public interface ContentValidator {
/**
* @param contentValidatorParams that related to input adapter.
* @param dynamicParameter that message.
* @return ContentInfo.
*/
ContentInfo validate(Object message, Map<String, String> contentValidatorParams, Map<String, String> dynamicParameter);
ContentInfo validate(Object message, Map<String, Object> dynamicParameter);
}

@ -8,7 +8,7 @@ import java.util.Map;
public class DefaultContentTransformer implements ContentTransformer{
@Override
public Object transform(Object message, Map<String, String> dynamicProperties) {
public Object transform(Object message, Map<String, Object> dynamicProperties) {
return message;
}
}

@ -8,7 +8,7 @@ import java.util.Map;
public class DefaultContentValidator implements ContentValidator {
@Override
public ContentInfo validate(Object message, Map<String, String> params, Map<String, String> dynamicParams) {
public ContentInfo validate(Object message, Map<String, Object> dynamicParams) {
return new ContentInfo(true, message);
}

@ -124,16 +124,6 @@ public class HTTPEventAdapterFactory extends InputEventAdapterFactory {
contentValidator.setDefaultValue(HTTPEventAdapterConstants.DEFAULT);
propertyList.add(contentValidator);
//Content Validator Params details
Property contentValidatorParams = new Property(HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
contentValidatorParams.setDisplayName(
resourceBundle.getString(HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS));
contentValidatorParams.setRequired(false);
contentValidatorParams.setHint(
resourceBundle.getString(HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT));
contentValidatorParams.setDefaultValue(HTTPEventAdapterConstants.HTTP_CONTENT_VALIDATION_DEFAULT_PARAMETERS);
propertyList.add(contentValidatorParams);
//Content Transformer details
Property contentTransformer = new Property(HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME);
contentTransformer.setDisplayName(

@ -51,7 +51,6 @@ public class HTTPMessageServlet extends HttpServlet {
private static Log log = LogFactory.getLog(HTTPMessageServlet.class);
private static Map<String, String> contentValidationProperties;
private static ContentValidator contentValidator;
private static ContentTransformer contentTransformer;
private InputEventAdapterListener eventAdaptorListener;
@ -66,18 +65,6 @@ public class HTTPMessageServlet extends HttpServlet {
this.tenantId = tenantId;
this.exposedTransports = eventAdapterConfiguration.getProperties().get(
HTTPEventAdapterConstants.EXPOSED_TRANSPORTS);
HTTPMessageServlet.contentValidationProperties = new HashMap<>();
String contentValidationParams = eventAdapterConfiguration.getProperties().get(
HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
if (contentValidationParams != null && !contentValidationParams.isEmpty()) {
String validationParams[] = contentValidationParams.split(",");
for (String validationParam : validationParams) {
String[] validationProperty = validationParam.split(":");
if (validationProperty.length == 2) {
contentValidationProperties.put(validationProperty[0], validationProperty[1]);
}
}
}
String className = eventAdapterConfiguration.getProperties().get(
HTTPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME);
@ -180,7 +167,7 @@ public class HTTPMessageServlet extends HttpServlet {
}
if (authenticationInfo != null) {
Map<String, String> paramMap = new HashMap<>();
Map<String, Object> paramMap = new HashMap<>();
Enumeration<String> reqParameterNames = req.getParameterNames();
while (reqParameterNames.hasMoreElements()) {
String paramterName = reqParameterNames.nextElement();
@ -188,9 +175,10 @@ public class HTTPMessageServlet extends HttpServlet {
}
paramMap.put(HTTPEventAdapterConstants.USERNAME_TAG, authenticationInfo.getUsername());
paramMap.put(HTTPEventAdapterConstants.TENANT_DOMAIN_TAG, authenticationInfo.getTenantDomain());
paramMap.put(HTTPEventAdapterConstants.SCOPE_TAG, authenticationInfo.getScopes());
if (contentValidator != null && contentTransformer != null) {
data = (String) contentTransformer.transform(data, paramMap);
ContentInfo contentInfo = contentValidator.validate(data, contentValidationProperties, paramMap);
ContentInfo contentInfo = contentValidator.validate(data, paramMap);
if (contentInfo != null && contentInfo.isValidContent()) {
HTTPEventAdapter.executorService.submit(new HTTPRequestProcessor(eventAdaptorListener,
(String) contentInfo.getMessage(), tenantId));

@ -119,6 +119,7 @@ public class OAuthAuthenticator {
RealmService realmService = InputAdapterServiceDataHolder.getRealmService();
int tenantId = realmService.getTenantManager().getTenantId(authenticationInfo.getTenantDomain());
authenticationInfo.setTenantId(tenantId);
authenticationInfo.setScopes(tokenValidationResponse.getScope());
} else {
if (log.isDebugEnabled()) {
log.debug("Token validation failed for token: " + token);

@ -26,6 +26,7 @@ public class AuthenticationInfo {
private String username;
private String tenantDomain;
private int tenantId;
private String[] scopes;
/**
* returns whether the client is authenticated
*/
@ -66,4 +67,12 @@ public class AuthenticationInfo {
public void setTenantId(int tenantId) {
this.tenantId = tenantId;
}
public String[] getScopes() {
return scopes;
}
public void setScopes(String[] scopes) {
this.scopes = scopes;
}
}

@ -27,23 +27,28 @@ import org.json.simple.parser.ParseException;
import org.wso2.carbon.device.mgt.iot.input.adapter.extension.ContentInfo;
import org.wso2.carbon.device.mgt.iot.input.adapter.extension.ContentValidator;
import java.util.List;
import java.util.Map;
public class HTTPContentValidator implements ContentValidator {
private static final Log log = LogFactory.getLog(HTTPContentValidator.class);
private static String JSON_ARRAY_START_CHAR = "[";
private static String CDMF_SCOPE_PREFIX = "cdmf";
private static String CDMF_SCOPE_SEPERATOR = "/";
@Override
public ContentInfo validate(Object msgPayload, Map<String, String> contentValidationParams,
Map<String, String> dynamicParams) {
String deviceId = dynamicParams.get("deviceId");
public ContentInfo validate(Object msgPayload, Map<String, Object> dynamicParams) {
String deviceId = (String) dynamicParams.get("deviceId");
String deviceType = (String) dynamicParams.get("deviceType");
String msg = (String) msgPayload;
String deviceIdJsonPath = contentValidationParams.get(HTTPEventAdapterConstants.DEVICE_ID_JSON_PATH);
String deviceIdJsonPath = HTTPEventAdapterConstants.DEVICE_ID_JSON_PATH;
boolean status;
if (msg.startsWith(JSON_ARRAY_START_CHAR)) {
status = processMultipleEvents(msg, deviceId, deviceIdJsonPath);
} else {
status = processSingleEvent(msg, deviceId, deviceIdJsonPath);
if (status = isValidDevice(deviceId, deviceType, dynamicParams)) {
if (msg.startsWith(JSON_ARRAY_START_CHAR)) {
status = processMultipleEvents(msg, deviceId, deviceIdJsonPath);
} else {
status = processSingleEvent(msg, deviceId, deviceIdJsonPath);
}
}
return new ContentInfo(status, msg);
}
@ -74,4 +79,21 @@ public class HTTPContentValidator implements ContentValidator {
return false;
}
}
private boolean isValidDevice(String deviceId, String deviceType, Map<String, Object> dynamicParams) {
List<String> scopes = (List<String>) dynamicParams.get(HTTPEventAdapterConstants.SCOPE_TAG);
if (scopes != null) {
for (String scope : scopes) {
if (scope.startsWith(CDMF_SCOPE_PREFIX)) {
String deviceIdInfo[] = scope.split(CDMF_SCOPE_SEPERATOR);
if (deviceIdInfo.length == 3) {
if (deviceId.equals(deviceIdInfo[2]) && deviceType.equals(deviceIdInfo[1])) {
return true;
}
}
}
}
}
return false;
}
}

@ -62,12 +62,11 @@ public final class HTTPEventAdapterConstants {
public static final String MAX_TOTAL_HTTP_CONNECTION = "100";
public static final String TENANT_DOMAIN_TAG = "tenantDomain";
public static final String USERNAME_TAG = "username";
public static final String SCOPE_TAG = "scopes";
public static final String PAYLOAD_TAG = "payload";
public static final String DEVICE_ID_JSON_PATH = "device_id_json_path";
public static final String DEVICE_ID_JSON_PATH = "event.metaData.deviceId";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME = "contentValidator";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME_HINT = "contentValidator.hint";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS = "contentValidatorParams";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT = "contentValidatorParams.hint";
public static final String DEFAULT = "default";
public static final String HTTP_CONTENT_VALIDATION_DEFAULT_PARAMETERS = "";
public static final String ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME = "contentTransformer";

@ -34,7 +34,5 @@ maximumHttpConnectionPerHost=maximumHttpConnectionPerHost
maximumHttpConnectionPerHost.hint=Maximum Http connection per host.
contentValidator=contentValidator
contentValidator.hint=Class Name of the content Validation or 'default' to set default class, required to implement (if required)
contentValidatorParams=contentValidationParams
contentValidatorParams.hint=ContentValidationParams, comma seperated. (if required)
contentTransformer=contentTransformer
contentTransformer.hint=Class Name of the content transformer or 'default' to set default class, required to implement (if required)

@ -62,18 +62,6 @@ public class MQTTEventAdapter implements InputEventAdapter {
} else {
keepAlive = MQTTEventAdapterConstants.ADAPTER_CONF_DEFAULT_KEEP_ALIVE;
}
String contentValidationParams = eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
Map<String, String> paramsMap = new HashMap<>();
if (contentValidationParams != null && !contentValidationParams.isEmpty()) {
String params[] = contentValidationParams.split(",");
for (String param : params) {
String paramsKeyAndValue[] = splitOnFirst(param, ':');
if (paramsKeyAndValue.length != 2) {
throw new InputEventAdapterException("Invalid parameters for content validation - " + param);
}
paramsMap.put(paramsKeyAndValue[0], paramsKeyAndValue[1]);
}
}
mqttBrokerConnectionConfiguration = new MQTTBrokerConnectionConfiguration(
eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_URL),
eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME),
@ -82,7 +70,6 @@ public class MQTTEventAdapter implements InputEventAdapter {
eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CLEAN_SESSION),
keepAlive,
eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME),
paramsMap,
eventAdapterConfiguration.getProperties().get(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME)
);
mqttAdapterListener = new MQTTAdapterListener(mqttBrokerConnectionConfiguration,

@ -80,16 +80,6 @@ public class MQTTEventAdapterFactory extends InputEventAdapterFactory {
contentValidator.setDefaultValue(MQTTEventAdapterConstants.DEFAULT);
propertyList.add(contentValidator);
//Content Validator Params details
Property contentValidatorParams = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
contentValidatorParams.setDisplayName(
resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS));
contentValidatorParams.setRequired(false);
contentValidatorParams.setHint(
resourceBundle.getString(MQTTEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT));
contentValidatorParams.setDefaultValue(MQTTEventAdapterConstants.MQTT_CONTENT_VALIDATION_DEFAULT_PARAMETERS);
propertyList.add(contentValidatorParams);
//Broker Username
Property userName = new Property(MQTTEventAdapterConstants.ADAPTER_CONF_USERNAME);
userName.setDisplayName(

@ -64,7 +64,6 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
private int tenantId;
private boolean connectionSucceeded = false;
ContentValidator contentValidator;
Map<String, String> contentValidationParams;
ContentTransformer contentTransformer;
private InputEventAdapterListener eventAdapterListener = null;
@ -87,7 +86,6 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
String temp_directory = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(temp_directory);
try {
connectionOptions = new MqttConnectOptions();
connectionOptions.setCleanSession(cleanSession);
@ -119,8 +117,6 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
}
}
contentValidationParams = mqttBrokerConnectionConfiguration.getContentValidatorParams();
String contentTransformerClassName = this.mqttBrokerConnectionConfiguration.getContentTransformerClassName();
if (contentTransformerClassName != null && contentTransformerClassName.equals(MQTTEventAdapterConstants.DEFAULT)) {
contentTransformer = new DefaultContentTransformer();
@ -244,10 +240,10 @@ public class MQTTAdapterListener implements MqttCallback, Runnable {
if (contentValidator != null && contentTransformer != null) {
ContentInfo contentInfo;
Map<String, String> dynamicProperties = new HashMap<>();
Map<String, Object> dynamicProperties = new HashMap<>();
dynamicProperties.put(MQTTEventAdapterConstants.TOPIC, topic);
msgText = (String) contentTransformer.transform(msgText, dynamicProperties);
contentInfo = contentValidator.validate(msgText,contentValidationParams, dynamicProperties);
contentInfo = contentValidator.validate(msgText, dynamicProperties);
if (contentInfo != null && contentInfo.isValidContent()) {
eventAdapterListener.onEvent(contentInfo.getMessage());
}

@ -31,7 +31,6 @@ public class MQTTBrokerConnectionConfiguration {
private String brokerUrl;
private String dcrUrl;
private String contentValidatorClassName;
private Map<String, String> contentValidatorParams;
private String contentTransformerClassName;
public String getBrokerScopes() {
@ -62,18 +61,13 @@ public class MQTTBrokerConnectionConfiguration {
return contentValidatorClassName;
}
public Map<String, String> getContentValidatorParams() {
return contentValidatorParams;
}
public String getContentTransformerClassName() {
return contentTransformerClassName;
}
public MQTTBrokerConnectionConfiguration(String brokerUrl, String brokerUsername, String brokerScopes,
String dcrUrl, String cleanSession, int keepAlive,
String contentValidatorClassName, Map<String, String> contentValidatorParams,
String contentTransformerClassName) {
String contentValidatorClassName, String contentTransformerClassName) {
this.brokerUsername = brokerUsername;
this.brokerScopes = brokerScopes;
if (brokerScopes == null) {
@ -86,9 +80,6 @@ public class MQTTBrokerConnectionConfiguration {
this.cleanSession = Boolean.parseBoolean(cleanSession);
}
this.keepAlive = keepAlive;
if (contentValidatorParams != null) {
this.contentValidatorParams = contentValidatorParams;
}
this.contentTransformerClassName = contentTransformerClassName;
}
}

@ -34,17 +34,11 @@ public class MQTTContentValidator implements ContentValidator {
private static final Log log = LogFactory.getLog(MQTTContentValidator.class);
@Override
public ContentInfo validate(Object msgPayload, Map<String, String> contentValidationParams,
Map<String, String> dynamicParams) {
String topic = dynamicParams.get(MQTTEventAdapterConstants.TOPIC);
public ContentInfo validate(Object msgPayload, Map<String, Object> dynamicParams) {
String topic = (String) dynamicParams.get(MQTTEventAdapterConstants.TOPIC);
String topics[] = topic.split("/");
String deviceIdJsonPath = contentValidationParams.get(MQTTEventAdapterConstants.DEVICE_ID_JSON_PATH);
String deviceIdInTopicHierarchyLevel = contentValidationParams.get(
MQTTEventAdapterConstants.DEVICE_ID_TOPIC_HIERARCHY_INDEX);
int deviceIdInTopicHierarchyLevelIndex = 0;
if (deviceIdInTopicHierarchyLevel != null && !deviceIdInTopicHierarchyLevel.isEmpty()) {
deviceIdInTopicHierarchyLevelIndex = Integer.parseInt(deviceIdInTopicHierarchyLevel);
}
String deviceIdJsonPath = MQTTEventAdapterConstants.DEVICE_ID_JSON_PATH;
int deviceIdInTopicHierarchyLevelIndex = MQTTEventAdapterConstants.DEVICE_ID_TOPIC_HIERARCHY_INDEX;
String deviceIdFromTopic = topics[deviceIdInTopicHierarchyLevelIndex];
boolean status;
String message = (String) msgPayload;

@ -34,8 +34,6 @@ public class MQTTEventAdapterConstants {
public static final String ADAPTER_CONF_DCR_URL_HINT = "dcrUrl.hint";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME = "contentValidator";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME_HINT = "contentValidator.hint";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS = "contentValidatorParams";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT = "contentValidatorParams.hint";
public static final String ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME = "contentTransformer";
public static final String ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME_HINT = "contentTransformer.hint";
public static final String ADAPTER_MESSAGE_TOPIC = "topic";
@ -61,6 +59,7 @@ public class MQTTEventAdapterConstants {
public static final String MQTT_CONTENT_VALIDATION_DEFAULT_PARAMETERS = "";
public static final String TOPIC = "topic";
public static final String PAYLOAD = "payload";
public static final String DEVICE_ID_JSON_PATH = "device_id_json_path";
public static final String DEVICE_ID_TOPIC_HIERARCHY_INDEX = "device_id_topic_hierarchy_index";
public static final String DEVICE_ID_JSON_PATH = "event.metaData.deviceId";
public static final String DEVICE_TYPE_JSON_PATH = "event.metaData.deviceId";
public static final int DEVICE_ID_TOPIC_HIERARCHY_INDEX = 2;
}

@ -29,8 +29,6 @@ dcrUrl=dcrUrl
dcrUrl.hint=dynamic client registration endpoint URL to create application (if required) eg: https://localhost:9443/dynamic-client-web/register
contentValidator=contentValidation
contentValidator.hint=Class Name of the content Validation or 'default' to set default class, required to implement (if required)
contentValidatorParams=contentValidationParams
contentValidatorParams.hint=ContentValidationParams, comma seperated. (if required)
url.hint=MQTT broker url tcp://localhost:1883
cleanSession=Clean Session
cleanSession.hint=Persist topic subscriptions and ack positions across client sessions

@ -54,20 +54,6 @@ public class XMPPEventAdapter implements InputEventAdapter {
public void init(InputEventAdapterListener eventAdapterListener) throws InputEventAdapterException {
this.eventAdapterListener = eventAdapterListener;
try {
String contentValidationParams = eventAdapterConfiguration.getProperties().get(
XMPPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
Map<String, String> paramsMap = new HashMap<>();
if (contentValidationParams != null && !contentValidationParams.isEmpty()) {
String params[] = contentValidationParams.split(",");
for (String param : params) {
String paramsKeyAndValue[] = splitOnFirst(param, ':');
if (paramsKeyAndValue.length != 2) {
throw new InputEventAdapterException("Invalid parameters for content validation - " + param);
}
paramsMap.put(paramsKeyAndValue[0], paramsKeyAndValue[1]);
}
}
int xmppPort = XMPPEventAdapterConstants.DEFAULT_XMPP_PORT;
String xmppPortString = eventAdapterConfiguration.getProperties()
.get(XMPPEventAdapterConstants.ADAPTER_CONF_PORT);
@ -90,7 +76,6 @@ public class XMPPEventAdapter implements InputEventAdapter {
eventAdapterConfiguration.getProperties().get(XMPPEventAdapterConstants.ADAPTER_CONF_RESOURCE),
eventAdapterConfiguration.getProperties().get(XMPPEventAdapterConstants
.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME),
paramsMap,
eventAdapterConfiguration.getProperties().get(XMPPEventAdapterConstants.ADAPTER_CONF_RECIEVER_JID),
eventAdapterConfiguration.getProperties().get(XMPPEventAdapterConstants
.ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME)

@ -101,15 +101,6 @@ public class XMPPEventAdapterFactory extends InputEventAdapterFactory {
resourceBundle.getString(XMPPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME_HINT));
contentValidator.setDefaultValue(XMPPEventAdapterConstants.DEFAULT);
//Content Validator Params details
Property contentValidatorParams = new Property(XMPPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS);
contentValidatorParams.setDisplayName(
resourceBundle.getString(XMPPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS));
contentValidatorParams.setRequired(false);
contentValidatorParams.setHint(
resourceBundle.getString(XMPPEventAdapterConstants.ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT));
contentValidatorParams.setDefaultValue(XMPPEventAdapterConstants.XMPP_CONTENT_VALIDATION_DEFAULT_PARAMETERS);
Property jid = new Property(XMPPEventAdapterConstants.ADAPTER_CONF_RECIEVER_JID);
jid.setDisplayName(resourceBundle.getString(XMPPEventAdapterConstants.ADAPTER_CONF_RECIEVER_JID));
jid.setRequired(true);
@ -131,7 +122,6 @@ public class XMPPEventAdapterFactory extends InputEventAdapterFactory {
propertyList.add(timooutInterval);
propertyList.add(resource);
propertyList.add(contentValidator);
propertyList.add(contentValidatorParams);
propertyList.add(jid);
propertyList.add(contentTransformer);
return propertyList;

@ -51,7 +51,6 @@ public class XMPPAdapterListener implements Runnable {
private int tenantId;
private boolean connectionSucceeded = false;
private ContentValidator contentValidator;
private Map<String, String> contentValidationParams;
private ContentTransformer contentTransformer;
private PacketListener packetListener;
@ -83,7 +82,6 @@ public class XMPPAdapterListener implements Runnable {
throw new XMPPContentInitializationException("Access of the instance in not allowed.", e);
}
}
contentValidationParams = xmppServerConnectionConfiguration.getContentValidatorParams();
String contentTransformerClassName = this.xmppServerConnectionConfiguration.getContentTransformerClassName();
if (contentTransformerClassName != null && contentTransformerClassName.equals(XMPPEventAdapterConstants.DEFAULT)) {
@ -184,11 +182,11 @@ public class XMPPAdapterListener implements Runnable {
}
if (contentValidator != null && contentTransformer != null) {
Map<String, String> dynamicParmaters = new HashMap<>();
Map<String, Object> dynamicParmaters = new HashMap<>();
dynamicParmaters.put(XMPPEventAdapterConstants.FROM_KEY, from);
dynamicParmaters.put(XMPPEventAdapterConstants.SUBJECT_KEY, subject);
message = (String) contentTransformer.transform(message, dynamicParmaters);
ContentInfo contentInfo = contentValidator.validate(message, contentValidationParams, dynamicParmaters);
ContentInfo contentInfo = contentValidator.validate(message, dynamicParmaters);
if (contentInfo != null && contentInfo.isValidContent()) {
eventAdapterListener.onEvent(contentInfo.getMessage());
}

@ -40,8 +40,6 @@ public class XMPPEventAdapterConstants {
public static final String ADAPTER_CONF_TIMEOUT_INTERVAL_HINT = "timeoutInterval.hint";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME = "contentValidator";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_CLASSNAME_HINT = "contentValidator.hint";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS = "contentValidatorParams";
public static final String ADAPTER_CONF_CONTENT_VALIDATOR_PARAMS_HINT = "contentValidatorParams.hint";
public static final String ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME = "contentTransformer";
public static final String ADAPTER_CONF_CONTENT_TRANSFORMER_CLASSNAME_HINT = "contentTransformer.hint";
public static final String ADAPTER_CONF_RECIEVER_JID = "jid";
@ -53,8 +51,6 @@ public class XMPPEventAdapterConstants {
public static final int RECONNECTION_PROGRESS_FACTOR = 2;
public static final String DEFAULT = "default";
public static final String XMPP_CONTENT_VALIDATION_DEFAULT_PARAMETERS = "";
public static final String FROM_KEY = "from";
public static final String SUBJECT_KEY = "subject";
}

@ -32,7 +32,6 @@ public class XMPPServerConnectionConfiguration {
private String resource;
private String jid;
private String contentValidatorClassName;
private Map<String, String> contentValidatorParams;
private String contentTransformerClassName;
public String getHost() {
@ -63,10 +62,6 @@ public class XMPPServerConnectionConfiguration {
return contentValidatorClassName;
}
public Map<String, String> getContentValidatorParams() {
return contentValidatorParams;
}
public String getJid() {
return jid;
}
@ -76,8 +71,7 @@ public class XMPPServerConnectionConfiguration {
}
public XMPPServerConnectionConfiguration(String host, int port, String username, String password,
int timeoutInterval, String resource, String contentValidatorClassName,
Map<String, String> contentValidatorParams, String jid,
int timeoutInterval, String resource, String contentValidatorClassName, String jid,
String contentTransformerClassName) {
this.host = host;
this.port = port;
@ -86,9 +80,6 @@ public class XMPPServerConnectionConfiguration {
this.timeoutInterval = timeoutInterval;
this.resource = resource;
this.contentValidatorClassName = contentValidatorClassName;
if (contentValidatorParams != null) {
this.contentValidatorParams = contentValidatorParams;
}
this.contentTransformerClassName = contentTransformerClassName;
this.jid = jid;
}

@ -30,8 +30,6 @@ resource=Resource
resource.hint=specific to the XMPP-Account to which the login is made to.
contentValidator=contentValidation
contentValidator.hint=Class Name of the content Validation or 'default' to set default class, required to implement (if required)
contentValidatorParams=contentValidationParams
contentValidatorParams.hint=ContentValidationParams, comma seperated. (if required)
jid=jid
jid.hint=JID - XMPP Account Name.
contentTransformer=contentTransformer

@ -69,7 +69,11 @@
org.apache.commons.logging,
org.wso2.carbon.core,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.utils
org.wso2.carbon.utils,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers,
org.w3c.dom
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.internal,

@ -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.devicetype;
import java.io.Serializable;
/**
* This class holds key for the configuration of the device type and its provider tenant.
*/
public class DeviceTypeConfigIdentifier implements Serializable {
private String deviceType;
private String tenantDomain;
public DeviceTypeConfigIdentifier(String deviceType, String tenantDomain) {
this.deviceType = deviceType;
this.tenantDomain = tenantDomain;
}
@Override
public int hashCode() {
int result = this.deviceType.hashCode();
result = 31 * result + ("@" + this.tenantDomain).hashCode();
return result;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof DeviceTypeConfigIdentifier) && deviceType.equals(
((DeviceTypeConfigIdentifier) obj).deviceType) && tenantDomain.equals(
((DeviceTypeConfigIdentifier) obj).tenantDomain);
}
}

@ -0,0 +1,18 @@
package org.wso2.carbon.device.mgt.iot.devicetype;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
/**
* Service to retrieve device type configs.
*/
public interface DeviceTypeConfigService {
/**
* This service will read the device type configuration files from conf/etc/device-type-plugins
*
* @param deviceType retrive the device type configuration.
* @param tenantDomain retrieve the device type of this tenant domain.
* @return device management configuratio for the device type owned by the given tenant domain.
*/
DeviceManagementConfiguration getConfiguration(String deviceType, String tenantDomain);
}

@ -0,0 +1,72 @@
package org.wso2.carbon.device.mgt.iot.devicetype;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.exception.DeviceTypeConfigurationException;
import org.wso2.carbon.device.mgt.iot.devicetype.util.DeviceTypeConfigUtil;
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;
import java.util.HashMap;
import java.util.Map;
public class DeviceTypeConfigServiceImpl implements DeviceTypeConfigService {
private static final Log log = LogFactory.getLog(DeviceTypeConfigServiceImpl.class);
private static final String DEVICE_TYPE_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugins";
private Map<DeviceTypeConfigIdentifier, DeviceManagementConfiguration> deviceTypeConfigurationMap = new HashMap<>();
public void initialize() {
File configurationDirectory = new File(DEVICE_TYPE_CONFIG_PATH);
File[] deviceTypeConfigurationFiles = configurationDirectory.listFiles();
if (deviceTypeConfigurationFiles != null) {
for (File file : deviceTypeConfigurationFiles) {
String filename = file.getName();
if (filename.endsWith(".xml") || filename.endsWith(".XML")) {
try {
DeviceManagementConfiguration deviceManagementConfiguration = getDeviceTypeConfiguration(file);
String deviceType = deviceManagementConfiguration.getDeviceType();
String tenantDomain = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getProvisioningConfig().getTenantDomain();
if ( deviceType != null && !deviceType.isEmpty() && tenantDomain != null
&& !tenantDomain.isEmpty()) {
deviceTypeConfigurationMap.put(new DeviceTypeConfigIdentifier(deviceType, tenantDomain),
deviceManagementConfiguration);
}
} catch (DeviceTypeConfigurationException e) {
//continue reading other files
log.error(e.getMessage(), e);
}
}
}
}
}
private DeviceManagementConfiguration getDeviceTypeConfiguration(File configurationFile)
throws DeviceTypeConfigurationException {
try {
Document doc = DeviceTypeConfigUtil.convertToDocument(configurationFile);
/* Un-marshaling Webapp Authenticator configuration */
JAXBContext ctx = JAXBContext.newInstance(DeviceManagementConfiguration.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
return (DeviceManagementConfiguration) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new DeviceTypeConfigurationException("Error occurred while un-marshalling the file " +
configurationFile.getAbsolutePath(), e);
}
}
@Override
public DeviceManagementConfiguration getConfiguration(String deviceType, String tenantDomain) {
return deviceTypeConfigurationMap.get(new DeviceTypeConfigIdentifier(deviceType, tenantDomain));
}
}

@ -15,14 +15,13 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config;
package org.wso2.carbon.device.mgt.iot.devicetype.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class for holding data source configuration in malformed-cdm-config-no-mgt-repo.xml at parsing
* with JAXB.
* Class for holding device type configuration and parsing with JAXB.
*/
@XmlRootElement(name = "DataSourceConfiguration")
public class DataSourceConfig {

@ -15,7 +15,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config;
package org.wso2.carbon.device.mgt.iot.devicetype.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@ -27,6 +27,7 @@ import javax.xml.bind.annotation.XmlRootElement;
public class DeviceManagementConfigRepository {
private DataSourceConfig dataSourceConfig;
private ProvisioningConfig provisioningConfig;
@XmlElement(name = "DataSourceConfiguration", required = true)
public DataSourceConfig getDataSourceConfig() {
@ -37,4 +38,13 @@ public class DeviceManagementConfigRepository {
this.dataSourceConfig = dataSourceConfig;
}
@XmlElement(name = "ProvisioningConfig", required = true)
public ProvisioningConfig getProvisioningConfig() {
return provisioningConfig;
}
public void setProvisioningConfig(
ProvisioningConfig provisioningConfig) {
this.provisioningConfig = provisioningConfig;
}
}

@ -0,0 +1,66 @@
/*
* 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.devicetype.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "DeviceManagementConfiguration")
public class DeviceManagementConfiguration {
private DeviceManagementConfigRepository deviceManagementConfigRepository;
private PushNotificationConfig pushNotificationConfig;
private String deviceType;
private static final Log log = LogFactory.getLog(DeviceManagementConfiguration.class);
private DeviceManagementConfiguration() {
}
@XmlElement(name = "DeviceType", required = false)
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
return deviceManagementConfigRepository;
}
public void setDeviceManagementConfigRepository(DeviceManagementConfigRepository deviceManagementConfigRepository) {
this.deviceManagementConfigRepository = deviceManagementConfigRepository;
}
@XmlElement(name = "PushNotificationConfiguration", required = false)
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}
public void setPushNotificationConfig(PushNotificationConfig pushNotificationConfig) {
this.pushNotificationConfig = pushNotificationConfig;
}
}

@ -16,13 +16,17 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config;
package org.wso2.carbon.device.mgt.iot.devicetype.config;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.util.List;
/**
* Class for hold JndiLookupDefinition of rss-manager.xml at parsing with JAXB.
* Class for hold JndiLookupDefinition parsing with JAXB.
*/
@XmlRootElement(name = "JndiLookupDefinition")
public class JNDILookupDefinition {

@ -0,0 +1,49 @@
/*
* Copyright (c) 2014, 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.devicetype.config;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Class for holding device type configuration and parsing with JAXB.
*/
@XmlRootElement(name = "ProvisioningConfig")
public class ProvisioningConfig {
private String tenantDomain;
private boolean sharedWithAllTenants;
@XmlElement(name = "TenantDomain", required = true)
public String getTenantDomain() {
return tenantDomain;
}
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
@XmlElement(name = "SharedWithAllTenants", required = true)
public boolean isSharedWithAllTenants() {
return sharedWithAllTenants;
}
public void setSharedWithAllTenants(boolean sharedWithAllTenants) {
this.sharedWithAllTenants = sharedWithAllTenants;
}
}

@ -16,14 +16,19 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config;
package org.wso2.carbon.device.mgt.iot.devicetype.config;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import java.util.List;
@XmlRootElement(name = "PushNotificationConfiguration")
public class PushNotificationConfig {
private String pushNotificationProvider;
private List<Property> properties;
@XmlElementWrapper(name = "Properties", required = true)
@ -36,6 +41,15 @@ public class PushNotificationConfig {
this.properties = properties;
}
@XmlElement(name = "PushNotificationProvider", required = true)
public String getPushNotificationProvider() {
return pushNotificationProvider;
}
public void setPushNotificationProvider(String pushNotificationProvider) {
this.pushNotificationProvider = pushNotificationProvider;
}
@XmlRootElement(name = "Property")
public static class Property {

@ -16,37 +16,37 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.exception;
package org.wso2.carbon.device.mgt.iot.devicetype.config.exception;
public class VirtualFireAlarmConfigurationException extends Exception {
public class DeviceTypeConfigurationException extends Exception {
private static final long serialVersionUID = -3151279431229070297L;
public VirtualFireAlarmConfigurationException(int errorCode, String message) {
public DeviceTypeConfigurationException(int errorCode, String message) {
super(message);
}
public VirtualFireAlarmConfigurationException(int errorCode, String message, Throwable cause) {
public DeviceTypeConfigurationException(int errorCode, String message, Throwable cause) {
super(message, cause);
}
public VirtualFireAlarmConfigurationException(String msg, Exception nestedEx) {
public DeviceTypeConfigurationException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public VirtualFireAlarmConfigurationException(String message, Throwable cause) {
public DeviceTypeConfigurationException(String message, Throwable cause) {
super(message, cause);
}
public VirtualFireAlarmConfigurationException(String msg) {
public DeviceTypeConfigurationException(String msg) {
super(msg);
}
public VirtualFireAlarmConfigurationException() {
public DeviceTypeConfigurationException() {
super();
}
public VirtualFireAlarmConfigurationException(Throwable cause) {
public DeviceTypeConfigurationException(Throwable cause) {
super(cause);
}

@ -16,28 +16,34 @@
* under the License.
*
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.util;
package org.wso2.carbon.device.mgt.iot.devicetype.util;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.exception.VirtualFireAlarmConfigurationException;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.exception.DeviceTypeConfigurationException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class VirtualFireAlarmUtil {
public class DeviceTypeConfigUtil {
public static Document convertToDocument(File file) throws VirtualFireAlarmConfigurationException {
public static Document convertToDocument(File file) throws DeviceTypeConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
return docBuilder.parse(file);
} catch (Exception e) {
throw new VirtualFireAlarmConfigurationException("Error occurred while parsing file, while converting " +
throw new DeviceTypeConfigurationException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
}

@ -23,6 +23,8 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigServiceImpl;
import org.wso2.carbon.device.mgt.iot.url.printer.URLPrinterStartupHandler;
import org.wso2.carbon.utils.ConfigurationContextService;
@ -50,6 +52,10 @@ public class IotDeviceManagementServiceComponent {
if (log.isDebugEnabled()) {
log.debug("Iot Device Management Service Component has been successfully activated");
}
DeviceTypeConfigServiceImpl deviceTypeConfigLoaderService = new DeviceTypeConfigServiceImpl();
deviceTypeConfigLoaderService.initialize();
bundleContext.registerService(DeviceTypeConfigService.class.getName(), deviceTypeConfigLoaderService,
null);
} catch (Throwable e) {
log.error("Error occurred while activating Iot Device Management Service Component", e);
}

@ -20,7 +20,6 @@
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/raspberrypi/+/temperature</property>
<property name="username">admin</property>
<property name="contentValidatorParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>

@ -34,6 +34,9 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
@ -60,6 +63,7 @@ import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
public class RaspberryPiServiceImpl implements RaspberryPiService {
@ -83,16 +87,31 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String actualMessage = RaspberrypiConstants.BULB_CONTEXT + ":" + state;
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
dynamicProperties.put(RaspberrypiConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(RaspberrypiConstants.MQTT_ADAPTER_NAME,
dynamicProperties, actualMessage);
Operation commandOp = new CommandOperation();
commandOp.setCode("bulb");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(actualMessage);
Properties props = new Properties();
props.setProperty(RaspberrypiConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, RaspberrypiConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(RaspberrypiConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (OperationManagementException e) {
String msg = "Error occurred while executing command operation upon switch the bulb";
log.error(msg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@ -191,6 +210,11 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
UserStoreException {
//create new device id
String deviceId = shortUUID();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
@ -200,17 +224,12 @@ public class RaspberryPiServiceImpl implements RaspberryPiService {
RaspberrypiConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + RaspberrypiConstants.DEVICE_TYPE + " device_" + deviceId;
String scopes = "cdmf/" + RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);

@ -22,7 +22,6 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
@ -45,6 +44,7 @@ public class ZipUtil {
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
private static final String CONFIG_TYPE = "general";
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token,
@ -63,7 +63,7 @@ public class ZipUtil {
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String apimEndpoint = httpsServerEP;
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}

@ -75,9 +75,8 @@
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.core.util,
org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception,
org.wso2.carbon.ndatasource.core
org.wso2.carbon.ndatasource.core,
org.wso2.carbon.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal,
@ -119,8 +118,8 @@
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -30,38 +30,12 @@ public class RaspberrypiConstants {
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
public static final String URL_PREFIX = "http://";
public static final String BULB_CONTEXT = "BULB";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
//type of the sensor
public static final String SENSOR_TEMPERATURE = "temperature";
//sensor events summerized table name
public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY";
public static final String DATA_SOURCE_NAME = "jdbc/RaspberryPiDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants
public static final String MQTT_ADAPTER_NAME = "raspberrypi_mqtt";
public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt";
public static final String ADAPTER_TOPIC_PROPERTY = "topic";
public static final String MQTT_PORT = "\\$\\{mqtt.broker.port\\}";
public static final String MQTT_BROKER_HOST = "\\$\\{mqtt.broker.host\\}";
public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset";
public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip";
public static final int CARBON_DEFAULT_PORT_OFFSET = 0;
public static final int DEFAULT_MQTT_PORT = 1883;
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String DCR_PROPERTY_KEY = "dcrUrl";
public static final String BROKER_URL_PROPERTY_KEY = "url";
public static final String SCOPES_PROPERTY_KEY = "scopes";
public static final String QOS_PROPERTY_KEY = "qos";
public static final String CLIENT_ID_PROPERTY_KEY = "qos";
public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession";
public static final String TOPIC = "topic";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";
}

@ -24,7 +24,9 @@ import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal.RaspberrypiManagementDataHolder;
public class RaspberrypiManagerService implements DeviceManagementService {
@ -52,7 +54,12 @@ public class RaspberrypiManagerService implements DeviceManagementService {
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
DeviceManagementConfiguration deviceManagementConfiguration = RaspberrypiManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(RaspberrypiConstants.DEVICE_TYPE,
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
boolean sharedWithAllTenants = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getProvisioningConfig().isSharedWithAllTenants();
return new ProvisioningConfig(RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN, sharedWithAllTenants);
}
@Override

@ -20,8 +20,10 @@ package org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal.RaspberrypiManagementDataHolder;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -45,11 +47,16 @@ public class RaspberrypiDAOUtil {
}
public static void initRaspberrypiDAO() {
DeviceManagementConfiguration deviceManagementConfiguration = RaspberrypiManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(RaspberrypiConstants.DEVICE_TYPE,
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(RaspberrypiConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + RaspberrypiConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
}
}

@ -1,46 +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.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import java.io.IOException;
/**
* Startup listener to create an output adapter after server starts up.
*/
public class RaspberrypiStartupListener implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(RaspberrypiStartupListener.class);
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
try {
RaspberrypiUtils.setupMqttOutputAdapter();
} catch (IOException e) {
log.error("Failed to intilaize the virtual firealarm output adapter", e);
}
}
}

@ -23,6 +23,7 @@ import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal.RaspberrypiManagementDataHolder;
@ -84,97 +85,23 @@ public class RaspberrypiUtils {
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws RaspberrypiDeviceMgtPluginException {
DeviceManagementConfiguration deviceManagementConfiguration = RaspberrypiManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(RaspberrypiConstants.DEVICE_TYPE,
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasource = deviceManagementConfiguration.getDeviceManagementConfigRepository().getDataSourceConfig()
.getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(RaspberrypiConstants.DATA_SOURCE_NAME);
DataSource dataSource = (DataSource) ctx.lookup(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + RaspberrypiConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasource, e);
} catch (Exception e) {
throw new RaspberrypiDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
public static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(RaspberrypiConstants.MQTT_ADAPTER_NAME,
RaspberrypiConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
RaspberrypiManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + RaspberrypiConstants.MQTT_ADAPTER_NAME, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Create Output Event Adapter Configuration for given configuration.
*
* @param name Output Event Adapter name
* @param type Output Event Adapter type
* @param msgFormat Output Event Adapter message format
* @return OutputEventAdapterConfiguration instance for given configuration
*/
private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);
outputEventAdapterConfiguration.setMessageFormat(msgFormat);
File configFile = new File(RaspberrypiConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
Map<String, String> mqttAdapterProperties = new HashMap<>();
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
mqttAdapterProperties.put(RaspberrypiConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
RaspberrypiConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(RaspberrypiConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(RaspberrypiConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(RaspberrypiConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(RaspberrypiConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(RaspberrypiConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
RaspberrypiConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(RaspberrypiConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
RaspberrypiConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(RaspberrypiConstants.QOS_PROPERTY_KEY, properties.getProperty(
RaspberrypiConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(RaspberrypiConstants.CLIENT_ID_PROPERTY_KEY, "");
outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties);
}
return outputEventAdapterConfiguration;
}
public static String replaceMqttProperty(String urlWithPlaceholders) {
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(RaspberrypiConstants.MQTT_PORT, "" +
(RaspberrypiConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(RaspberrypiConstants.MQTT_BROKER_HOST,
System.getProperty(RaspberrypiConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
return urlWithPlaceholders;
}
private static int getPortOffset() {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
RaspberrypiConstants.CARBON_CONFIG_PORT_OFFSET));
try {
if ((portOffset != null)) {
return Integer.parseInt(portOffset.trim());
} else {
return RaspberrypiConstants.CARBON_DEFAULT_PORT_OFFSET;
}
} catch (NumberFormatException e) {
return RaspberrypiConstants.CARBON_DEFAULT_PORT_OFFSET;
}
}
}

@ -18,6 +18,7 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
@ -25,7 +26,7 @@ import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
*/
public class RaspberrypiManagementDataHolder {
private OutputEventAdapterService outputEventAdapterService;
private DeviceTypeConfigService deviceTypeConfigService;
private static RaspberrypiManagementDataHolder thisInstance = new RaspberrypiManagementDataHolder();
@ -36,13 +37,13 @@ public class RaspberrypiManagementDataHolder {
return thisInstance;
}
public OutputEventAdapterService getOutputEventAdapterService() {
return outputEventAdapterService;
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setOutputEventAdapterService(
OutputEventAdapterService outputEventAdapterService) {
this.outputEventAdapterService = outputEventAdapterService;
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
}

@ -23,30 +23,28 @@ import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.RaspberrypiManagerService;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.util.RaspberrypiStartupListener;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.util.RaspberrypiUtils;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.ndatasource.core.DataSourceService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.raspberrypi.internal.RaspberrypiManagementServiceComponent"
* immediate="true"
* @scr.reference name="event.output.adapter.service"
* interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOutputEventAdapterService"
* unbind="unsetOutputEventAdapterService"
* @scr.reference name="org.wso2.carbon.ndatasource"
* interface="org.wso2.carbon.ndatasource.core.DataSourceService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDataSourceService"
* unbind="unsetDataSourceService"
* @scr.reference name="devicetype.configuration.service"
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeConfigService"
* unbind="unsetDeviceTypeConfigService"
*/
public class RaspberrypiManagementServiceComponent {
@ -59,11 +57,8 @@ public class RaspberrypiManagementServiceComponent {
}
try {
BundleContext bundleContext = ctx.getBundleContext();
raspberrypiServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
raspberrypiServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName(),
new RaspberrypiManagerService(), null);
bundleContext.registerService(ServerStartupObserver.class.getName(), new RaspberrypiStartupListener(),
null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
@ -101,22 +96,6 @@ public class RaspberrypiManagementServiceComponent {
}
}
/**
* Initialize the Output EventAdapter Service dependency
*
* @param outputEventAdapterService Output EventAdapter Service reference
*/
protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
RaspberrypiManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
RaspberrypiManagementDataHolder.getInstance().setOutputEventAdapterService(null);
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
@ -129,4 +108,12 @@ public class RaspberrypiManagementServiceComponent {
//do nothing
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
RaspberrypiManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
RaspberrypiManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

@ -1,60 +0,0 @@
/*
* 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.raspberrypi.plugin.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.util.RaspberrypiUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MqttConfig {
private static String brokerEndpoint;
private static MqttConfig mqttConfig = new MqttConfig();
private static final Log log = LogFactory.getLog(MqttConfig.class);
private MqttConfig() {
File configFile = new File(RaspberrypiConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
brokerEndpoint = RaspberrypiUtils.replaceMqttProperty(
properties.getProperty(RaspberrypiConstants.BROKER_URL_PROPERTY_KEY));
} catch (IOException e) {
log.error("Failed to read the mqtt.properties file" + e);
}
}
}
public static MqttConfig getInstance() {
return mqttConfig;
}
public String getBrokerEndpoint() {
return brokerEndpoint;
}
}

@ -69,7 +69,7 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
username = agentManager.getAgentConfigs().getDeviceId();
password = agentManager.getAgentConfigs().getAuthToken();
xmppDeviceJID = username + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = "wso2admin_" + AgentConstants.DEVICE_TYPE + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = agentManager.getAgentConfigs().getServerJID();
Runnable connect = new Runnable() {
public void run() {

@ -40,6 +40,7 @@ public class AgentConfiguration {
private String refreshToken;
private int dataPushInterval;
private String xmppServerName;
private String serverJID;
public String getTenantDomain() {
return tenantDomain;
@ -61,6 +62,14 @@ public class AgentConfiguration {
return deviceId;
}
public String getServerJID() {
return serverJID;
}
public void setServerJID(String serverJID) {
this.serverJID = serverJID;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}

@ -70,6 +70,7 @@ public class AgentConstants {
public static final String TENANT_DOMAIN = "tenantDomain";
public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String SERVER_JID_PROPERTY = "server-jid";
public static final String DEVICE_NAME_PROPERTY = "device-name";
public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context";
public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context";
@ -89,6 +90,7 @@ public class AgentConstants {
public static final String DEFAULT_SERVER_NAME = "WSO2IoTServer";
public static final String DEFAULT_DEVICE_OWNER = "admin";
public static final String DEFAULT_DEVICE_ID = "1234567890";
public static final String DEFAULT_SERVER_JID = "admin@localhost";
public static final String DEFAULT_DEVICE_NAME = "admin_1234567890";
public static final String DEFAULT_HTTPS_SERVER_EP = "https://localhost:9443";
public static final String DEFAULT_HTTP_SERVER_EP = "http://localhost:9763";

@ -204,7 +204,7 @@ public class AgentManager {
if (protocol.equals(AgentConstants.HTTP_PROTOCOL) && !protocol.equals(
prevProtocol)) {
switchCommunicator(protocol, protocol);
switchCommunicator(prevProtocol, protocol);
}
}
}

@ -86,6 +86,8 @@ public class AgentUtilOperations {
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
AgentConstants.DEVICE_ID_PROPERTY));
iotServerConfigs.setServerJID(properties.getProperty(
AgentConstants.SERVER_JID_PROPERTY));
iotServerConfigs.setDeviceName(properties.getProperty(
AgentConstants.DEVICE_NAME_PROPERTY));
iotServerConfigs.setControllerContext(properties.getProperty(
@ -182,6 +184,7 @@ public class AgentUtilOperations {
iotServerConfigs.setDeviceOwner(AgentConstants.DEFAULT_SERVER_NAME);
iotServerConfigs.setDeviceOwner(AgentConstants.DEFAULT_DEVICE_OWNER);
iotServerConfigs.setDeviceId(AgentConstants.DEFAULT_DEVICE_ID);
iotServerConfigs.setServerJID(AgentConstants.DEFAULT_SERVER_JID);
iotServerConfigs.setDeviceName(AgentConstants.DEFAULT_DEVICE_NAME);
iotServerConfigs.setControllerContext(AgentConstants.DEVICE_CONTROLLER_API_EP);
iotServerConfigs.setScepContext(AgentConstants.DEVICE_SCEP_API_EP);

@ -70,7 +70,7 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
username = agentManager.getAgentConfigs().getDeviceId();
password = agentManager.getAgentConfigs().getAuthToken();
xmppDeviceJID = username + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = "wso2admin_" + AgentConstants.DEVICE_TYPE + "@" + agentManager.getAgentConfigs().getXmppServerName();
xmppAdminJID = agentManager.getAgentConfigs().getServerJID();
Runnable connect = new Runnable() {
public void run() {

@ -41,6 +41,7 @@ public class AgentConfiguration {
private String refreshToken;
private int dataPushInterval;
private String xmppServerName;
private String serverJID;
public String getTenantDomain() {
return tenantDomain;
@ -62,6 +63,14 @@ public class AgentConfiguration {
return deviceId;
}
public String getServerJID() {
return serverJID;
}
public void setServerJID(String serverJID) {
this.serverJID = serverJID;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}

@ -71,6 +71,7 @@ public class AgentConstants {
public static final String TENANT_DOMAIN = "tenantDomain";
public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String SERVER_JID_PROPERTY = "server-jid";
public static final String DEVICE_NAME_PROPERTY = "device-name";
public static final String DEVICE_CONTROLLER_CONTEXT_PROPERTY = "controller-context";
public static final String DEVICE_SCEP_CONTEXT_PROPERTY = "scep-context";

@ -191,7 +191,7 @@ public class AgentManager {
if (protocol.equals(AgentConstants.HTTP_PROTOCOL) && !protocol.equals(
prevProtocol)) {
switchCommunicator(protocol, protocol);
switchCommunicator(prevProtocol, protocol);
}
}
}

@ -104,6 +104,8 @@ public class AgentUtilOperations {
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
AgentConstants.DEVICE_ID_PROPERTY));
iotServerConfigs.setServerJID(properties.getProperty(
AgentConstants.SERVER_JID_PROPERTY));
iotServerConfigs.setDeviceName(properties.getProperty(
AgentConstants.DEVICE_NAME_PROPERTY));
iotServerConfigs.setControllerContext(properties.getProperty(

@ -43,7 +43,6 @@ public interface VirtualFireAlarmService {
* to connect-to and send the command to the device.
*
* @param deviceId the ID of the VirtualFirealarm device on which the buzzer needs to switched `ON` or `OFF`.
* @param protocol the protocol (HTTP, MQTT, XMPP) to be used to connect-to & send the message to the device.
* @param state the state to which the buzzer on the device needs to be changed. Either "ON" or "OFF".
* (Case-Insensitive String)
*/
@ -51,7 +50,7 @@ public interface VirtualFireAlarmService {
@Path("device/{deviceId}/buzz")
@Permission(scope = "virtual_firealarm_user", permissions = {"/permission/admin/device-mgt/user/operations"})
@Feature(code = "buzz", name = "Buzzer On / Off", description = "Switch on/off Virtual Fire Alarm Buzzer. (On / Off)")
Response switchBuzzer(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
Response switchBuzzer(@PathParam("deviceId") String deviceId,
@FormParam("state") String state);
/**

@ -86,8 +86,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
@POST
@Path("device/{deviceId}/buzz")
public Response switchBuzzer(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state) {
public Response switchBuzzer(@PathParam("deviceId") String deviceId, @FormParam("state") String state) {
if (state == null || state.isEmpty()) {
log.error("State is not defined for the buzzer operation");
return Response.status(Response.Status.BAD_REQUEST).build();
@ -98,18 +97,6 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST).build();
}
String protocolString;
if (protocol == null || protocol.isEmpty()) {
protocolString = MQTT_PROTOCOL;
} else {
protocolString = protocol.toUpperCase();
}
if (log.isDebugEnabled()) {
log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " +
protocolString);
}
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
@ -121,39 +108,28 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
String actualMessage = resource + ":" + switchToState;
String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage,
serverPrivateKey);
Map<String, String> dynamicProperties = new HashMap<>();
switch (protocolString) {
case XMPP_PROTOCOL:
dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY,
deviceId + "@" + XmppConfig.getInstance().getXmppServerName());
dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST");
dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
APIUtil.getOutputEventAdapterService().publish(VirtualFireAlarmConstants.XMPP_ADAPTER_NAME,
dynamicProperties, encryptedMsg);
break;
default:
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
dynamicProperties.put(VirtualFireAlarmConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(VirtualFireAlarmConstants.MQTT_ADAPTER_NAME,
dynamicProperties, encryptedMsg);
Operation commandOp = new CommandOperation();
commandOp.setCode("buzz");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(encryptedMsg);
String publishTopic = APIUtil.getTenantDomainOftheUser() + "/"
+ VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
Properties props = new Properties();
props.setProperty(VirtualFireAlarmConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
commandOp.setProperties(props);
Operation commandOp = new CommandOperation();
commandOp.setCode("buzz");
commandOp.setType(Operation.Type.COMMAND);
commandOp.setEnabled(true);
commandOp.setPayLoad(encryptedMsg);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
break;
}
Properties props = new Properties();
props.setProperty(VirtualFireAlarmConstants.MQTT_ADAPTER_TOPIC_PROPERTY_NAME, publishTopic);
props.setProperty(VirtualFireAlarmConstants.CLIENT_JID_PROPERTY_KEY, deviceId + "@" + XmppConfig
.getInstance().getServerName());
props.setProperty(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "CONTROL-REQUEST");
props.setProperty(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
commandOp.setProperties(props);
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
deviceIdentifiers.add(new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE));
APIUtil.getDeviceManagementService().addOperation(VirtualFireAlarmConstants.DEVICE_TYPE, commandOp,
deviceIdentifiers);
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
@ -191,7 +167,7 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
switch (protocolString) {
case XMPP_PROTOCOL:
dynamicProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY,
deviceId + "@" + XmppConfig.getInstance().getXmppServerName());
deviceId + "@" + XmppConfig.getInstance().getServerName());
dynamicProperties.put(VirtualFireAlarmConstants.SUBJECT_PROPERTY_KEY, "POLICTY-REQUEST");
dynamicProperties.put(VirtualFireAlarmConstants.MESSAGE_TYPE_PROPERTY_KEY,
VirtualFireAlarmConstants.CHAT_PROPERTY_KEY);
@ -318,6 +294,11 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
UserStoreException, VirtualFirealarmDeviceMgtPluginException {
//create new device id
String deviceId = shortUUID();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
@ -328,37 +309,25 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + VirtualFireAlarmConstants.DEVICE_TYPE + " device_" + deviceId;
String scopes = "cdmf/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@" + APIUtil.getTenantDomainOftheUser());
status = XmppServerClient.createAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs";
throw new DeviceManagementException(msg);
}
}
status = register(deviceId, deviceName);
status = XmppServerClient.createAccount(newXmppAccount);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs";
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
return ziputil.createZipFile(owner, sketchType, deviceId, deviceName, apiApplicationKey.toString(),
accessToken, refreshToken);

@ -22,4 +22,5 @@ public class VirtualFireAlarmUtilConstants {
public static final String DEVICE_TOKEN = "DEVICE_TOKEN";
public static final String DEVICE_REFRESH_TOKEN = "DEVICE_REFRESH_TOKEN";
public static final String SERVER_NAME = "SERVER_NAME";
public static final String SERVER_JID = "SERVER_JID";
}

@ -29,8 +29,6 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManageme
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.utils.CarbonUtils;
@ -53,6 +51,7 @@ public class ZipUtil {
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
private static final String CONFIG_TYPE = "general";
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName,
String apiApplicationKey, String token, String refreshToken)
@ -71,17 +70,18 @@ public class ZipUtil {
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}
String xmppEndpoint = XmppConfig.getInstance().getXmppServerIP() + ":" +
XmppConfig.getInstance().getXmppServerPort();
if (xmppEndpoint.contains(LOCALHOST)) {
xmppEndpoint = xmppEndpoint.replace(LOCALHOST, iotServerIP);
String xmppEndpoint = "";
if (XmppConfig.getInstance().isEnabled()) {
xmppEndpoint = XmppConfig.getInstance().getHost() + ":" + XmppConfig.getInstance().getPort();
if (xmppEndpoint.contains(LOCALHOST)) {
xmppEndpoint = xmppEndpoint.replace(LOCALHOST, iotServerIP);
}
}
PlatformConfiguration configuration = APIUtil.getTenantConfigurationManagementService().getConfiguration(
CONFIG_TYPE);
if (configuration != null && configuration.getConfiguration() != null && configuration
@ -119,7 +119,11 @@ public class ZipUtil {
contextParams.put(VirtualFireAlarmUtilConstants.API_APPLICATION_KEY, base64EncodedApplicationKey);
contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_TOKEN, token);
contextParams.put(VirtualFireAlarmUtilConstants.DEVICE_REFRESH_TOKEN, refreshToken);
contextParams.put(VirtualFireAlarmUtilConstants.SERVER_NAME, XmppConfig.getInstance().getXmppServerName());
contextParams.put(VirtualFireAlarmUtilConstants.SERVER_NAME, XmppConfig.getInstance().getServerName() == null
? "" : XmppConfig.getInstance().getServerName());
contextParams.put(VirtualFireAlarmUtilConstants.SERVER_JID, XmppConfig.getInstance().getJid() == null
? "" : XmppConfig.getInstance().getJid());
ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;

@ -71,10 +71,6 @@
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception,
org.wso2.carbon.base,
org.wso2.carbon.core.util,
org.wso2.carbon.context,
org.wso2.carbon.core,
javax.crypto,
@ -88,10 +84,7 @@
org.wso2.carbon.event.input.adapter.core,
org.wso2.carbon.event.input.adapter.core.exception,
org.jivesoftware.smack.*,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers,
org.w3c.dom,
org.wso2.carbon.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal,
@ -140,10 +133,6 @@
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.input.adapter.core</artifactId>
@ -172,5 +161,9 @@
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies>
</project>

@ -35,7 +35,6 @@ public class VirtualFireAlarmConstants {
//sensor events sumerized table name for temperature
public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY";
public static final String DATA_SOURCE_NAME = "jdbc/VirtualFireAlarmDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants
@ -54,8 +53,9 @@ public class VirtualFireAlarmConstants {
public static final String XMPP_ADAPTER_TYPE = "xmpp";
public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String JID_PROPERTY_KEY = "jid";
public static final String SUBJECT_PROPERTY_KEY = "subject";
public static final String MESSAGE_TYPE_PROPERTY_KEY = "messageType";
public static final String CLIENT_JID_PROPERTY_KEY = "xmpp.client.jid";
public static final String SUBJECT_PROPERTY_KEY = "xmpp.client.subject";
public static final String MESSAGE_TYPE_PROPERTY_KEY = "xmpp.client.messageType";
public static final String CHAT_PROPERTY_KEY = "chat";
public static final String USERNAME_PROPERTY_KEY = "username";
@ -77,19 +77,10 @@ public class VirtualFireAlarmConstants {
public static final String JSON_MESSAGE_KEY = "Msg";
public static final String JSON_SIGNATURE_KEY = "Sig";
public static final String IS_ENABLED_KEY = "enabled";
public static final String HOST_KEY = "host";
public static final String PORT_KEY = "port";
public static final String ADMIN_USERNAME = "admin.username";
public static final String ADMIN_PASSWORD = "admin.password";
public static final String XMPP_SERVER_PASSWORD = "admin@123456789";
public static final String SERVER_NAME = "serverName";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
public static final String XMPP_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "xmpp.properties";
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";
}

@ -24,8 +24,9 @@ import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.VirtualFireAlarmConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import java.util.HashMap;
import java.util.Map;
@ -47,14 +48,17 @@ public class VirtualFireAlarmManagerService implements DeviceManagementService {
}
private PushNotificationConfig populatePushNotificationConfig() {
org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.PushNotificationConfig sourceConfig =
VirtualFireAlarmConfig.getInstance().getPushNotificationConfig();
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.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.virtualfirealarm.plugin.internal.config.PushNotificationConfig.Property
for (org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig.Property
property : sourceConfig.getProperties()) {
staticProps.put(property.getName(), property.getValue());
}
return new PushNotificationConfig("MQTT", staticProps);
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
}
@Override
@ -69,7 +73,12 @@ public class VirtualFireAlarmManagerService implements DeviceManagementService {
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
boolean sharedWithAllTenants = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getProvisioningConfig().isSharedWithAllTenants();
return new ProvisioningConfig(VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN, sharedWithAllTenants);
}
@Override

@ -20,8 +20,10 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -41,11 +43,16 @@ public class VirtualFireAlarmDAOUtil {
}
public static void initFireAlarmDAO() {
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasourceName = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getDataSourceConfig().getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(VirtualFireAlarmConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(datasourceName);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + VirtualFireAlarmConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasourceName, e);
}
}

@ -21,33 +21,27 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterConfiguration;
import org.wso2.carbon.event.input.adapter.core.MessageType;
import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException;
import org.wso2.carbon.event.output.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import org.json.JSONObject;
import org.wso2.carbon.utils.NetworkUtils;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.sql.Connection;
@ -56,7 +50,6 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Contains utility methods used by FireAlarm plugin.
@ -97,38 +90,29 @@ public class VirtualFireAlarmUtils {
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws VirtualFirealarmDeviceMgtPluginException {
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
String datasourceName = deviceManagementConfiguration.getDeviceManagementConfigRepository()
.getDataSourceConfig().getJndiLookupDefinition().getJndiName();
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(VirtualFireAlarmConstants.DATA_SOURCE_NAME);
DataSource dataSource = (DataSource) ctx.lookup(datasourceName);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + VirtualFireAlarmConstants.DATA_SOURCE_NAME, e);
log.error("Error while looking up the data source: " + datasourceName, e);
} catch (Exception e) {
throw new VirtualFirealarmDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
public static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(VirtualFireAlarmConstants.MQTT_ADAPTER_NAME,
VirtualFireAlarmConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
VirtualFirealarmManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + VirtualFireAlarmConstants.MQTT_ADAPTER_NAME, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
public static void setupMqttInputAdapter() throws IOException {
if (!MqttConfig.getInstance().isEnabled()) {
return;
}
InputEventAdapterConfiguration inputEventAdapterConfiguration =
createMqttInputEventAdapterConfiguration(VirtualFireAlarmConstants.MQTT_ADAPTER_NAME,
VirtualFireAlarmConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
@ -145,45 +129,6 @@ public class VirtualFireAlarmUtils {
}
}
/**
* Create Output Event Adapter Configuration for given configuration.
*
* @param name Output Event Adapter name
* @param type Output Event Adapter type
* @param msgFormat Output Event Adapter message format
* @return OutputEventAdapterConfiguration instance for given configuration
*/
private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);
outputEventAdapterConfiguration.setMessageFormat(msgFormat);
File configFile = new File(VirtualFireAlarmConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
Map<String, String> mqttAdapterProperties = new HashMap<>();
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
mqttAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(VirtualFireAlarmConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(VirtualFireAlarmConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.QOS_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLIENT_ID_PROPERTY_KEY, "");
mqttAdapterProperties.put(VirtualFireAlarmConstants.RESOURCE, "output-event");
outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties);
}
return outputEventAdapterConfiguration;
}
/**
* Create Output Event Adapter Configuration for given configuration.
*
@ -198,57 +143,23 @@ public class VirtualFireAlarmUtils {
inputEventAdapterConfiguration.setName(name);
inputEventAdapterConfiguration.setType(type);
inputEventAdapterConfiguration.setMessageFormat(msgFormat);
File configFile = new File(VirtualFireAlarmConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
Map<String, String> mqttAdapterProperties = new HashMap<>();
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
mqttAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(VirtualFireAlarmConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(VirtualFireAlarmConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.QOS_PROPERTY_KEY, properties.getProperty(
VirtualFireAlarmConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLIENT_ID_PROPERTY_KEY, "");
mqttAdapterProperties.put(VirtualFireAlarmConstants.TOPIC, VirtualFireAlarmConstants.SUBSCRIBED_TOPIC);
mqttAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_TRANSFORMATION,
VirtualFirealarmMqttContentTransformer.class.getName());
mqttAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_VALIDATION, "default");
mqttAdapterProperties.put(VirtualFireAlarmConstants.RESOURCE, "input-event");
inputEventAdapterConfiguration.setProperties(mqttAdapterProperties);
}
return inputEventAdapterConfiguration;
}
Map<String, String> mqttAdapterProperties = new HashMap<>();
mqttAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, MqttConfig.getInstance().getUsername());
mqttAdapterProperties.put(VirtualFireAlarmConstants.DCR_PROPERTY_KEY, MqttConfig.getInstance().getDcrUrl());
mqttAdapterProperties.put(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY, MqttConfig.getInstance().getUrl());
mqttAdapterProperties.put(VirtualFireAlarmConstants.SCOPES_PROPERTY_KEY, MqttConfig.getInstance().getScopes());
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLEAR_SESSION_PROPERTY_KEY, MqttConfig.getInstance()
.getClearSession());
mqttAdapterProperties.put(VirtualFireAlarmConstants.QOS_PROPERTY_KEY, MqttConfig.getInstance().getQos());
mqttAdapterProperties.put(VirtualFireAlarmConstants.CLIENT_ID_PROPERTY_KEY, "");
mqttAdapterProperties.put(VirtualFireAlarmConstants.TOPIC, VirtualFireAlarmConstants.SUBSCRIBED_TOPIC);
mqttAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_TRANSFORMATION,
VirtualFirealarmMqttContentTransformer.class.getName());
mqttAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_VALIDATION, "default");
mqttAdapterProperties.put(VirtualFireAlarmConstants.RESOURCE, "input-event");
inputEventAdapterConfiguration.setProperties(mqttAdapterProperties);
public static String replaceMqttProperty(String urlWithPlaceholders) {
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(VirtualFireAlarmConstants.MQTT_PORT, "" +
(VirtualFireAlarmConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(VirtualFireAlarmConstants.MQTT_BROKER_HOST,
System.getProperty(VirtualFireAlarmConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
return urlWithPlaceholders;
}
private static int getPortOffset() {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
VirtualFireAlarmConstants.CARBON_CONFIG_PORT_OFFSET));
try {
if ((portOffset != null)) {
return Integer.parseInt(portOffset.trim());
} else {
return VirtualFireAlarmConstants.CARBON_DEFAULT_PORT_OFFSET;
}
} catch (NumberFormatException e) {
return VirtualFireAlarmConstants.CARBON_DEFAULT_PORT_OFFSET;
}
return inputEventAdapterConfiguration;
}
public static String extractMessageFromPayload(String message, PublicKey verifySignatureKey)
@ -357,12 +268,11 @@ public class VirtualFireAlarmUtils {
inputEventAdapterConfiguration.setMessageFormat(msgFormat);
Map<String, String> xmppAdapterProperties = new HashMap<>();
XmppConfig xmppConfig = XmppConfig.getInstance();
xmppAdapterProperties.put(VirtualFireAlarmConstants.HOST_KEY, xmppConfig.getXmppServerIP());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort()));
xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword());
xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()
+ "/input-adapter");
xmppAdapterProperties.put(VirtualFireAlarmConstants.HOST_KEY, xmppConfig.getHost());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getPort()));
xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getUsername());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getPassword());
xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getJid());
xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_TRANSFORMATION,
VirtualFirealarmXmppContentTransformer.class.getName());
xmppAdapterProperties.put(VirtualFireAlarmConstants.CONTENT_VALIDATION, "default");
@ -370,39 +280,4 @@ public class VirtualFireAlarmUtils {
return inputEventAdapterConfiguration;
}
public static void setupXmppOutputAdapter() throws IOException {
if(!XmppConfig.getInstance().isEnabled()) return;
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createXmppOutputEventAdapterConfiguration(VirtualFireAlarmConstants.XMPP_ADAPTER_NAME,
VirtualFireAlarmConstants.XMPP_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
VirtualFirealarmManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + VirtualFireAlarmConstants.MQTT_ADAPTER_NAME, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
private static OutputEventAdapterConfiguration createXmppOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);
outputEventAdapterConfiguration.setMessageFormat(msgFormat);
Map<String, String> xmppAdapterProperties = new HashMap<>();
XmppConfig xmppConfig = XmppConfig.getInstance();
xmppAdapterProperties.put(VirtualFireAlarmConstants.HOST_KEY, xmppConfig.getXmppServerIP());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PORT_KEY, String.valueOf(xmppConfig.getXmppServerPort()));
xmppAdapterProperties.put(VirtualFireAlarmConstants.USERNAME_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminUsername());
xmppAdapterProperties.put(VirtualFireAlarmConstants.PASSWORD_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminPassword());
xmppAdapterProperties.put(VirtualFireAlarmConstants.JID_PROPERTY_KEY, xmppConfig.getVirtualFirealarmAdminJID()
+ "/output-adapter");
outputEventAdapterConfiguration.setStaticProperties(xmppAdapterProperties);
return outputEventAdapterConfiguration;
}
}

@ -13,8 +13,8 @@ import java.util.Map;
public class VirtualFirealarmMqttContentTransformer implements ContentTransformer {
@Override
public Object transform(Object message, Map<String, String> dynamicProperties) {
String topic = dynamicProperties.get("topic");
public Object transform(Object message, Map<String, Object> dynamicProperties) {
String topic = (String) dynamicProperties.get("topic");
String[] topicParams = topic.split("/");
String tenantDomain = topicParams[0];
String deviceId = topicParams[2];

@ -21,7 +21,6 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppUtil;
import java.io.IOException;
@ -35,14 +34,11 @@ public class VirtualFirealarmStartupListener implements ServerStartupObserver {
@Override
public void completedServerStartup() {
try {
XmppUtil.createXMPPAccountForDeviceType();
VirtualFireAlarmUtils.setupMqttOutputAdapter();
VirtualFireAlarmUtils.setupMqttInputAdapter();
VirtualFireAlarmUtils.setupXmppInputAdapter();
VirtualFireAlarmUtils.setupXmppOutputAdapter();
} catch (IOException e) {
log.error("Failed to intilaize the virtual firealarm output adapter", e);
log.error("Failed to intilaize the virtual firealarm input adapter", e);
}
}

@ -12,9 +12,9 @@ import java.util.Map;
public class VirtualFirealarmXmppContentTransformer implements ContentTransformer {
@Override
public Object transform(Object message, Map<String, String> dynamicProperties) {
String from = dynamicProperties.get("from");
String subject = dynamicProperties.get("subject");
public Object transform(Object message, Map<String, Object> dynamicProperties) {
String from = (String) dynamicProperties.get("from");
String subject = (String) dynamicProperties.get("subject");
int indexOfAt = from.indexOf("@");
int indexOfSlash = from.indexOf("/");
@ -26,7 +26,7 @@ public class VirtualFirealarmXmppContentTransformer implements ContentTransforme
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(subject, true);
Long serialNo = (Long) jsonPayload.get(VirtualFireAlarmConstants.JSON_SERIAL_KEY);
Integer serialNo = (Integer) jsonPayload.get(VirtualFireAlarmConstants.JSON_SERIAL_KEY);
// the hash-code of the deviceId is used as the alias for device certificates during SCEP enrollment.
// hence, the same is used here to fetch the device-specific-certificate from the key store.
PublicKey clientPublicKey = VirtualFireAlarmUtils.getDevicePublicKey("" + serialNo);

@ -20,19 +20,18 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFireAlarmManagerService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* DataHolder class of virtual firealarm plugins component.
*/
public class VirtualFirealarmManagementDataHolder {
private OutputEventAdapterService outputEventAdapterService;
private InputEventAdapterService inputEventAdapterService;
private EventsPublisherService eventsPublisherService;
private CertificateManagementService certificateManagementService;
private DeviceTypeConfigService deviceTypeConfigService;
private static VirtualFirealarmManagementDataHolder thisInstance = new VirtualFirealarmManagementDataHolder();
@ -43,15 +42,6 @@ public class VirtualFirealarmManagementDataHolder {
return thisInstance;
}
public OutputEventAdapterService getOutputEventAdapterService() {
return outputEventAdapterService;
}
public void setOutputEventAdapterService(
OutputEventAdapterService outputEventAdapterService) {
this.outputEventAdapterService = outputEventAdapterService;
}
public InputEventAdapterService getInputEventAdapterService() {
return inputEventAdapterService;
}
@ -76,4 +66,13 @@ public class VirtualFirealarmManagementDataHolder {
public void setCertificateManagementService(CertificateManagementService certificateManagementService) {
this.certificateManagementService = certificateManagementService;
}
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
}

@ -27,25 +27,18 @@ import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFireAlarmManagerService;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFireAlarmUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmStartupListener;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.VirtualFireAlarmConfig;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal
* .VirtualFirealarmManagementServiceComponent"
* immediate="true"
* @scr.reference name="event.output.adapter.service"
* interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOutputEventAdapterService"
* unbind="unsetOutputEventAdapterService"
* @scr.reference name="event.input.adapter.service"
* interface="org.wso2.carbon.event.input.adapter.core.InputEventAdapterService"
* cardinality="1..1"
@ -64,6 +57,12 @@ import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
* policy="dynamic"
* bind="setEventsPublisherService"
* unbind="unsetEventsPublisherService"
* @scr.reference name="devicetype.configuration.service"
* interface="org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService"
* cardinality="1..1"
* policy="dynamic"
* bind="setDeviceTypeConfigService"
* unbind="unsetDeviceTypeConfigService"
*/
public class VirtualFirealarmManagementServiceComponent {
@ -75,8 +74,6 @@ public class VirtualFirealarmManagementServiceComponent {
log.debug("Activating Virtual Firealarm Device Management Service Component");
}
try {
/* Initializing Virtual Fire Alarm Configuration */
VirtualFireAlarmConfig.init();
VirtualFireAlarmManagerService virtualFireAlarmManagerService = new VirtualFireAlarmManagerService();
BundleContext bundleContext = ctx.getBundleContext();
@ -121,22 +118,6 @@ public class VirtualFirealarmManagementServiceComponent {
}
}
/**
* Initialize the Output EventAdapter Service dependency
*
* @param outputEventAdapterService Output EventAdapter Service reference
*/
protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
VirtualFirealarmManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
VirtualFirealarmManagementDataHolder.getInstance().setOutputEventAdapterService(null);
}
/**
* Initialize the Input EventAdapter Service dependency
*
@ -168,4 +149,12 @@ public class VirtualFirealarmManagementServiceComponent {
protected void unsetEventsPublisherService(EventsPublisherService eventsPublisherService) {
VirtualFirealarmManagementDataHolder.getInstance().setEventsPublisherService(null);
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
VirtualFirealarmManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
VirtualFirealarmManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

@ -1,93 +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.
*
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Document;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.exception.InvalidConfigurationStateException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.config.exception.VirtualFireAlarmConfigurationException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.util.VirtualFireAlarmUtil;
import org.wso2.carbon.utils.CarbonUtils;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
@XmlRootElement(name = "DeviceManagementConfiguration")
public class VirtualFireAlarmConfig {
private DeviceManagementConfigRepository deviceManagementConfigRepository;
private PushNotificationConfig pushNotificationConfig;
private static VirtualFireAlarmConfig config;
private static final Log log = LogFactory.getLog(VirtualFireAlarmConfig.class);
private static final String VIRTUAL_FIRE_ALARM_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugins" + File.separator +
"virtual-fire-alarm" + File.separator + "virtual-fire-alarm-config.xml";
private VirtualFireAlarmConfig() {
}
public static VirtualFireAlarmConfig getInstance() {
if (config == null) {
throw new InvalidConfigurationStateException("Webapp Authenticator Configuration is not " +
"initialized properly");
}
return config;
}
@XmlElement(name = "ManagementRepository", required = true)
public DeviceManagementConfigRepository getDeviceManagementConfigRepository() {
return deviceManagementConfigRepository;
}
public void setDeviceManagementConfigRepository(DeviceManagementConfigRepository deviceManagementConfigRepository) {
this.deviceManagementConfigRepository = deviceManagementConfigRepository;
}
@XmlElement(name = "PushNotificationConfiguration", required = false)
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}
public void setPushNotificationConfig(PushNotificationConfig pushNotificationConfig) {
this.pushNotificationConfig = pushNotificationConfig;
}
public static void init() throws VirtualFireAlarmConfigurationException {
try {
File authConfig = new File(VirtualFireAlarmConfig.VIRTUAL_FIRE_ALARM_CONFIG_PATH);
Document doc = VirtualFireAlarmUtil.convertToDocument(authConfig);
/* Un-marshaling Webapp Authenticator configuration */
JAXBContext ctx = JAXBContext.newInstance(VirtualFireAlarmConfig.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
config = (VirtualFireAlarmConfig) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new VirtualFireAlarmConfigurationException("Error occurred while un-marshalling Virtual Fire Alarm " +
" Config", e);
}
}
}

@ -20,32 +20,60 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFireAlarmUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.List;
public class MqttConfig {
private static String brokerEndpoint;
private static MqttConfig mqttConfig = new MqttConfig();
private static final Log log = LogFactory.getLog(MqttConfig.class);
private boolean enabled;
private String url;
private String username;
private String dcrUrl;
private String qos;
private String scopes;
private String clearSession;
private MqttConfig() {
File configFile = new File(VirtualFireAlarmConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
brokerEndpoint = VirtualFireAlarmUtils.replaceMqttProperty(
properties.getProperty(VirtualFireAlarmConstants.BROKER_URL_PROPERTY_KEY));
} catch (IOException e) {
log.error("Failed to read the mqtt.properties file" + e);
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
List<PushNotificationConfig.Property> properties = deviceManagementConfiguration
.getPushNotificationConfig().getProperties();
String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider();
if (provider.equals("MQTT")) {
enabled = true;
}
if (enabled) {
for (PushNotificationConfig.Property property : properties) {
switch (property.getName()) {
case "url":
url = property.getValue();
break;
case "username":
username = property.getValue();
break;
case "dcrUrl":
dcrUrl = property.getValue();
break;
case "qos":
qos = property.getValue();
break;
case "scopes":
scopes = property.getValue();
break;
case "clearSession":
clearSession = property.getValue();
break;
}
}
}
}
@ -54,7 +82,31 @@ public class MqttConfig {
return mqttConfig;
}
public String getBrokerEndpoint() {
return brokerEndpoint;
public boolean isEnabled() {
return enabled;
}
public String getUrl() {
return url;
}
public String getUsername() {
return username;
}
public String getDcrUrl() {
return dcrUrl;
}
public String getQos() {
return qos;
}
public String getScopes() {
return scopes;
}
public String getClearSession() {
return clearSession;
}
}

@ -20,87 +20,118 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFireAlarmUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import java.util.List;
public class XmppConfig {
private String xmppServerIP;
private int xmppServerPort;
private String xmppUsername;
private String xmppPassword;
private boolean isEnabled;
private String virtualFirealarmAdminUsername;
private String virtualFirealarmAdminPassword;
private String virtualFirealarmAdminJID;
private String xmppServerName;
private String host;
private int port;
private String username;
private String password;
private String serverName;
private boolean enabled;
private String jid;
private static XmppConfig xmppConfig = new XmppConfig();
private static final Log log = LogFactory.getLog(XmppConfig.class);
private XmppConfig() {
File configFile = new File(VirtualFireAlarmConstants.XMPP_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
xmppServerIP = properties.getProperty(VirtualFireAlarmConstants.HOST_KEY);
xmppServerName = properties.getProperty(VirtualFireAlarmConstants.SERVER_NAME);
xmppServerPort = Integer.parseInt(properties.getProperty(VirtualFireAlarmConstants.PORT_KEY));
isEnabled = Boolean.parseBoolean(properties.getProperty(VirtualFireAlarmConstants.IS_ENABLED_KEY));
xmppUsername = properties.getProperty(VirtualFireAlarmConstants.ADMIN_USERNAME);
xmppPassword = properties.getProperty(VirtualFireAlarmConstants.ADMIN_PASSWORD);
virtualFirealarmAdminUsername = "wso2admin_" + VirtualFireAlarmConstants.DEVICE_TYPE;
virtualFirealarmAdminJID = virtualFirealarmAdminUsername + "@" + xmppServerName;
virtualFirealarmAdminPassword = VirtualFireAlarmConstants.XMPP_SERVER_PASSWORD;
} catch (IOException e) {
log.error(e);
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE,
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
List<PushNotificationConfig.Property> properties = deviceManagementConfiguration.getPushNotificationConfig()
.getProperties();
String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider();
if (provider.equals("XMPP")) {
enabled = true;
}
if (enabled) {
for (PushNotificationConfig.Property property : properties) {
switch (property.getName()) {
case "host":
host = property.getValue();
break;
case "port":
port = Integer.parseInt(property.getValue());
break;
case "username":
username = property.getValue();
break;
case "password":
password = property.getValue();
break;
case "server.name":
serverName = property.getValue();
break;
case "jid":
jid = property.getValue();
break;
}
}
}
}
public String getXmppServerIP() {
return xmppServerIP;
public static XmppConfig getInstance() {
return xmppConfig;
}
public int getXmppServerPort() {
return xmppServerPort;
public String getHost() {
return host;
}
public String getXmppUsername() {
return xmppUsername;
public void setHost(String host) {
this.host = host;
}
public String getXmppPassword() {
return xmppPassword;
public int getPort() {
return port;
}
public boolean isEnabled() {
return isEnabled;
public void setPort(int port) {
this.port = port;
}
public static XmppConfig getInstance() {
return xmppConfig;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getVirtualFirealarmAdminUsername() {
return virtualFirealarmAdminUsername;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getServerName() {
return serverName;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
public boolean isEnabled() {
return enabled;
}
public String getVirtualFirealarmAdminPassword() {
return virtualFirealarmAdminPassword;
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getVirtualFirealarmAdminJID() {
return virtualFirealarmAdminJID;
public String getJid() {
return jid;
}
public String getXmppServerName() {
return xmppServerName;
public void setJid(String jid) {
this.jid = jid;
}
}

@ -29,36 +29,39 @@ import java.util.Map;
public class XmppServerClient {
public static boolean createAccount(XmppAccount xmppAccount)
throws VirtualFirealarmDeviceMgtPluginException {
if (xmppAccount != null) {
try {
ConnectionConfiguration config = new ConnectionConfiguration(XmppConfig.getInstance().getXmppServerIP(),
XmppConfig.getInstance().getXmppServerPort(),
"Accounts");
XMPPConnection xmppConnection = new XMPPConnection(config);
xmppConnection.connect();
xmppConnection.login(XmppConfig.getInstance().getXmppUsername(), XmppConfig.getInstance().getXmppPassword());
AccountManager accountManager = xmppConnection.getAccountManager();
Map<String, String> attributes = new HashMap<>();
attributes.put("username", xmppAccount.getUsername());
attributes.put("password", xmppAccount.getPassword());
attributes.put("email", xmppAccount.getEmail());
attributes.put("name", xmppAccount.getAccountName());
accountManager.createAccount(xmppAccount.getUsername(), xmppAccount.getPassword(), attributes);
xmppConnection.disconnect();
return true;
} catch (XMPPException e) {
if (e.getXMPPError().getCode() == 409) {
//AccountAlreadyExist
public static boolean createAccount(XmppAccount xmppAccount) throws VirtualFirealarmDeviceMgtPluginException {
if (XmppConfig.getInstance().isEnabled()) {
if (xmppAccount != null) {
try {
ConnectionConfiguration config = new ConnectionConfiguration(XmppConfig.getInstance().getHost(),
XmppConfig.getInstance().getPort(),
"Accounts");
XMPPConnection xmppConnection = new XMPPConnection(config);
xmppConnection.connect();
xmppConnection.login(XmppConfig.getInstance().getUsername(), XmppConfig.getInstance().getPassword());
AccountManager accountManager = xmppConnection.getAccountManager();
Map<String, String> attributes = new HashMap<>();
attributes.put("username", xmppAccount.getUsername());
attributes.put("password", xmppAccount.getPassword());
attributes.put("email", xmppAccount.getEmail());
attributes.put("name", xmppAccount.getAccountName());
accountManager.createAccount(xmppAccount.getUsername(), xmppAccount.getPassword(), attributes);
xmppConnection.disconnect();
return true;
} else {
throw new VirtualFirealarmDeviceMgtPluginException(
"XMPP account creation failed. Error: " + e.getLocalizedMessage(), e);
} catch (XMPPException e) {
if (e.getXMPPError().getCode() == 409) {
//AccountAlreadyExist
return true;
} else {
throw new VirtualFirealarmDeviceMgtPluginException(
"XMPP account creation failed. Error: " + e.getLocalizedMessage(), e);
}
}
} else {
throw new VirtualFirealarmDeviceMgtPluginException("Invalid XMPP attributes");
}
} else {
throw new VirtualFirealarmDeviceMgtPluginException("Invalid XMPP attributes");
return true;
}
}
}

@ -1,46 +0,0 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
/**
* This holds the utility class related to XMPP.
*/
public class XmppUtil {
private static final Log log = LogFactory.getLog(XmppUtil.class);
public static void createXMPPAccountForDeviceType() {
if (!XmppConfig.getInstance().isEnabled()) {
return;
}
XmppServerClient xmppServerClient = new XmppServerClient();
try {
XmppAccount xmppAccount = new XmppAccount();
xmppAccount.setAccountName(XmppConfig.getInstance().getVirtualFirealarmAdminUsername());
xmppAccount.setUsername(XmppConfig.getInstance().getVirtualFirealarmAdminUsername());
xmppAccount.setPassword(XmppConfig.getInstance().getVirtualFirealarmAdminPassword());
xmppAccount.setEmail(XmppConfig.getInstance().getVirtualFirealarmAdminJID());
xmppServerClient.createAccount(xmppAccount);
} catch (VirtualFirealarmDeviceMgtPluginException e) {
String errorMsg = "An error was encountered whilst trying to create Server XMPP account for device-type - "
+ VirtualFireAlarmConstants.DEVICE_TYPE;
log.error(errorMsg, e);
}
}
}

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<DeviceManagementConfiguration>
<DeviceType>android_sense</DeviceType>
<ManagementRepository>
<DataSourceConfiguration>
<JndiLookupDefinition>
<Name>jdbc/AndroidSenseDM_DB</Name>
</JndiLookupDefinition>
</DataSourceConfiguration>
<ProvisioningConfig>
<TenantDomain>carbon.super</TenantDomain>
<SharedWithAllTenants>false</SharedWithAllTenants>
</ProvisioningConfig>
</ManagementRepository>
<PushNotificationConfiguration>
<!--MQTT Config-->
<PushNotificationProvider>MQTT</PushNotificationProvider>
<Properties>
<Property Name="mqtt.adapter.name">androidsense.mqtt.adapter</Property>
<Property Name="url">tcp://localhost:1883</Property>
<Property Name="username">admin</Property>
<Property Name="dcrUrl">https://localhost:9443/dynamic-client-web/register</Property>
<Property Name="qos">0</Property>
<Property Name="scopes"/>
<Property Name="clearSession">true</Property>
</Properties>
</PushNotificationConfiguration>
</DeviceManagementConfiguration>

@ -9,6 +9,7 @@ org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../depl
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/conf/android-sense-config.xml,target:${installFolder}/../../conf/etc/device-mgt-plugins/android-sense-config.xml,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/android_sense.war);\
@ -23,3 +24,4 @@ org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../dep
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.platform.configuration);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.android_sense.realtime.analytics-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/carbonapps/android_sense.car);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/etc/device-mgt-plugins/android-sense-config.xml);\

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<DeviceManagementConfiguration>
<DeviceType>arduino</DeviceType>
<ManagementRepository>
<DataSourceConfiguration>
<JndiLookupDefinition>
<Name>jdbc/ArduinoDM_DB</Name>
</JndiLookupDefinition>
</DataSourceConfiguration>
<ProvisioningConfig>
<TenantDomain>carbon.super</TenantDomain>
<SharedWithAllTenants>false</SharedWithAllTenants>
</ProvisioningConfig>
</ManagementRepository>
</DeviceManagementConfiguration>

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save