Merge pull request #397 from ayyoob/st2

refactored existing device types to support deployer
This commit is contained in:
Charitha Goonetilleke 2016-11-02 13:04:52 +05:30 committed by GitHub
commit c2bfb7cce0
124 changed files with 1368 additions and 6098 deletions

View File

@ -44,24 +44,7 @@
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS --> <!--JAX-RS -->
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>org.codehaus.jackson</groupId>
@ -82,12 +65,6 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
@ -171,6 +148,11 @@
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>

View File

@ -30,12 +30,10 @@ 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.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil; 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.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import javax.ws.rs.*; import javax.ws.rs.*;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@ -283,8 +281,8 @@ public class AndroidSenseServiceImpl implements AndroidSenseService {
AndroidConfiguration androidConfiguration = new AndroidConfiguration(); AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain()); androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = DEFAULT_MQTT_ENDPOINT; String mqttEndpoint = DEFAULT_MQTT_ENDPOINT;
if (mqttEndpoint.contains(Constants.LOCALHOST)) { if (mqttEndpoint.contains(AndroidSenseConstants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getServerUrl()); mqttEndpoint = mqttEndpoint.replace(AndroidSenseConstants.LOCALHOST, APIUtil.getServerUrl());
} }
androidConfiguration.setMqttEndpoint(mqttEndpoint); androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.ok(androidConfiguration.toString()).build(); return Response.ok(androidConfiguration.toString()).build();

View File

@ -14,17 +14,11 @@
* limitations under the License. * limitations under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants; package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
public class AndroidSenseConstants { public class AndroidSenseConstants {
public final static String DEVICE_TYPE = "android_sense"; 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 Sensor names //Android Sensor names
public static final String SENSOR_ACCELEROMETER = "accelerometer"; public static final String SENSOR_ACCELEROMETER = "accelerometer";
@ -39,9 +33,13 @@ public class AndroidSenseConstants {
public static final String SENSOR_ROTATION = "rotation"; public static final String SENSOR_ROTATION = "rotation";
public static final String SENSOR_WORDCOUNT = "wordcounter"; public static final String SENSOR_WORDCOUNT = "wordcounter";
//MQTT Subscribe topic //MQTT Subscribe topic
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants //mqtt tranport related constants
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic"; public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";
public static final String HOST_NAME = "HostName";
public static final String LOCALHOST = "localhost";
public static final String CONFIG_TYPE = "general";
public static final String DEFAULT_ENDPOINT = "tcp://localhost:1883";
} }

View File

@ -10,6 +10,7 @@ import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.Record; import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
@ -18,13 +19,13 @@ 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.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.util.Utils; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.constants.AndroidSenseConstants;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService; import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.NetworkUtils;
import java.net.SocketException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -204,10 +205,10 @@ public class APIUtil {
} }
public static String getMqttEndpoint() throws ConfigurationManagementException { public static String getMqttEndpoint() throws ConfigurationManagementException {
String iotServerIP = Constants.DEFAULT_ENDPOINT; String iotServerIP = AndroidSenseConstants.DEFAULT_ENDPOINT;
iotServerIP = iotServerIP.replace(Constants.LOCALHOST, Utils.getServerUrl());; iotServerIP = iotServerIP.replace(AndroidSenseConstants.LOCALHOST, getServerUrl());;
PlatformConfiguration configuration = APIUtil.getTenantConfigurationManagementService().getConfiguration( PlatformConfiguration configuration = APIUtil.getTenantConfigurationManagementService().getConfiguration(
Constants.CONFIG_TYPE); AndroidSenseConstants.CONFIG_TYPE);
if (configuration != null && configuration.getConfiguration() != null && configuration if (configuration != null && configuration.getConfiguration() != null && configuration
.getConfiguration().size() > 0) { .getConfiguration().size() > 0) {
List<ConfigurationEntry> configurations = configuration.getConfiguration(); List<ConfigurationEntry> configurations = configuration.getConfiguration();
@ -221,4 +222,17 @@ public class APIUtil {
} }
return iotServerIP; return iotServerIP;
} }
public static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(AndroidSenseConstants.HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
log.warn("Failed retrieving the hostname, therefore set to localhost", e);
}
return hostName;
}
} }

View File

@ -1,30 +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.service.impl.util;
import org.wso2.carbon.user.core.Permission;
/**
* This hold the constants related to the device type.
*/
public class Constants {
public static final String LOCALHOST = "localhost";
public static final String CONFIG_TYPE = "general";
public static final String DEFAULT_ENDPOINT = "tcp://localhost:1883";
}

View File

@ -1,116 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- ~ 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. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>androidsense-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.2.6-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.plugin</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - AndroidSense DeviceType Plugin</name>
<description>WSO2 Carbon - AndroidSense DeviceType Plugin Implementation</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.base,
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.core.util,
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,
org.wso2.carbon.device.mgt.iot.androidsense.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<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>

View File

@ -1,56 +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.exception;
public class AndroidSenseDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public AndroidSenseDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public AndroidSenseDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public AndroidSenseDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public AndroidSenseDeviceMgtPluginException() {
super();
}
public AndroidSenseDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

View File

@ -1,256 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.exception.AndroidSenseDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.feature.AndroidSenseFeatureManager;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.dao.AndroidSenseDAOUtil;
import java.util.List;
/**
* This represents the Android implementation of DeviceManagerService.
*/
public class AndroidSenseManager implements DeviceManager {
private static final AndroidSenseDAOUtil androidSenseDAO = new AndroidSenseDAOUtil();
private static final Log log = LogFactory.getLog(AndroidSenseManager.class);
private FeatureManager androidSenseFeatureManager = new AndroidSenseFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return androidSenseFeatureManager;
}
@Override
public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException {
//TODO implement this
return false;
}
@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Android device : " + device.getDeviceIdentifier());
}
AndroidSenseDAOUtil.beginTransaction();
status = androidSenseDAO.getDeviceDAO().addDevice(device);
AndroidSenseDAOUtil.commitTransaction();
} catch (AndroidSenseDeviceMgtPluginException e) {
try {
AndroidSenseDAOUtil.rollbackTransaction();
} catch (AndroidSenseDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Android device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Android device enrollment data");
}
AndroidSenseDAOUtil.beginTransaction();
status = androidSenseDAO.getDeviceDAO().updateDevice(device);
AndroidSenseDAOUtil.commitTransaction();
} catch (AndroidSenseDeviceMgtPluginException e) {
try {
AndroidSenseDAOUtil.rollbackTransaction();
} catch (AndroidSenseDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Android device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Android device : " + deviceId);
}
AndroidSenseDAOUtil.beginTransaction();
status = androidSenseDAO.getDeviceDAO().deleteDevice(deviceId.getId());
AndroidSenseDAOUtil.commitTransaction();
} catch (AndroidSenseDeviceMgtPluginException e) {
try {
AndroidSenseDAOUtil.rollbackTransaction();
} catch (AndroidSenseDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Android device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Android device : " + deviceId.getId());
}
Device iotDevice = androidSenseDAO.getDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (AndroidSenseDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Android device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Android device : " + deviceId.getId());
}
device = androidSenseDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (AndroidSenseDeviceMgtPluginException e) {
String msg = "Error while fetching the Android device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Android device : " + deviceIdentifier);
}
AndroidSenseDAOUtil.beginTransaction();
status = androidSenseDAO.getDeviceDAO().updateDevice(device);
AndroidSenseDAOUtil.commitTransaction();
} catch (AndroidSenseDeviceMgtPluginException e) {
try {
AndroidSenseDAOUtil.rollbackTransaction();
} catch (AndroidSenseDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Android device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Android devices");
}
devices = androidSenseDAO.getDeviceDAO().getAllDevices();
} catch (AndroidSenseDeviceMgtPluginException e) {
String msg = "Error while fetching all Android devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

View File

@ -1,61 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
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.androidsense.plugin.constants.AndroidSenseConstants;
public class AndroidSenseManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return AndroidSenseConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager=new AndroidSenseManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(AndroidSenseConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
}

View File

@ -1,197 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
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.impl.util.AndroidSenseUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements dao impl for android Devices.
*/
public class AndroidSenseDAO {
private static final Log log = LogFactory.getLog(AndroidSenseDAO.class);
public Device getDevice(String deviceId) throws AndroidSenseDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = AndroidSenseDAOUtil.getConnection();
String selectDBQuery =
"SELECT ANDROID_DEVICE_ID, DEVICE_NAME" +
" FROM ANDROID_SENSE_DEVICE WHERE ANDROID_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
device.setName(resultSet.getString(AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Android device " + deviceId + " data has been fetched from " +
"Android database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Android device : '" + deviceId + "'";
log.error(msg, e);
throw new AndroidSenseDeviceMgtPluginException(msg, e);
} finally {
AndroidSenseUtils.cleanupResources(stmt, resultSet);
AndroidSenseDAOUtil.closeConnection();
}
return device;
}
public boolean addDevice(Device device)throws AndroidSenseDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = AndroidSenseDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO ANDROID_SENSE_DEVICE(ANDROID_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + device.getDeviceIdentifier() + " data has been" +
" added to the Android database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Android device '" + device.getDeviceIdentifier()
+ "' to the Android db.";
log.error(msg, e);
throw new AndroidSenseDeviceMgtPluginException(msg, e);
} finally {
AndroidSenseUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws AndroidSenseDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = AndroidSenseDAOUtil.getConnection();
String updateDBQuery =
"UPDATE ANDROID_SENSE_DEVICE SET DEVICE_NAME = ? WHERE ANDROID_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + device.getDeviceIdentifier() + " data has been modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Android device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new AndroidSenseDeviceMgtPluginException(msg, e);
} finally {
AndroidSenseUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String deviceId) throws AndroidSenseDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = AndroidSenseDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM ANDROID_SENSE_DEVICE WHERE ANDROID_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Android device " + deviceId + " data has deleted from the Android database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Android device " + deviceId;
log.error(msg, e);
throw new AndroidSenseDeviceMgtPluginException(msg, e);
} finally {
AndroidSenseUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws AndroidSenseDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> iotDevices = new ArrayList<>();
try {
conn = AndroidSenseDAOUtil.getConnection();
String selectDBQuery =
"SELECT ANDROID_DEVICE_ID, DEVICE_NAME FROM ANDROID_SENSE_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(AndroidSenseConstants.DEVICE_PLUGIN_DEVICE_NAME));
iotDevices.add(device);
}
if (log.isDebugEnabled()) {
log.debug("All Android device details have fetched from Android database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Android device data'";
log.error(msg, e);
throw new AndroidSenseDeviceMgtPluginException(msg, e);
} finally {
AndroidSenseUtils.cleanupResources(stmt, resultSet);
AndroidSenseDAOUtil.closeConnection();
}
}
}

View File

@ -1,130 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.dao;
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;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class AndroidSenseDAOUtil {
private static final Log log = LogFactory.getLog(AndroidSenseDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public AndroidSenseDAOUtil() {
initAndroidDAO();
}
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(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + datasource, e);
}
}
public AndroidSenseDAO getDeviceDAO() {
return new AndroidSenseDAO();
}
public static void beginTransaction() throws AndroidSenseDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new AndroidSenseDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws AndroidSenseDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new AndroidSenseDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws AndroidSenseDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new AndroidSenseDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws AndroidSenseDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws AndroidSenseDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new AndroidSenseDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.feature;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import java.util.List;
public class AndroidSenseFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(AndroidSenseConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(AndroidSenseConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

View File

@ -1,111 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.impl.util;
import org.apache.commons.logging.Log;
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.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;
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.sql.Connection;
import java.sql.PreparedStatement;
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 plugin.
*/
public class AndroidSenseUtils {
private static Log log = LogFactory.getLog(AndroidSenseUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* 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(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
String checkSql = "select * from ANDROID_SENSE_DEVICE";
if (!initializer.isDatabaseStructureCreated(checkSql)) {
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} else {
log.info("Device management repository database already exists. Not creating a new database.");
}
} catch (NamingException 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);
}
}
}

View File

@ -1,52 +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.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator + AndroidSenseConstants.DEVICE_TYPE
+ File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

View File

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

View File

@ -1,117 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.plugin.internal;
import org.apache.commons.logging.Log;
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.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.AndroidSenseUtils;
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="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 {
private ServiceRegistration androidServiceRegRef;
private static final Log log = LogFactory.getLog(AndroidSenseManagementServiceComponent.class);
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Android Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
androidServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(), new AndroidSenseManagerService(), null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
AndroidSenseUtils.setupDeviceManagementSchema();
} catch (AndroidSenseDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("Android Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Android Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Android Device Management Service Component");
}
try {
if (androidServiceRegRef != null) {
androidServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug(
"Android Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Android Device Management bundle", e);
}
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to service component");
}
}
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);
}
}

View File

@ -35,7 +35,6 @@
<modules> <modules>
<module>org.wso2.carbon.device.mgt.iot.androidsense.analytics</module> <module>org.wso2.carbon.device.mgt.iot.androidsense.analytics</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.api</module> <module>org.wso2.carbon.device.mgt.iot.androidsense.api</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.plugin</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.ui</module> <module>org.wso2.carbon.device.mgt.iot.androidsense.ui</module>
</modules> </modules>

View File

@ -109,13 +109,6 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT --> <!--IOT -->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
@ -123,16 +116,6 @@
<version>4.1</version> <version>4.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS --> <!--JAX-RS -->
<dependency> <dependency>
@ -153,19 +136,18 @@
<artifactId>jsr311-api</artifactId> <artifactId>jsr311-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.analytics</groupId> <groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId> <artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>

View File

@ -34,11 +34,11 @@ 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.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord; 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.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
@ -54,7 +54,6 @@ import java.util.*;
public class ArduinoServiceImpl implements ArduinoService { public class ArduinoServiceImpl implements ArduinoService {
private static Log log = LogFactory.getLog(ArduinoServiceImpl.class); private static Log log = LogFactory.getLog(ArduinoServiceImpl.class);
private static Map<String, LinkedList<String>> internalControlsQueue = new HashMap<>();
private static final String KEY_TYPE = "PRODUCTION"; private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey; private static ApiApplicationKey apiApplicationKey;

View File

@ -16,13 +16,10 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.arduino.plugin.constants; package org.wso2.carbon.device.mgt.iot.arduino.service.impl.constants;
public class ArduinoConstants { public class ArduinoConstants {
public final static String DEVICE_TYPE = "arduino"; 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 static final String URL_PREFIX = "http://"; public static final String URL_PREFIX = "http://";
//sensor events summerized table name //sensor events summerized table name

View File

@ -25,11 +25,9 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback; import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.wso2.carbon.context.PrivilegedCarbonContext;
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.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.constants.ArduinoConstants;
import javax.ws.rs.HttpMethod; import javax.ws.rs.HttpMethod;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.util; package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import java.io.File; import java.io.File;

View File

@ -18,20 +18,38 @@
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util; package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; 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.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.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** /**
* This is used to create a zip file that includes the necessary configuration required for the agent. * This is used to create a zip file that includes the necessary configuration required for the agent.
@ -40,6 +58,8 @@ public class ZipUtil {
private static final String HTTP_PORT_PROPERTY = "httpPort"; private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String CONFIG_TYPE = "general"; private static final String CONFIG_TYPE = "general";
private static final Log log = LogFactory.getLog(ZipUtil.class);
public static final String HOST_NAME = "HostName";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType, public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token, String deviceId, String deviceName, String token,
@ -52,7 +72,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getServerUrl(); iotServerIP = getServerUrl();
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
Map<String, String> contextParams = new HashMap<>(); Map<String, String> contextParams = new HashMap<>();
@ -88,7 +108,7 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile; ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -96,4 +116,227 @@ public class ZipUtil {
throw new DeviceManagementException("Failed to retrieve configuration", e); throw new DeviceManagementException("Failed to retrieve configuration", e);
} }
} }
private static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
log.warn("Failed retrieving the hostname, therefore set to localhost", e);
}
return hostName;
}
private static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams
, String zipFileName)
throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error("Failed closing connection", e);
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//read from file
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
if (origin != null) {
origin.close();
}
if (out != null) {
out.close();
}
}
return true;
}
} }

View File

@ -1,121 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.2.6-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - IoT Server Arduino Management Plugin</name>
<description>WSO2 Carbon - Arduino Management/Control Plugin Implementation</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>IoT Server Arduino Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.arduino.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
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.device.mgt.iot.devicetype.*
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.arduino.plugin.internal,
org.wso2.carbon.device.mgt.iot.arduino.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<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>

View File

@ -1,56 +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.arduino.plugin.exception;
public class ArduinoDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public ArduinoDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public ArduinoDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public ArduinoDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public ArduinoDeviceMgtPluginException() {
super();
}
public ArduinoDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

View File

@ -1,259 +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.arduino.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.dao.ArduinoDAOUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.feature.ArduinoFeatureManager;
import java.util.List;
/**
* This represents the Arduino implementation of DeviceManagerService.
*/
public class ArduinoManager implements DeviceManager {
private static final ArduinoDAOUtil arduinoDAO = new ArduinoDAOUtil();
private static final Log log = LogFactory.getLog(ArduinoManager.class);
private ArduinoFeatureManager arduinoFeatureManager = new ArduinoFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return arduinoFeatureManager;
}
@Override
public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException {
//TODO implement this
return false;
}
@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Arduino device : " + device.getDeviceIdentifier());
}
ArduinoDAOUtil.beginTransaction();
status = arduinoDAO.getDeviceDAO().addDevice(device);
ArduinoDAOUtil.commitTransaction();
} catch (ArduinoDeviceMgtPluginException e) {
try {
ArduinoDAOUtil.rollbackTransaction();
} catch (ArduinoDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Arduino device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Arduino device enrollment data");
}
ArduinoDAOUtil.beginTransaction();
status = arduinoDAO.getDeviceDAO().updateDevice(device);
ArduinoDAOUtil.commitTransaction();
} catch (ArduinoDeviceMgtPluginException e) {
try {
ArduinoDAOUtil.rollbackTransaction();
} catch (ArduinoDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Arduino device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Arduino device : " + deviceId);
}
ArduinoDAOUtil.beginTransaction();
status = arduinoDAO.getDeviceDAO().deleteDevice(deviceId.getId());
ArduinoDAOUtil.commitTransaction();
} catch (ArduinoDeviceMgtPluginException e) {
try {
ArduinoDAOUtil.rollbackTransaction();
} catch (ArduinoDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Arduino device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Arduino device : " + deviceId.getId());
}
Device iotDevice = arduinoDAO.getDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (ArduinoDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Arduino device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Arduino device : " + deviceId.getId());
}
device = arduinoDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (ArduinoDeviceMgtPluginException e) {
String msg = "Error while fetching the Arduino device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Arduino device : " + deviceIdentifier);
}
ArduinoDAOUtil.beginTransaction();
status = arduinoDAO.getDeviceDAO().updateDevice(device);
ArduinoDAOUtil.commitTransaction();
} catch (ArduinoDeviceMgtPluginException e) {
try {
ArduinoDAOUtil.rollbackTransaction();
} catch (ArduinoDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Arduino device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Arduino devices");
}
devices = arduinoDAO.getDeviceDAO().getAllDevices();
} catch (ArduinoDeviceMgtPluginException e) {
String msg = "Error while fetching all Arduino devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

View File

@ -1,65 +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.arduino.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
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.arduino.plugin.constants.ArduinoConstants;
public class ArduinoManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
@Override
public String getType() {
return ArduinoConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
deviceManager=new ArduinoManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(DEVICE_TYPE_PROVIDER_DOMAIN, false);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
}

View File

@ -1,132 +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.arduino.plugin.impl.dao;
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;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ArduinoDAOUtil {
private static final Log log = LogFactory.getLog(ArduinoDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public ArduinoDAOUtil() {
initArduinoDAO();
}
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(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + datasource, e);
}
}
public ArduinoDeviceDAO getDeviceDAO() {
return new ArduinoDeviceDAO();
}
public static void beginTransaction() throws ArduinoDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new ArduinoDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws ArduinoDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new ArduinoDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws ArduinoDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new ArduinoDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws ArduinoDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws ArduinoDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new ArduinoDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

View File

@ -1,196 +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.arduino.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.exception.ArduinoDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.util.ArduinoUtils;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements CRUD for arduino Devices.
*/
public class ArduinoDeviceDAO {
private static final Log log = LogFactory.getLog(ArduinoDeviceDAO.class);
public Device getDevice(String deviceId) throws ArduinoDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = ArduinoDAOUtil.getConnection();
String selectDBQuery =
"SELECT ARDUINO_DEVICE_ID, DEVICE_NAME FROM ARDUINO_DEVICE WHERE ARDUINO_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
device.setName(resultSet.getString(ArduinoConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Arduino device " + deviceId + " data has been fetched from " +
"Arduino database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Arduino device : '" + deviceId + "'";
log.error(msg, e);
throw new ArduinoDeviceMgtPluginException(msg, e);
} finally {
ArduinoUtils.cleanupResources(stmt, resultSet);
ArduinoDAOUtil.closeConnection();
}
return device;
}
public boolean addDevice(Device iotDevice) throws ArduinoDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ArduinoDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO ARDUINO_DEVICE(ARDUINO_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getDeviceIdentifier());
stmt.setString(2,iotDevice.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Arduino device " + iotDevice.getDeviceIdentifier() + " data has been" +
" added to the Arduino database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Arduino device '" +
iotDevice.getDeviceIdentifier() + "' to the Arduino db.";
log.error(msg, e);
throw new ArduinoDeviceMgtPluginException(msg, e);
} finally {
ArduinoUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device iotDevice) throws ArduinoDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ArduinoDAOUtil.getConnection();
String updateDBQuery =
"UPDATE ARDUINO_DEVICE SET DEVICE_NAME = ? WHERE ARDUINO_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, iotDevice.getName());
stmt.setString(2, iotDevice.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Arduino device " + iotDevice.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Arduino device '" + iotDevice.getDeviceIdentifier()
+ "' data.";
log.error(msg, e);
throw new ArduinoDeviceMgtPluginException(msg, e);
} finally {
ArduinoUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String iotDeviceId) throws ArduinoDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ArduinoDAOUtil.getConnection();
String deleteDBQuery =
"DELETE FROM ARDUINO_DEVICE WHERE ARDUINO_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Arduino device " + iotDeviceId + " data has deleted" +
" from the Arduino database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Arduino device " + iotDeviceId;
log.error(msg, e);
throw new ArduinoDeviceMgtPluginException(msg, e);
} finally {
ArduinoUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws ArduinoDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> devices = new ArrayList<Device>();
try {
conn = ArduinoDAOUtil.getConnection();
String selectDBQuery =
"SELECT ARDUINO_DEVICE_ID, DEVICE_NAME FROM ARDUINO_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(ArduinoConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(ArduinoConstants.DEVICE_PLUGIN_DEVICE_NAME));
}
if (log.isDebugEnabled()) {
log.debug("All Arduino device details have fetched from Arduino database.");
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Arduino device data'";
log.error(msg, e);
throw new ArduinoDeviceMgtPluginException(msg, e);
} finally {
ArduinoUtils.cleanupResources(stmt, resultSet);
ArduinoDAOUtil.closeConnection();
}
}
}

View File

@ -1,59 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.arduino.plugin.impl.feature;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import java.util.List;
public class ArduinoFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(ArduinoConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(ArduinoConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

View File

@ -1,125 +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.arduino.plugin.impl.util;
import org.apache.commons.logging.Log;
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;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Contains utility methods used by Arduino plugin.
*/
public class ArduinoUtils {
private static Log log = LogFactory.getLog(ArduinoUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for(Device.Property property :deviceProperties){
if(propertyKey.equals(property.getName())){
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* 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(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
String checkSql = "select * from ARDUINO_DEVICE";
if (!initializer.isDatabaseStructureCreated(checkSql)) {
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} else {
log.info("Device management repository database already exists. Not creating a new database.");
}
} catch (NamingException 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);
}
}
}

View File

@ -1,52 +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.arduino.plugin.impl.util;
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.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator + ArduinoConstants.DEVICE_TYPE
+ File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

View File

@ -1,47 +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.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;
}
}

View File

@ -1,121 +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.arduino.plugin.internal;
import org.apache.commons.logging.Log;
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.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;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.arduino.internal.ArduinoManagementServiceComponent"
* immediate="true"
* @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 ArduinoManagementServiceComponent {
private static final Log log = LogFactory.getLog(ArduinoManagementServiceComponent.class);
private ServiceRegistration arduinoServiceRegRef;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Arduino Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
arduinoServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new ArduinoManagerService(), null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug(
"-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
ArduinoUtils.setupDeviceManagementSchema();
} catch (ArduinoDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("Arduino Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Arduino Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Arduino Device Management Service Component");
}
try {
if (arduinoServiceRegRef != null) {
arduinoServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug(
"Arduino Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Arduino Device Management bundle", e);
}
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to service component");
}
}
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);
}
}

View File

@ -35,7 +35,6 @@
<modules> <modules>
<module>org.wso2.carbon.device.mgt.iot.arduino.api</module> <module>org.wso2.carbon.device.mgt.iot.arduino.api</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.plugin</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.ui</module> <module>org.wso2.carbon.device.mgt.iot.arduino.ui</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.analytics</module> <module>org.wso2.carbon.device.mgt.iot.arduino.analytics</module>
</modules> </modules>

View File

@ -0,0 +1,108 @@
<?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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>iot-base-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.2.6-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.url.printer</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - IoT url printer</name>
<description>WSO2 Carbon - IoT url printer</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.url.printer.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
org.apache.axis2.*;version="${axis2.osgi.version.range}",
org.wso2.carbon.core,
org.wso2.carbon.utils.*,
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.url.printer.internal,
org.wso2.carbon.device.mgt.iot.url.printer.*;version="${project.version}"
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -21,7 +21,7 @@ package org.wso2.carbon.device.mgt.iot.url.printer;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.iot.internal.IoTDeviceManagementDataHolder; import org.wso2.carbon.device.mgt.iot.url.printer.internal.UrlPrinterDataHolder;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
import org.wso2.carbon.utils.NetworkUtils; import org.wso2.carbon.utils.NetworkUtils;
@ -35,10 +35,10 @@ public class URLPrinterStartupHandler implements ServerStartupObserver {
@Override @Override
public void completedServerStartup() { public void completedServerStartup() {
log.info("IoT Console URL : " + this.getIoTUrl()); log.info("IoT Console URL : " + this.getServerUrl());
} }
private String getIoTUrl() { private String getServerUrl() {
// Hostname // Hostname
String hostName = "localhost"; String hostName = "localhost";
try { try {
@ -48,7 +48,7 @@ public class URLPrinterStartupHandler implements ServerStartupObserver {
// HTTPS port // HTTPS port
String mgtConsoleTransport = CarbonUtils.getManagementTransport(); String mgtConsoleTransport = CarbonUtils.getManagementTransport();
ConfigurationContextService configContextService = ConfigurationContextService configContextService =
IoTDeviceManagementDataHolder.getInstance().getConfigurationContextService(); UrlPrinterDataHolder.getInstance().getConfigurationContextService();
int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); int port = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport);
int httpsProxyPort = int httpsProxyPort =
CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), mgtConsoleTransport); CarbonUtils.getTransportProxyPort(configContextService.getServerConfigContext(), mgtConsoleTransport);

View File

@ -16,18 +16,18 @@
* under the License. * under the License.
* *
*/ */
package org.wso2.carbon.device.mgt.iot.internal; package org.wso2.carbon.device.mgt.iot.url.printer.internal;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
public class IoTDeviceManagementDataHolder { public class UrlPrinterDataHolder {
private ConfigurationContextService configurationContextService; private ConfigurationContextService configurationContextService;
private static IoTDeviceManagementDataHolder thisInstance = new IoTDeviceManagementDataHolder(); private static UrlPrinterDataHolder thisInstance = new UrlPrinterDataHolder();
private IoTDeviceManagementDataHolder() {} private UrlPrinterDataHolder() {}
public static IoTDeviceManagementDataHolder getInstance() { public static UrlPrinterDataHolder getInstance() {
return thisInstance; return thisInstance;
} }

View File

@ -16,20 +16,18 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.internal; package org.wso2.carbon.device.mgt.iot.url.printer.internal;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext; import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext; import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerStartupObserver; 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.device.mgt.iot.url.printer.URLPrinterStartupHandler;
import org.wso2.carbon.utils.ConfigurationContextService; import org.wso2.carbon.utils.ConfigurationContextService;
/** /**
* @scr.component name="org.wso2.carbon.device.mgt.iot.internal.IotDeviceManagementServiceComponent" * @scr.component name="org.wso2.carbon.device.mgt.iot.url.printer.internal.UrlPrinterServiceComponent"
* immediate="true" * immediate="true"
* @scr.reference name="config.context.service" * @scr.reference name="config.context.service"
* interface="org.wso2.carbon.utils.ConfigurationContextService" * interface="org.wso2.carbon.utils.ConfigurationContextService"
@ -38,32 +36,28 @@ import org.wso2.carbon.utils.ConfigurationContextService;
* bind="setConfigurationContextService" * bind="setConfigurationContextService"
* unbind="unsetConfigurationContextService" * unbind="unsetConfigurationContextService"
*/ */
public class IotDeviceManagementServiceComponent { public class UrlPrinterServiceComponent {
private static final Log log = LogFactory.getLog(IotDeviceManagementServiceComponent.class); private static final Log log = LogFactory.getLog(UrlPrinterServiceComponent.class);
protected void activate(ComponentContext ctx) { protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Activating Iot Device Management Service Component"); log.debug("Activating Url printer Service Component");
} }
try { try {
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
bundleContext.registerService(ServerStartupObserver.class.getName(), new URLPrinterStartupHandler(), null); bundleContext.registerService(ServerStartupObserver.class.getName(), new URLPrinterStartupHandler(), null);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Iot Device Management Service Component has been successfully activated"); log.debug("Url printer Service Component has been successfully activated");
} }
DeviceTypeConfigServiceImpl deviceTypeConfigLoaderService = new DeviceTypeConfigServiceImpl();
deviceTypeConfigLoaderService.initialize();
bundleContext.registerService(DeviceTypeConfigService.class.getName(), deviceTypeConfigLoaderService,
null);
} catch (Throwable e) { } catch (Throwable e) {
log.error("Error occurred while activating Iot Device Management Service Component", e); log.error("Error occurred while activating Url printer Service Component", e);
} }
} }
protected void deactivate(ComponentContext ctx) { protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Iot Device Management Service Component"); log.debug("De-activating Url printer Service Component");
} }
} }
@ -72,7 +66,7 @@ public class IotDeviceManagementServiceComponent {
log.debug("Setting ConfigurationContextService"); log.debug("Setting ConfigurationContextService");
} }
IoTDeviceManagementDataHolder.getInstance().setConfigurationContextService(configurationContextService); UrlPrinterDataHolder.getInstance().setConfigurationContextService(configurationContextService);
} }
@ -80,6 +74,6 @@ public class IotDeviceManagementServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Un-setting ConfigurationContextService"); log.debug("Un-setting ConfigurationContextService");
} }
IoTDeviceManagementDataHolder.getInstance().setConfigurationContextService(null); UrlPrinterDataHolder.getInstance().setConfigurationContextService(null);
} }
} }

View File

@ -1,195 +0,0 @@
<?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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>iot-base-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.2.6-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - IoT Device Management Common Impl</name>
<description>WSO2 Carbon - IoT Device Management and Control Implementation</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.internal</Private-Package>
<Import-Package>
org.wso2.carbon.base.*,
org.osgi.framework,
org.osgi.service.component,
org.apache.axis2.context,
org.apache.commons.io,
org.apache.commons.logging,
org.wso2.carbon.core,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.utils,
javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers; version="${javax.xml.parsers.import.pkg.version}",
org.w3c.dom
</Import-Package>
<Export-Package>
!org.wso2.carbon.device.mgt.iot.internal,
org.wso2.carbon.device.mgt.iot.*;version="${project.version}"
</Export-Package>
</instructions>
</configuration>
</plugin>
<!--<plugin>-->
<!--<groupId>org.apache.maven.plugins</groupId>-->
<!--<artifactId>maven-surefire-plugin</artifactId>-->
<!--<version>2.18</version>-->
<!--<configuration>-->
<!--<systemPropertyVariables>-->
<!--<log4j.configuration>file:src/test/resources/log4j.properties-->
<!--</log4j.configuration>-->
<!--</systemPropertyVariables>-->
<!--<suiteXmlFiles>-->
<!--<suiteXmlFile>src/test/resources/testng.xml</suiteXmlFile>-->
<!--</suiteXmlFiles>-->
<!--</configuration>-->
<!--</plugin>-->
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents.wso2</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.policy.mgt.core</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.policy.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.databridge.agent</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.commons</groupId>
<artifactId>org.wso2.carbon.databridge.commons</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
</dependency>
<!--Dependencies on XMPP Client Library-->
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,48 +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.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);
}
}

View File

@ -1,18 +0,0 @@
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);
}

View File

@ -1,72 +0,0 @@
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));
}
}

View File

@ -1,40 +0,0 @@
/*
* 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 = "DataSourceConfiguration")
public class DataSourceConfig {
private JNDILookupDefinition jndiLookupDefinition;
@XmlElement(name = "JndiLookupDefinition", required = true)
public JNDILookupDefinition getJndiLookupDefinition() {
return jndiLookupDefinition;
}
public void setJndiLookupDefinition(JNDILookupDefinition jndiLookupDefinition) {
this.jndiLookupDefinition = jndiLookupDefinition;
}
}

View File

@ -1,50 +0,0 @@
/*
* 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 management repository data.
*/
@XmlRootElement(name = "ManagementRepository")
public class DeviceManagementConfigRepository {
private DataSourceConfig dataSourceConfig;
private ProvisioningConfig provisioningConfig;
@XmlElement(name = "DataSourceConfiguration", required = true)
public DataSourceConfig getDataSourceConfig() {
return dataSourceConfig;
}
public void setDataSourceConfig(DataSourceConfig dataSourceConfig) {
this.dataSourceConfig = dataSourceConfig;
}
@XmlElement(name = "ProvisioningConfig", required = true)
public ProvisioningConfig getProvisioningConfig() {
return provisioningConfig;
}
public void setProvisioningConfig(
ProvisioningConfig provisioningConfig) {
this.provisioningConfig = provisioningConfig;
}
}

View File

@ -1,65 +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.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;
}
}

View File

@ -1,83 +0,0 @@
/*
* 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.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 parsing with JAXB.
*/
@XmlRootElement(name = "JndiLookupDefinition")
public class JNDILookupDefinition {
private String jndiName;
private List<JNDIProperty> jndiProperties;
@XmlElement(name = "Name", required = false)
public String getJndiName() {
return jndiName;
}
public void setJndiName(String jndiName) {
this.jndiName = jndiName;
}
@XmlElementWrapper(name = "Environment", required = false)
@XmlElement(name = "Property", nillable = false)
public List<JNDIProperty> getJndiProperties() {
return jndiProperties;
}
public void setJndiProperties(List<JNDIProperty> jndiProperties) {
this.jndiProperties = jndiProperties;
}
@XmlRootElement(name = "Property")
public static class JNDIProperty {
private String name;
private String value;
@XmlAttribute(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}

View File

@ -1,49 +0,0 @@
/*
* 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;
}
}

View File

@ -1,53 +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.devicetype.config.exception;
public class InvalidConfigurationStateException extends RuntimeException {
private static final long serialVersionUID = -3151279411229070297L;
public InvalidConfigurationStateException(int errorCode, String message) {
super(message);
}
public InvalidConfigurationStateException(int errorCode, String message, Throwable cause) {
super(message, cause);
}
public InvalidConfigurationStateException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public InvalidConfigurationStateException(String message, Throwable cause) {
super(message, cause);
}
public InvalidConfigurationStateException(String msg) {
super(msg);
}
public InvalidConfigurationStateException() {
super();
}
public InvalidConfigurationStateException(Throwable cause) {
super(cause);
}
}

View File

@ -1,52 +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.devicetype.util;
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 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 DeviceTypeConfigUtil {
public static final String CARBON_HOME = "carbon.home";
public static final String CARBON_HOME_ENTRY = "${carbon.home}";
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 DeviceTypeConfigurationException("Error occurred while parsing file, while converting " +
"to a org.w3c.dom.Document", e);
}
}
}

View File

@ -1,283 +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.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Provides utility methods required by the device type plugins.
*/
public class Utils {
public static final String HOST_NAME = "HostName";
private static final Log log = LogFactory.getLog(Utils.class);
public static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
log.warn("Failed retrieving the hostname, therefore set to localhost", e);
}
return hostName;
}
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams,
String zipFileName)
throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error("Failed closing connection", e);
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//read from file
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
if (origin != null) {
origin.close();
}
if (out != null) {
out.close();
}
}
return true;
}
}

View File

@ -33,7 +33,7 @@
<url>http://wso2.org</url> <url>http://wso2.org</url>
<modules> <modules>
<module>org.wso2.carbon.device.mgt.iot</module> <module>org.wso2.carbon.device.mgt.iot.url.printer</module>
<module>org.wso2.carbon.device.mgt.iot.ui</module> <module>org.wso2.carbon.device.mgt.iot.ui</module>
<module>org.wso2.carbon.device.mgt.iot.output.adapter.mqtt</module> <module>org.wso2.carbon.device.mgt.iot.output.adapter.mqtt</module>
<module>org.wso2.carbon.device.mgt.iot.output.adapter.xmpp</module> <module>org.wso2.carbon.device.mgt.iot.output.adapter.xmpp</module>

View File

@ -69,13 +69,6 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT --> <!--IOT -->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
@ -83,16 +76,6 @@
<version>4.1</version> <version>4.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS --> <!--JAX-RS -->
<dependency> <dependency>
@ -113,22 +96,11 @@
<artifactId>jsr311-api</artifactId> <artifactId>jsr311-api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId> <artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
@ -144,6 +116,11 @@
<artifactId>org.wso2.carbon.analytics.api</artifactId> <artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>

View File

@ -34,11 +34,11 @@ 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.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord; 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.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;

View File

@ -16,24 +16,17 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants; package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
public class RaspberrypiConstants { public class RaspberrypiConstants {
public final static String DEVICE_TYPE = "raspberrypi"; public final static String DEVICE_TYPE = "raspberrypi";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "RASPBERRYPI_DEVICE_ID";
public final static String STATE_ON = "ON"; public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF"; public final static String STATE_OFF = "OFF";
public static final String BULB_CONTEXT = "BULB"; public static final String BULB_CONTEXT = "BULB";
//sensor events summerized table name //sensor events summerized table name
public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY"; public static final String TEMPERATURE_EVENT_TABLE = "DEVICE_TEMPERATURE_SUMMARY";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants //mqtt tranport related constants
public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic"; public static final String MQTT_ADAPTER_TOPIC_PROPERTY_NAME = "mqtt.adapter.topic";

View File

@ -0,0 +1,43 @@
/*
* 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.service.impl.util;
import java.io.File;
/**
* This is an utility class to hold zip files.
*/
public class ZipArchive {
private File zipFile = null;
private String fileName = null;
public ZipArchive(String fileName, File zipFile) {
this.fileName = fileName;
this.zipFile = zipFile;
}
public File getZipFile() {
return zipFile;
}
public String getFileName() {
return fileName;
}
}

View File

@ -18,25 +18,45 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util; package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; 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.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.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** /**
* This is used to create a zip file that includes the necessary configuration required for the agent. * This is used to create a zip file that includes the necessary configuration required for the agent.
*/ */
public class ZipUtil { public class ZipUtil {
private static final Log log = LogFactory.getLog(ZipUtil.class);
public static final String HOST_NAME = "HostName";
private static final String HTTPS_PORT_PROPERTY = "httpsPort"; private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort"; private static final String HTTP_PORT_PROPERTY = "httpPort";
@ -57,7 +77,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getServerUrl(); iotServerIP = getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
@ -101,7 +121,7 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile; ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -109,4 +129,227 @@ public class ZipUtil {
throw new DeviceManagementException("Failed to retrieve configuration", e); throw new DeviceManagementException("Failed to retrieve configuration", e);
} }
} }
private static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
log.warn("Failed retrieving the hostname, therefore set to localhost", e);
}
return hostName;
}
private static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams
, String zipFileName)
throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error("Failed closing connection", e);
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//read from file
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
if (origin != null) {
origin.close();
}
if (out != null) {
out.close();
}
}
return true;
}
} }

View File

@ -1,125 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.2.6-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi Management Plugin</name>
<description>WSO2 Carbon - RaspberryPi Management/Control Plugin Implementation</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.devicemgt.plugins.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.base,
org.wso2.carbon.context,
org.wso2.carbon.core,
org.wso2.carbon.core.util,
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,
org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<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>

View File

@ -1,56 +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.exception;
public class RaspberrypiDeviceMgtPluginException extends Exception{
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public RaspberrypiDeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public RaspberrypiDeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public RaspberrypiDeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public RaspberrypiDeviceMgtPluginException() {
super();
}
public RaspberrypiDeviceMgtPluginException(Throwable cause) {
super(cause);
}
}

View File

@ -1,254 +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.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.dao.RaspberrypiDAOUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.feature.RaspberrypiFeatureManager;
import java.util.List;
/**
* This represents the Raspberrypi implementation of DeviceManagerService.
*/
public class RaspberrypiManager implements DeviceManager {
private static final RaspberrypiDAOUtil raspberrypiDAO = new RaspberrypiDAOUtil();
private static final Log log = LogFactory.getLog(RaspberrypiManager.class);
private RaspberrypiFeatureManager raspberrypiFeatureManager = new RaspberrypiFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return raspberrypiFeatureManager;
}
@Override
public boolean saveConfiguration(PlatformConfiguration tenantConfiguration)
throws DeviceManagementException {
return false;
}
@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Raspberrypi device : " + device.getDeviceIdentifier());
}
RaspberrypiDAOUtil.beginTransaction();
status = raspberrypiDAO.getDeviceDAO().addDevice(device);
RaspberrypiDAOUtil.commitTransaction();
} catch (RaspberrypiDeviceMgtPluginException e) {
try {
RaspberrypiDAOUtil.rollbackTransaction();
} catch (RaspberrypiDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Raspberrypi device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Raspberrypi device enrollment data");
}
RaspberrypiDAOUtil.beginTransaction();
status = raspberrypiDAO.getDeviceDAO().updateDevice(device);
RaspberrypiDAOUtil.commitTransaction();
} catch (RaspberrypiDeviceMgtPluginException e) {
try {
RaspberrypiDAOUtil.rollbackTransaction();
} catch (RaspberrypiDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Raspberrypi device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Raspberrypi device : " + deviceId);
}
RaspberrypiDAOUtil.beginTransaction();
status = raspberrypiDAO.getDeviceDAO().deleteDevice(deviceId.getId());
RaspberrypiDAOUtil.commitTransaction();
} catch (RaspberrypiDeviceMgtPluginException e) {
try {
RaspberrypiDAOUtil.rollbackTransaction();
} catch (RaspberrypiDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Raspberrypi device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Raspberrypi device : " + deviceId.getId());
}
Device iotDevice = raspberrypiDAO.getDeviceDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (RaspberrypiDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Raspberrypi device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Raspberrypi device : " + deviceId.getId());
}
device = raspberrypiDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (RaspberrypiDeviceMgtPluginException e) {
String msg = "Error while fetching the Raspberrypi device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Raspberrypi device : " + deviceIdentifier);
}
RaspberrypiDAOUtil.beginTransaction();
status = raspberrypiDAO.getDeviceDAO().updateDevice(device);
RaspberrypiDAOUtil.commitTransaction();
} catch (RaspberrypiDeviceMgtPluginException e) {
try {
RaspberrypiDAOUtil.rollbackTransaction();
} catch (RaspberrypiDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Raspberrypi device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Raspberrypi devices");
}
List<Device> iotDevices = raspberrypiDAO.getDeviceDAO().getAllDevices();
} catch (RaspberrypiDeviceMgtPluginException e) {
String msg = "Error while fetching all Raspberrypi devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

View File

@ -1,90 +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.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
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;
import java.util.HashMap;
import java.util.Map;
public class RaspberrypiManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private PushNotificationConfig pushNotificationConfig;
@Override
public String getType() {
return RaspberrypiConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
deviceManager = new RaspberrypiManager();
this.pushNotificationConfig = this.populatePushNotificationConfig();
}
private PushNotificationConfig populatePushNotificationConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = RaspberrypiManagementDataHolder.getInstance()
.getDeviceTypeConfigService().getConfiguration(RaspberrypiConstants.DEVICE_TYPE,
RaspberrypiConstants.DEVICE_TYPE_PROVIDER_DOMAIN);
org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig sourceConfig =
deviceManagementConfiguration.getPushNotificationConfig();
Map<String, String> staticProps = new HashMap<>();
for (org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig.Property
property : sourceConfig.getProperties()) {
staticProps.put(property.getName(), property.getValue());
}
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
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
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}
}

View File

@ -1,131 +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.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;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class RaspberrypiDAOUtil {
private static final Log log = LogFactory.getLog(RaspberrypiDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public RaspberrypiDAOUtil() {
initRaspberrypiDAO();
}
public RaspberrypiDeviceDAO getDeviceDAO() {
return new RaspberrypiDeviceDAO();
}
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(datasource);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + datasource, e);
}
}
public static void beginTransaction() throws RaspberrypiDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new RaspberrypiDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws RaspberrypiDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new RaspberrypiDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws RaspberrypiDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new RaspberrypiDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws RaspberrypiDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws RaspberrypiDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new RaspberrypiDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

View File

@ -1,190 +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.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.exception.RaspberrypiDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.util.RaspberrypiUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements CRUD for Raspberrypi Devices.
*/
public class RaspberrypiDeviceDAO {
private static final Log log = LogFactory.getLog(RaspberrypiDeviceDAO.class);
public Device getDevice(String iotDeviceId) throws RaspberrypiDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = RaspberrypiDAOUtil.getConnection();
String selectDBQuery =
"SELECT RASPBERRYPI_DEVICE_ID, DEVICE_NAME FROM RASPBERRYPI_DEVICE WHERE RASPBERRYPI_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
device.setName(resultSet.getString(RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Raspberrypi device " + iotDeviceId + " data has been fetched from " +
"Raspberrypi database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Raspberrypi device : '" + iotDeviceId + "'";
log.error(msg, e);
throw new RaspberrypiDeviceMgtPluginException(msg, e);
} finally {
RaspberrypiUtils.cleanupResources(stmt, resultSet);
RaspberrypiDAOUtil.closeConnection();
}
return device;
}
public boolean addDevice(Device device) throws RaspberrypiDeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = RaspberrypiDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO RASPBERRYPI_DEVICE(RASPBERRYPI_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Raspberrypi device " + device.getDeviceIdentifier() + " data has been" +
" added to the Raspberrypi database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Raspberrypi device '" +
device.getDeviceIdentifier() + "' to the Raspberrypi db.";
log.error(msg, e);
throw new RaspberrypiDeviceMgtPluginException(msg, e);
} finally {
RaspberrypiUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws RaspberrypiDeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = RaspberrypiDAOUtil.getConnection();
String updateDBQuery = "UPDATE RASPBERRYPI_DEVICE SET DEVICE_NAME = ? WHERE RASPBERRYPI_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Raspberrypi device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Raspberrypi device '" + device.getDeviceIdentifier()
+ "' data.";
log.error(msg, e);
throw new RaspberrypiDeviceMgtPluginException(msg, e);
} finally {
RaspberrypiUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String iotDeviceId) throws RaspberrypiDeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = RaspberrypiDAOUtil.getConnection();
String deleteDBQuery = "DELETE FROM RASPBERRYPI_DEVICE WHERE RASPBERRYPI_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Raspberrypi device " + iotDeviceId + " data has deleted" +
" from the Raspberrypi database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Raspberrypi device " + iotDeviceId;
log.error(msg, e);
throw new RaspberrypiDeviceMgtPluginException(msg, e);
} finally {
RaspberrypiUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws RaspberrypiDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> devices = new ArrayList<>();
try {
conn = RaspberrypiDAOUtil.getConnection();
String selectDBQuery = "SELECT RASPBERRYPI_DEVICE_ID, DEVICE_NAME FROM RASPBERRYPI_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(RaspberrypiConstants.DEVICE_PLUGIN_DEVICE_NAME));
devices.add(device);
}
if (log.isDebugEnabled()) {
log.debug("All Raspberrypi device details have fetched from Raspberrypi database.");
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Raspberrypi device data'";
log.error(msg, e);
throw new RaspberrypiDeviceMgtPluginException(msg, e);
} finally {
RaspberrypiUtils.cleanupResources(stmt, resultSet);
RaspberrypiDAOUtil.closeConnection();
}
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl.feature;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import java.util.List;
public class RaspberrypiFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(RaspberrypiConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(RaspberrypiConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

View File

@ -1,52 +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.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator + RaspberrypiConstants.DEVICE_TYPE
+ File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

View File

@ -1,112 +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.impl.util;
import org.apache.commons.logging.Log;
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;
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 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.sql.Connection;
import java.sql.PreparedStatement;
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 Raspberrypi plugin.
*/
public class RaspberrypiUtils {
private static Log log = LogFactory.getLog(RaspberrypiUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* 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(datasource);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
String checkSql = "select * from RASPBERRYPI_DEVICE";
if (!initializer.isDatabaseStructureCreated(checkSql)) {
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} else {
log.info("Device management repository database already exists. Not creating a new database.");
}
} catch (NamingException 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);
}
}
}

View File

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

View File

@ -1,119 +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.internal;
import org.apache.commons.logging.Log;
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.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.RaspberrypiUtils;
import org.wso2.carbon.ndatasource.core.DataSourceService;
/**
* @scr.component name="org.wso2.carbon.device.mgt.iot.raspberrypi.internal.RaspberrypiManagementServiceComponent"
* immediate="true"
* @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 {
private ServiceRegistration raspberrypiServiceRegRef;
private static final Log log = LogFactory.getLog(RaspberrypiManagementServiceComponent.class);
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Raspberrypi Device Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
raspberrypiServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName(),
new RaspberrypiManagerService(), null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
RaspberrypiUtils.setupDeviceManagementSchema();
} catch (RaspberrypiDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("Raspberrypi Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error(
"Error occurred while activating Raspberrypi Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Raspberrypi Device Management Service Component");
}
try {
if (raspberrypiServiceRegRef != null) {
raspberrypiServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Raspberrypi Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Raspberrypi Device Management bundle", e);
}
}
protected void setDataSourceService(DataSourceService dataSourceService) {
/* This is to avoid mobile device management component getting initialized before the underlying datasources
are registered */
if (log.isDebugEnabled()) {
log.debug("Data source service set to service component");
}
}
protected void unsetDataSourceService(DataSourceService dataSourceService) {
//do nothing
}
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
RaspberrypiManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
RaspberrypiManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
}

View File

@ -33,7 +33,6 @@
<url>http://wso2.org</url> <url>http://wso2.org</url>
<modules> <modules>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.ui</module> <module>org.wso2.carbon.device.mgt.iot.raspberrypi.ui</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.api</module> <module>org.wso2.carbon.device.mgt.iot.raspberrypi.api</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.analytics</module> <module>org.wso2.carbon.device.mgt.iot.raspberrypi.analytics</module>

View File

@ -107,16 +107,6 @@
<version>4.1</version> <version>4.1</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS --> <!--JAX-RS -->
<dependency> <dependency>
@ -206,18 +196,15 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-codec</groupId> <groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId> <artifactId>commons-codec</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.igniterealtime.smack.wso2</groupId> <groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId> <artifactId>smack</artifactId>
@ -228,11 +215,6 @@
<artifactId>smackx</artifactId> <artifactId>smackx</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId> <artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
@ -248,9 +230,17 @@
<artifactId>org.wso2.carbon.analytics.api</artifactId> <artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>

View File

@ -35,10 +35,9 @@ 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.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; 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.core.operation.mgt.CommandOperation;
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.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppServerClient; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppServerClient;
@ -46,6 +45,7 @@ import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRe
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient; import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;

View File

@ -19,11 +19,9 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.exception.VirtualFireAlarmException;
import java.lang.*; import java.lang.*;

View File

@ -0,0 +1,43 @@
/*
* 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.virtualfirealarm.service.impl.util;
import java.io.File;
/**
* This is an utility class to hold zip files.
*/
public class ZipArchive {
private File zipFile = null;
private String fileName = null;
public ZipArchive(String fileName, File zipFile) {
this.fileName = fileName;
this.zipFile = zipFile;
}
public File getZipFile() {
return zipFile;
}
public String getFileName() {
return fileName;
}
}

View File

@ -19,24 +19,40 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; 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.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; 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.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.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/** /**
* This is used to create a zip file that includes the necessary configuration required for the agent. * This is used to create a zip file that includes the necessary configuration required for the agent.
@ -52,6 +68,7 @@ public class ZipUtil {
private static final String HTTP_PROTOCOL_APPENDER = "http://"; private static final String HTTP_PROTOCOL_APPENDER = "http://";
private static final String CONFIG_TYPE = "general"; private static final String CONFIG_TYPE = "general";
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883"; private static final String DEFAULT_MQTT_ENDPOINT = "tcp://localhost:1883";
public static final String HOST_NAME = "HostName";
public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName, public ZipArchive createZipFile(String owner, String deviceType, String deviceId, String deviceName,
String apiApplicationKey, String token, String refreshToken) String apiApplicationKey, String token, String refreshToken)
@ -65,7 +82,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = Utils.getServerUrl(); iotServerIP = getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY); String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY); String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort; String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
@ -125,7 +142,7 @@ public class ZipUtil {
? "" : XmppConfig.getInstance().getJid()); ? "" : XmppConfig.getInstance().getJid());
ZipArchive zipFile; ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName); zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile; return zipFile;
} catch (IOException e) { } catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e); throw new DeviceManagementException("Zip File Creation Failed", e);
@ -142,4 +159,229 @@ public class ZipUtil {
String stringToEncode = consumerKey + ":" + consumerSecret; String stringToEncode = consumerKey + ":" + consumerSecret;
return Base64.encodeBase64String(stringToEncode.getBytes()); return Base64.encodeBase64String(stringToEncode.getBytes());
} }
public static String getServerUrl() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
log.warn("Failed retrieving the hostname, therefore set to localhost", e);
}
return hostName;
}
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams
, String zipFileName)
throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
createZipArchive(archivesPath);
FileUtils.deleteDirectory(new File(archivesPath));
File zip = new File(archivesPath + ".zip");
return new org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive(zipFileName, zip);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
log.error("Failed closing connection", e);
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//read from file
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = new FileInputStream(srcFile);
outputStream = new FileOutputStream(dstFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
if (origin != null) {
origin.close();
}
if (out != null) {
out.close();
}
}
return true;
}
} }

View File

@ -0,0 +1,61 @@
/*
* 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.service.impl.util.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Provides utility methods required by the device type plugins.
*/
public class Utils {
public static final String HOST_NAME = "HostName";
private static final Log log = LogFactory.getLog(Utils.class);
}

View File

@ -24,10 +24,6 @@
<param-name>doAuthentication</param-name> <param-name>doAuthentication</param-name>
<param-value>true</param-value> <param-value>true</param-value>
</context-param> </context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param> <context-param>
<param-name>providerTenantDomain</param-name> <param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value> <param-value>carbon.super</param-value>

View File

@ -83,7 +83,10 @@
org.wso2.carbon.event.input.adapter.core, org.wso2.carbon.event.input.adapter.core,
org.wso2.carbon.event.input.adapter.core.exception, org.wso2.carbon.event.input.adapter.core.exception,
org.jivesoftware.smack.*, org.jivesoftware.smack.*,
org.wso2.carbon.device.mgt.iot.devicetype.* javax.xml.bind,
javax.xml.bind.annotation,
javax.xml.parsers; version="${javax.xml.parsers.import.pkg.version}",
org.w3c.dom
</Import-Package> </Import-Package>
<Export-Package> <Export-Package>
!org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal, !org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal,
@ -160,9 +163,5 @@
<groupId>org.igniterealtime.smack.wso2</groupId> <groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId> <artifactId>smackx</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -0,0 +1,45 @@
/*
* 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.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 EventListenerConfiguration eventListenerConfiguration;
private static final Log log = LogFactory.getLog(DeviceManagementConfiguration.class);
private DeviceManagementConfiguration() {
}
@XmlElement(name = "EventListenerConfiguration", required = false)
public EventListenerConfiguration getEventListenerConfiguration() {
return eventListenerConfiguration;
}
public void setEventListenerConfiguration(EventListenerConfiguration eventListenerConfiguration) {
this.eventListenerConfiguration = eventListenerConfiguration;
}
}

View File

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

View File

@ -0,0 +1,60 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.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.config.exception.VirtualFirealarmConfigurationException;
import org.wso2.carbon.utils.CarbonUtils;
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 VirtualFirealarmConfig {
private static final Log log = LogFactory.getLog(VirtualFirealarmConfig.class);
private static final String DEVICE_TYPE_CONFIG_PATH =
CarbonUtils.getEtcCarbonConfigDirPath() + File.separator + "device-mgt-plugins" + File.separator
+ "virtual_firealarm.xml";
private static VirtualFirealarmConfig virtualFirealarmConfig = new VirtualFirealarmConfig();
private static DeviceManagementConfiguration deviceManagementConfiguration;
public static VirtualFirealarmConfig getInstance() {
return virtualFirealarmConfig;
}
public static void initialize() throws VirtualFirealarmConfigurationException {
File configFile = new File(DEVICE_TYPE_CONFIG_PATH);
try {
Document doc = convertToDocument(configFile);
/* Un-marshaling Webapp Authenticator configuration */
JAXBContext ctx = JAXBContext.newInstance(DeviceManagementConfiguration.class);
Unmarshaller unmarshaller = ctx.createUnmarshaller();
//unmarshaller.setSchema(getSchema());
deviceManagementConfiguration = (DeviceManagementConfiguration) unmarshaller.unmarshal(doc);
} catch (JAXBException e) {
throw new VirtualFirealarmConfigurationException("Error occurred while un-marshalling the file " +
DEVICE_TYPE_CONFIG_PATH, e);
}
}
public DeviceManagementConfiguration getDeviceTypeConfiguration() {
return deviceManagementConfiguration;
}
public static Document convertToDocument(File file) throws VirtualFirealarmConfigurationException {
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 " +
"to a org.w3c.dom.Document", e);
}
}
}

View File

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

View File

@ -1,256 +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.virtualfirealarm.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.dao.VirtualFireAlarmDAOUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.feature.VirtualFirealarmFeatureManager;
import java.util.List;
/**
* This represents the FireAlarm implementation of DeviceManagerService.
*/
public class VirtualFireAlarmManager implements DeviceManager {
private static final VirtualFireAlarmDAOUtil virtualFireAlarmDAO = new VirtualFireAlarmDAOUtil();
private static final Log log = LogFactory.getLog(VirtualFireAlarmManager.class);
private FeatureManager virtualFirealarmFeatureManager = new VirtualFirealarmFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return virtualFirealarmFeatureManager;
}
@Override
public boolean saveConfiguration(PlatformConfiguration PlatformConfiguration)
throws DeviceManagementException {
return false;
}
@Override
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new Virtual Firealarm device : " + device.getDeviceIdentifier());
}
VirtualFireAlarmDAOUtil.beginTransaction();
status = virtualFireAlarmDAO.getDeviceDAO().addDevice(device);
VirtualFireAlarmDAOUtil.commitTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
try {
VirtualFireAlarmDAOUtil.rollbackTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while enrolling the Virtual Firealarm device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Virtual Firealarm device enrollment data");
}
VirtualFireAlarmDAOUtil.beginTransaction();
status = virtualFireAlarmDAO.getDeviceDAO().updateDevice(device);
VirtualFireAlarmDAOUtil.commitTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
try {
VirtualFireAlarmDAOUtil.rollbackTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the Virtual Firealarm device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling Virtual Firealarm device : " + deviceId);
}
VirtualFireAlarmDAOUtil.beginTransaction();
status = virtualFireAlarmDAO.getDeviceDAO().deleteDevice(deviceId.getId());
VirtualFireAlarmDAOUtil.commitTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
try {
VirtualFireAlarmDAOUtil.rollbackTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the Virtual Firealarm device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Virtual Firealarm device : " + deviceId.getId());
}
Device device = virtualFireAlarmDAO.getDeviceDAO().getDevice(deviceId.getId());
if (device != null) {
isEnrolled = true;
}
} catch (VirtualFirealarmDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Virtual Firealarm device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Virtual Firealarm device : " + deviceId.getId());
}
device = virtualFireAlarmDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (VirtualFirealarmDeviceMgtPluginException e) {
String msg = "Error while fetching the Virtual Firealarm device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return false;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug(
"updating the details of Virtual Firealarm device : " + deviceIdentifier);
}
VirtualFireAlarmDAOUtil.beginTransaction();
status = virtualFireAlarmDAO.getDeviceDAO().updateDevice(device);
VirtualFireAlarmDAOUtil.commitTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
try {
VirtualFireAlarmDAOUtil.rollbackTransaction();
} catch (VirtualFirealarmDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the Virtual Firealarm device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Virtual Firealarm devices");
}
devices = virtualFireAlarmDAO.getDeviceDAO().getAllDevices();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
String msg = "Error while fetching all Virtual Firealarm devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

View File

@ -1,89 +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.virtualfirealarm.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
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.VirtualFirealarmManagementDataHolder;
import java.util.HashMap;
import java.util.Map;
public class VirtualFireAlarmManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private PushNotificationConfig pushNotificationConfig;
@Override
public String getType() {
return VirtualFireAlarmConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new VirtualFireAlarmManager();
this.pushNotificationConfig = this.populatePushNotificationConfig();
}
private PushNotificationConfig populatePushNotificationConfig() {
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.devicetype.config.PushNotificationConfig.Property
property : sourceConfig.getProperties()) {
staticProps.put(property.getName(), property.getValue());
}
return new PushNotificationConfig(sourceConfig.getPushNotificationProvider(), staticProps);
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
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
public PushNotificationConfig getPushNotificationConfig() {
return pushNotificationConfig;
}
}

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -26,7 +26,6 @@ import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException; 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.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.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; 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.internal.VirtualFirealarmManagementDataHolder;
@ -37,17 +36,9 @@ import org.wso2.carbon.event.input.adapter.core.MessageType;
import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException; import org.wso2.carbon.event.input.adapter.core.exception.InputEventAdapterException;
import org.json.JSONObject; import org.json.JSONObject;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException; import java.io.IOException;
import java.security.PublicKey; import java.security.PublicKey;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -58,62 +49,6 @@ public class VirtualFireAlarmUtils {
private static Log log = LogFactory.getLog(VirtualFireAlarmUtils.class); private static Log log = LogFactory.getLog(VirtualFireAlarmUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* 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(datasourceName);
DeviceSchemaInitializer initializer = new DeviceSchemaInitializer(dataSource);
String checkSql = "select * from VIRTUAL_FIREALARM_DEVICE";
if (!initializer.isDatabaseStructureCreated(checkSql)) {
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} else {
log.info("Device management repository database already exists. Not creating a new database.");
}
} catch (NamingException 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 setupMqttInputAdapter() throws IOException { public static void setupMqttInputAdapter() throws IOException {
if (!MqttConfig.getInstance().isEnabled()) { if (!MqttConfig.getInstance().isEnabled()) {
return; return;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterSubscription; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterSubscription;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
@ -6,7 +6,6 @@ import org.wso2.carbon.device.mgt.iot.input.adapter.extension.ContentTransformer
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; 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.exception.VirtualFirealarmDeviceMgtPluginException;
import java.math.BigInteger;
import java.security.PublicKey; import java.security.PublicKey;
import java.util.Map; import java.util.Map;

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;

View File

@ -16,7 +16,7 @@
* under the License. * under the License.
*/ */
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;

View File

@ -1,132 +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.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;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class VirtualFireAlarmDAOUtil {
private static final Log log = LogFactory.getLog(VirtualFireAlarmDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public VirtualFireAlarmDAOUtil() {
initFireAlarmDAO();
}
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(datasourceName);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + datasourceName, e);
}
}
public VirtualFireAlarmDeviceDAO getDeviceDAO() {
return new VirtualFireAlarmDeviceDAO();
}
public static void beginTransaction() throws VirtualFirealarmDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new VirtualFirealarmDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws VirtualFirealarmDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new VirtualFirealarmDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws VirtualFirealarmDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new VirtualFirealarmDeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws VirtualFirealarmDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws VirtualFirealarmDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new VirtualFirealarmDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

View File

@ -1,195 +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.virtualfirealarm.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
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.impl.util.VirtualFireAlarmUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements CRUD for virtual firealarm Devices.
*/
public class VirtualFireAlarmDeviceDAO {
private static final Log log = LogFactory.getLog(VirtualFireAlarmDeviceDAO.class);
public Device getDevice(String deviceId) throws VirtualFirealarmDeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
ResultSet resultSet = null;
try {
conn = VirtualFireAlarmDAOUtil.getConnection();
String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME" +
" FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
device.setName(resultSet.getString(VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm device " + deviceId + " data has been fetched from " +
"Virtual Firealarm database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Virtual Firealarm device : '" + deviceId + "'";
log.error(msg, e);
throw new VirtualFirealarmDeviceMgtPluginException(msg, e);
} finally {
VirtualFireAlarmUtils.cleanupResources(stmt, resultSet);
VirtualFireAlarmDAOUtil.closeConnection();
}
return device;
}
public boolean addDevice(Device device) throws VirtualFirealarmDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = VirtualFireAlarmDAOUtil.getConnection();
String createDBQuery =
"INSERT INTO VIRTUAL_FIREALARM_DEVICE(VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm device " + device.getDeviceIdentifier() + " data has been" +
" added to the Virtual Firealarm database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Virtual Firealarm device '" +
device.getDeviceIdentifier() + "' to the Virtual Firealarm db.";
log.error(msg, e);
throw new VirtualFirealarmDeviceMgtPluginException(msg, e);
} finally {
VirtualFireAlarmUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws VirtualFirealarmDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = VirtualFireAlarmDAOUtil.getConnection();
String updateDBQuery =
"UPDATE VIRTUAL_FIREALARM_DEVICE SET DEVICE_NAME = ? WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Virtualm Firealarm device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Virtual Firealarm device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new VirtualFirealarmDeviceMgtPluginException(msg, e);
} finally {
VirtualFireAlarmUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String iotDeviceId) throws VirtualFirealarmDeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = VirtualFireAlarmDAOUtil.getConnection();
String deleteDBQuery = "DELETE FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm device " + iotDeviceId + " data has deleted" +
" from the Virtual Firealarm database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Virtual Firealarm device " + iotDeviceId;
log.error(msg, e);
throw new VirtualFirealarmDeviceMgtPluginException(msg, e);
} finally {
VirtualFireAlarmUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws VirtualFirealarmDeviceMgtPluginException {
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> devices = new ArrayList<>();
try {
conn = VirtualFireAlarmDAOUtil.getConnection();
String selectDBQuery =
"SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME FROM VIRTUAL_FIREALARM_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME));
devices.add(device);
}
if (log.isDebugEnabled()) {
log.debug("All Virtual Firealarm device details have fetched from Firealarm database.");
}
return devices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Virtual Firealarm device data'";
log.error(msg, e);
throw new VirtualFirealarmDeviceMgtPluginException(msg, e);
} finally {
VirtualFireAlarmUtils.cleanupResources(stmt, resultSet);
VirtualFireAlarmDAOUtil.closeConnection();
}
}
}

View File

@ -1,58 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.feature;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import java.util.List;
public class VirtualFirealarmFeatureManager implements FeatureManager{
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(VirtualFireAlarmConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(VirtualFireAlarmConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

View File

@ -1,52 +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.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator
+ VirtualFireAlarmConstants.DEVICE_TYPE + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

View File

@ -20,7 +20,6 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; 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.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService;
import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
/** /**
@ -31,7 +30,6 @@ public class VirtualFirealarmManagementDataHolder {
private InputEventAdapterService inputEventAdapterService; private InputEventAdapterService inputEventAdapterService;
private EventsPublisherService eventsPublisherService; private EventsPublisherService eventsPublisherService;
private CertificateManagementService certificateManagementService; private CertificateManagementService certificateManagementService;
private DeviceTypeConfigService deviceTypeConfigService;
private static VirtualFirealarmManagementDataHolder thisInstance = new VirtualFirealarmManagementDataHolder(); private static VirtualFirealarmManagementDataHolder thisInstance = new VirtualFirealarmManagementDataHolder();
@ -66,13 +64,4 @@ public class VirtualFirealarmManagementDataHolder {
public void setCertificateManagementService(CertificateManagementService certificateManagementService) { public void setCertificateManagementService(CertificateManagementService certificateManagementService) {
this.certificateManagementService = certificateManagementService; this.certificateManagementService = certificateManagementService;
} }
public DeviceTypeConfigService getDeviceTypeConfigService() {
return deviceTypeConfigService;
}
public void setDeviceTypeConfigService(
DeviceTypeConfigService deviceTypeConfigService) {
this.deviceTypeConfigService = deviceTypeConfigService;
}
} }

View File

@ -26,13 +26,9 @@ import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService; import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.core.ServerStartupObserver; import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService; 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.virtualfirealarm.plugin.config.VirtualFirealarmConfig;
import org.wso2.carbon.device.mgt.iot.devicetype.DeviceTypeConfigService; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmSecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.exception.VirtualFirealarmDeviceMgtPluginException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.VirtualFirealarmStartupListener;
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.event.input.adapter.core.InputEventAdapterService; import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
/** /**
@ -57,12 +53,6 @@ import org.wso2.carbon.event.input.adapter.core.InputEventAdapterService;
* policy="dynamic" * policy="dynamic"
* bind="setEventsPublisherService" * bind="setEventsPublisherService"
* unbind="unsetEventsPublisherService" * 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 { public class VirtualFirealarmManagementServiceComponent {
@ -74,25 +64,10 @@ public class VirtualFirealarmManagementServiceComponent {
log.debug("Activating Virtual Firealarm Device Management Service Component"); log.debug("Activating Virtual Firealarm Device Management Service Component");
} }
try { try {
VirtualFirealarmConfig.initialize();
VirtualFireAlarmManagerService virtualFireAlarmManagerService = new VirtualFireAlarmManagerService();
BundleContext bundleContext = ctx.getBundleContext(); BundleContext bundleContext = ctx.getBundleContext();
firealarmServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName()
,virtualFireAlarmManagerService, null);
bundleContext.registerService(ServerStartupObserver.class.getName(), new VirtualFirealarmStartupListener(), bundleContext.registerService(ServerStartupObserver.class.getName(), new VirtualFirealarmStartupListener(),
null); null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
VirtualFireAlarmUtils.setupDeviceManagementSchema();
} catch (VirtualFirealarmDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm Device Management Service Component has been successfully activated"); log.debug("Virtual Firealarm Device Management Service Component has been successfully activated");
} }
@ -106,16 +81,6 @@ public class VirtualFirealarmManagementServiceComponent {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("De-activating Virtual Firealarm Device Management Service Component"); log.debug("De-activating Virtual Firealarm Device Management Service Component");
} }
try {
if (firealarmServiceRegRef != null) {
firealarmServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Virtual Firealarm Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Virtual Firealarm Device Management bundle", e);
}
} }
/** /**
@ -149,12 +114,4 @@ public class VirtualFirealarmManagementServiceComponent {
protected void unsetEventsPublisherService(EventsPublisherService eventsPublisherService) { protected void unsetEventsPublisherService(EventsPublisherService eventsPublisherService) {
VirtualFirealarmManagementDataHolder.getInstance().setEventsPublisherService(null); VirtualFirealarmManagementDataHolder.getInstance().setEventsPublisherService(null);
} }
protected void setDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
VirtualFirealarmManagementDataHolder.getInstance().setDeviceTypeConfigService(deviceTypeConfigService);
}
protected void unsetDeviceTypeConfigService(DeviceTypeConfigService deviceTypeConfigService) {
VirtualFirealarmManagementDataHolder.getInstance().setDeviceTypeConfigService(null);
}
} }

View File

@ -20,10 +20,9 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.mqtt;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.EventListenerConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.VirtualFirealarmConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import java.util.List; import java.util.List;
@ -41,17 +40,16 @@ public class MqttConfig {
private String clearSession; private String clearSession;
private MqttConfig() { private MqttConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance() DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmConfig.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE, .getDeviceTypeConfiguration();
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN); List<EventListenerConfiguration.Property> properties = deviceManagementConfiguration
List<PushNotificationConfig.Property> properties = deviceManagementConfiguration .getEventListenerConfiguration().getProperties();
.getPushNotificationConfig().getProperties(); String provider = deviceManagementConfiguration.getEventListenerConfiguration().getEventListenerProvider();
String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider();
if (provider.equals("MQTT")) { if (provider.equals("MQTT")) {
enabled = true; enabled = true;
} }
if (enabled) { if (enabled) {
for (PushNotificationConfig.Property property : properties) { for (EventListenerConfiguration.Property property : properties) {
switch (property.getName()) { switch (property.getName()) {
case "url": case "url":
url = property.getValue(); url = property.getValue();
@ -71,8 +69,6 @@ public class MqttConfig {
case "clearSession": case "clearSession":
clearSession = property.getValue(); clearSession = property.getValue();
break; break;
} }
} }
} }

View File

@ -20,10 +20,10 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.devicetype.config.DeviceManagementConfiguration; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.DeviceManagementConfiguration;
import org.wso2.carbon.device.mgt.iot.devicetype.config.PushNotificationConfig; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.EventListenerConfiguration;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.config.VirtualFirealarmConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.internal.VirtualFirealarmManagementDataHolder;
import java.util.List; import java.util.List;
public class XmppConfig { public class XmppConfig {
@ -39,17 +39,16 @@ public class XmppConfig {
private static final Log log = LogFactory.getLog(XmppConfig.class); private static final Log log = LogFactory.getLog(XmppConfig.class);
private XmppConfig() { private XmppConfig() {
DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmManagementDataHolder.getInstance() DeviceManagementConfiguration deviceManagementConfiguration = VirtualFirealarmConfig.getInstance()
.getDeviceTypeConfigService().getConfiguration(VirtualFireAlarmConstants.DEVICE_TYPE, .getDeviceTypeConfiguration();
VirtualFireAlarmConstants.DEVICE_TYPE_PROVIDER_DOMAIN); List<EventListenerConfiguration.Property> properties = deviceManagementConfiguration.getEventListenerConfiguration()
List<PushNotificationConfig.Property> properties = deviceManagementConfiguration.getPushNotificationConfig()
.getProperties(); .getProperties();
String provider = deviceManagementConfiguration.getPushNotificationConfig().getPushNotificationProvider(); String provider = deviceManagementConfiguration.getEventListenerConfiguration().getEventListenerProvider();
if ("XMPP".equals(provider)) { if ("XMPP".equals(provider)) {
enabled = true; enabled = true;
} }
if (enabled) { if (enabled) {
for (PushNotificationConfig.Property property : properties) { for (EventListenerConfiguration.Property property : properties) {
switch (property.getName()) { switch (property.getName()) {
case "host": case "host":
host = property.getValue(); host = property.getValue();

View File

@ -1,6 +1,8 @@
{ {
"deviceType": { "deviceType": {
"label": "Android", "label": "Android",
"category" : "mobile" "category": "mobile",
"analyticsEnabled": "false",
"groupingEnabled": "false"
} }
} }

View File

@ -1,6 +1,8 @@
{ {
"deviceType": { "deviceType": {
"label": "Windows", "label": "Windows",
"category" : "mobile" "category": "mobile",
"analyticsEnabled": "false",
"groupingEnabled": "false"
} }
} }

View File

@ -37,19 +37,11 @@
</description> </description>
<dependencies> <dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.plugin</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.api</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.androidsense.api</artifactId>
<type>war</type> <type>war</type>
</dependency> </dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
@ -195,11 +187,6 @@
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef> <propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties> </properties>
</adviceFile> </adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.androidsense.plugin:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures> <importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef> <importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.devicemgt.version}</importFeatureDef> <importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.devicemgt.version}</importFeatureDef>

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