diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/pom.xml b/components/device-mgt/org.wso2.carbon.device.mgt.etc/pom.xml new file mode 100644 index 00000000000..6d4de612fb3 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/pom.xml @@ -0,0 +1,226 @@ + + + + + + + device-mgt + org.wso2.carbon.devicemgt + 1.1.0-SNAPSHOT + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.etc + bundle + WSO2 Carbon - Common Application Admin + http://wso2.org + + + + + org.apache.felix + maven-scr-plugin + + + maven-compiler-plugin + + 1.7 + 1.7 + + + + org.apache.felix + maven-bundle-plugin + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.device.mgt.version} + CDMF Common API Impl Bundle + org.wso2.carbon.device.mgt.etc.internal + + org.jivesoftware.smack.*, + javax.xml.namespace;resolution:=optional, + javax.xml.validation;resolution:=optional, + org.apache.commons.codec.binary, + org.apache.commons.collections.map, + org.apache.http.*, + org.apache.commons.io.*, + org.apache.commons.logging.*, + org.json;version="${commons-json.version}", + org.wso2.carbon.base.*, + org.wso2.carbon.databridge.*, + org.wso2.carbon.user.api, + org.wso2.carbon.user.core.service, + org.osgi.framework, + org.osgi.service.component, + javax.xml.bind.*;resolution:=optional, + javax.naming;resolution:=optional, + javax.sql;resolution:=optional, + javax.xml.bind.annotation.*;resolution:=optional, + javax.xml.parsers.*;resolution:=optional, + javax.net;resolution:=optional, + javax.net.ssl;resolution:=optional, + org.w3c.dom;resolution:=optional, + org.wso2.carbon.core;version="${carbon.kernel.version.range}", + org.wso2.carbon.utils.*;version="${carbon.kernel.version.range}", + org.wso2.carbon.device.mgt.group.common.*, + org.wso2.carbon.device.mgt.group.core.*, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.device.mgt.core.*, + org.wso2.carbon.context.*;version="${carbon.kernel.version.range}", + org.wso2.carbon.ndatasource.core;version="${carbon.kernel.version.range}", + org.eclipse.paho.client.mqttv3.*;version="${eclipse.paho.version}" + + + !org.wso2.carbon.device.mgt.etc.internal, + org.wso2.carbon.device.mgt.etc.*;version="${project.version}" + + + + + + + + + + + + + + + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + org.wso2.carbon + org.wso2.carbon.logging + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.core + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.policy.mgt.common + provided + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics.data.publisher + + + org.json.wso2 + json + + + + + + + + + + + + + + + org.wso2.carbon + org.wso2.carbon.core + + + commons-collections.wso2 + commons-collections + + + commons-codec.wso2 + commons-codec + + + commons-configuration + commons-configuration + + + org.wso2.carbon.analytics-common + org.wso2.carbon.databridge.agent + + + org.wso2.carbon.analytics-common + org.wso2.carbon.databridge.core + + + org.wso2.carbon.commons + org.wso2.carbon.databridge.commons + + + org.wso2.orbit.org.apache.httpcomponents + httpclient + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + + + org.wso2.carbon + org.wso2.carbon.utils + + + + + org.igniterealtime.smack.wso2 + smack + + + org.igniterealtime.smack.wso2 + smackx + + + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/AccessTokenInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/AccessTokenInfo.java new file mode 100644 index 00000000000..850c257fc59 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/AccessTokenInfo.java @@ -0,0 +1,61 @@ +/* + * 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.etc; + +public class AccessTokenInfo { + + private String token_type; + private int expires_in; + private String refresh_token; + private String access_token; + + public String getToken_type() { + return token_type; + } + + public void setToken_type(String token_type) { + this.token_type = token_type; + } + + public int getExpires_in() { + return expires_in; + } + + public void setExpires_in(int expres_in) { + this.expires_in = expres_in; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/ApisAppClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/ApisAppClient.java new file mode 100644 index 00000000000..59350f2f88b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/ApisAppClient.java @@ -0,0 +1,185 @@ +/* + * 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.etc; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig; +import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ApiManagerConfig; +import org.wso2.carbon.device.mgt.etc.util.IoTUtil; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class ApisAppClient { + + private static ConcurrentHashMap deviceTypeToApiAppMap = new ConcurrentHashMap<>(); + private static ApisAppClient instance =null; + + private String loginEndpoint; + private String subscriptionListEndpoint; + private static Log log = LogFactory.getLog(ApisAppClient.class); + private boolean isEnabled; + + public static ApisAppClient getInstance(){ + + if(instance==null){ + instance= new ApisAppClient(); + } + return instance; + } + + private ApisAppClient() { + ApiManagerConfig apiManagerConfig =DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager(); + String serverUrl=apiManagerConfig.getServerURL(); + String serverPort=apiManagerConfig.getServerPort(); + isEnabled = apiManagerConfig.isEnabled(); + + String loginURL = serverUrl+":"+serverPort+apiManagerConfig.getLoginURL(); + loginEndpoint= loginURL+"?action=login&username="+apiManagerConfig.getUsername() + +"&password="+apiManagerConfig.getPassword(); + + String subscriptionListUrl=serverUrl+":"+serverPort+apiManagerConfig.getSubscriptionListURL(); + subscriptionListEndpoint=subscriptionListUrl+"?action=getAllSubscriptions"; + } + + public String getBase64EncodedConsumerKeyAndSecret(String deviceType) { + if(!isEnabled) return null; + String consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType); + if(consumerKeyAndSecret == null){ + ArrayList iotDeviceTypeConfigs = new ArrayList<>(); + DeviceTypeConfig DeviceTypeConfig = DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap().get(deviceType); + if(DeviceTypeConfig != null) { + iotDeviceTypeConfigs.add(DeviceTypeConfig); + setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigs); + consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType); + if(consumerKeyAndSecret==null){ + log.warn("There is no API application for the device type " + deviceType); + } + } + } + return consumerKeyAndSecret; + } + + public void setBase64EncodedConsumerKeyAndSecret(List iotDeviceTypeConfigList) { + if(!isEnabled) return; + + URL loginURL = null; + try { + loginURL = new URL(loginEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed URL " + loginEndpoint; + log.error(errMsg); + return; + } + HttpClient httpClient = null; + try { + httpClient = IoTUtil.getHttpClient(loginURL.getPort(), loginURL.getProtocol()); + } catch (Exception e) { + log.error("Error on getting a http client for port :" + loginURL.getPort() + " protocol :" + + loginURL.getProtocol()); + return; + } + + HttpPost postMethod = new HttpPost(loginEndpoint); + JSONObject apiJsonResponse; + try { + HttpResponse httpResponse = httpClient.execute(postMethod); + String response = IoTUtil.getResponseString(httpResponse); + if(log.isDebugEnabled()) { + log.debug(response); + } + JSONObject jsonObject = new JSONObject(response); + + + boolean apiError = jsonObject.getBoolean("error"); + if(!apiError){ + String cookie = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0]; + HttpGet getMethod=new HttpGet(subscriptionListEndpoint); + getMethod.setHeader("cookie", cookie); + httpResponse = httpClient.execute(getMethod); + response = IoTUtil.getResponseString(httpResponse); + + + if(log.isDebugEnabled()) { + log.debug(response); + } + apiJsonResponse = new JSONObject(response); + apiError=apiJsonResponse.getBoolean("error"); + if(apiError){ + log.error("invalid subscription endpoint "+subscriptionListEndpoint); + return; + } + }else{ + log.error("invalid access for login endpoint " +loginEndpoint); + return; + } + + } catch (IOException | JSONException | DeviceMgtCommonsException e) { + log.warn("Trying to connect to the Api manager"); + return; + } + + + try { + JSONArray jsonSubscriptions = apiJsonResponse.getJSONObject("subscriptions").getJSONArray("applications"); + + HashMap subscriptionMap = new HashMap<>(); + for (int n = 0; n < jsonSubscriptions.length(); n++) { + + JSONObject object = jsonSubscriptions.getJSONObject(n); + String appName = object.getString("name"); + String prodConsumerKey = object.getString("prodConsumerKey"); + String prodConsumerSecret = object.getString("prodConsumerSecret"); + subscriptionMap.put(appName, new String(Base64.encodeBase64( + (prodConsumerKey + ":" + prodConsumerSecret).getBytes()))); + } + + for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) { + String deviceType = iotDeviceTypeConfig.getType(); + String deviceTypeApiApplicationName = iotDeviceTypeConfig.getApiApplicationName(); + String base64EncodedString = subscriptionMap.get(deviceTypeApiApplicationName); + if (base64EncodedString != null && base64EncodedString.length() != 0) { + deviceTypeToApiAppMap.put(deviceType, base64EncodedString); + } + } + + } catch (JSONException e) { + log.error("Json exception: " + e.getMessage(), e); + } + + + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceController.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceController.java new file mode 100644 index 00000000000..a418fde2341 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceController.java @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2014, 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.etc; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DeviceCloudConfig; +import org.wso2.carbon.device.mgt.etc.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.etc.datastore.impl.ThriftDataStoreConnector; +import org.wso2.carbon.device.mgt.etc.util.ResourceFileLoader; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore; +import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector; +import org.wso2.carbon.device.mgt.etc.datastore.DataStoreConnector; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.etc.exception.UnauthorizedException; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.File; +import java.util.HashMap; +import java.util.List; + +public class DeviceController { + + private static final Log log = LogFactory.getLog(DeviceController.class); + + private static HashMap dataStoresMap = new HashMap<>(); + private static HashMap controlQueueMap = new HashMap<>(); + + public static void init() { + DeviceCloudConfig config = DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig(); + + if (config != null) { + initSecurity(config); + loadDataStores(config); + loadControlQueues(config); + } + + } + + + private static void loadDataStores(DeviceCloudConfig config) { + List dataStores = config.getDataStores().getDataStore(); + if (dataStores == null) { + log.error("Error occurred when trying to read data stores configurations"); + return; + } + + for (DataStore dataStore : dataStores) { + try { + String handlerClass = dataStore.getPublisherClass(); + + Class dataStoreClass = Class.forName(handlerClass); + if (DataStoreConnector.class.isAssignableFrom(dataStoreClass)) { + + DataStoreConnector dataStoreConnector = + (DataStoreConnector) dataStoreClass.newInstance(); + String dataStoreName = dataStore.getName(); + if (dataStore.isEnabled()) { + dataStoresMap.put(dataStoreName, dataStoreConnector); + dataStoreConnector.initDataStore(dataStore); + } + } + } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) { + log.error("Error occurred when trying to initiate data store", ex); + } catch (DeviceControllerException ex) { + log.error(ex.getMessage()); + } + } + } + + private static void loadControlQueues(DeviceCloudConfig config) { + List controlQueues = config.getControlQueues().getControlQueue(); + if (controlQueues == null) { + log.error("Error occurred when trying to read control queue configurations"); + return; + } + + for (ControlQueue controlQueue : controlQueues) { + try { + String handlerClass = controlQueue.getControlClass(); + + Class controlQueueClass = Class.forName(handlerClass); + if (ControlQueueConnector.class.isAssignableFrom(controlQueueClass)) { + + ControlQueueConnector controlQueueConnector = + (ControlQueueConnector) controlQueueClass.newInstance(); + String controlQueueName = controlQueue.getName(); + if (controlQueue.isEnabled()) { + controlQueueMap.put(controlQueueName, controlQueueConnector); + controlQueueConnector.initControlQueue(); + } + } + } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) { + log.error("Error occurred when trying to initiate control queue" + + controlQueue.getName()); + } catch (DeviceControllerException ex) { + log.error(ex.getMessage()); + } + } + } + + private static void initSecurity(DeviceCloudConfig config) { + String trustStoreFile = null; + String trustStorePassword = null; + File certificateFile = null; + + trustStoreFile = config.getSecurity().getClientTrustStore(); + trustStorePassword = config.getSecurity().getPassword(); + String certificatePath = + CarbonUtils.getCarbonHome() + File.separator + "repository" + File.separator + + "resources" + File.separator + "security" + File.separator; + + certificateFile = new ResourceFileLoader(certificatePath + trustStoreFile).getFile(); + if (certificateFile.exists()) { + trustStoreFile = certificateFile.getAbsolutePath(); + log.info("Trust Store Path : " + trustStoreFile); + + System.setProperty("javax.net.ssl.trustStore", trustStoreFile); + System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); + } else { + log.error("Trust Store not found in path : " + certificateFile.getAbsolutePath()); + } + } + + public boolean publishMqttControl(String owner, String deviceType, String deviceId, String key, + String value) throws DeviceControllerException { + HashMap deviceControlsMap = new HashMap(); + + deviceControlsMap.put("owner", owner); + deviceControlsMap.put("deviceType", deviceType); + deviceControlsMap.put("deviceId", deviceId); + deviceControlsMap.put("key", key); + deviceControlsMap.put("value", value); + + + ControlQueueConnector mqttControlQueue = controlQueueMap.get(MqttConfig.getMqttQueueConfigName()); + if (mqttControlQueue == null) { + log.info("MQTT Queue has not been listed in 'device-mgt-config.xml'"); + return false; + } + + mqttControlQueue.enqueueControls(deviceControlsMap); + return true; + } + + private boolean pushData(HashMap deviceDataMap, String publisherType) + throws DeviceControllerException { + + DataStoreConnector dataStoreConnector = dataStoresMap.get(publisherType); + if (dataStoreConnector == null) { + log.error(publisherType + " is not enabled"); + return false; + } + + dataStoreConnector.publishDeviceData(deviceDataMap); + return true; + } + + public boolean pushBamData(String owner, String deviceType, String deviceId, Long time, + String key, + String value, String description) throws UnauthorizedException { + + HashMap deviceDataMap = new HashMap(); + + deviceDataMap.put("owner", owner); + deviceDataMap.put("deviceType", deviceType); + deviceDataMap.put("deviceId", deviceId); + deviceDataMap.put("time", "" + time); + deviceDataMap.put("key", key); + deviceDataMap.put("value", value); + deviceDataMap.put("description", description); + + try { + return pushData(deviceDataMap, ThriftDataStoreConnector.DataStoreConstants.BAM); + } catch (DeviceControllerException e) { + throw new UnauthorizedException(e); + } + } + + public boolean pushCepData(String owner, String deviceType, String deviceId, Long time, + String key, + String value, String description) + throws UnauthorizedException { + HashMap deviceDataMap = new HashMap(); + + deviceDataMap.put("owner", owner); + deviceDataMap.put("deviceType", deviceType); + deviceDataMap.put("deviceId", deviceId); + deviceDataMap.put("time", "" + time); + deviceDataMap.put("key", key); + deviceDataMap.put("value", value); + deviceDataMap.put("description", description); + + try { + return pushData(deviceDataMap, ThriftDataStoreConnector.DataStoreConstants.CEP); + } catch (DeviceControllerException e) { + throw new UnauthorizedException(e); + } + + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceManagement.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceManagement.java new file mode 100644 index 00000000000..72e2416479f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceManagement.java @@ -0,0 +1,122 @@ +/* +c * Copyright (c) 2014, 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.etc; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +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.EnrolmentInfo; +import org.wso2.carbon.device.mgt.etc.util.DeviceTypes; +import org.wso2.carbon.device.mgt.etc.util.ZipArchive; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOException; +import org.wso2.carbon.device.mgt.core.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.core.dto.DeviceType; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class DeviceManagement { + + private static Log log = LogFactory.getLog(DeviceManagement.class); + + public DeviceManagement(String tenantDomain){ + } + + public boolean isExist(String owner, DeviceIdentifier deviceIdentifier) + throws DeviceManagementException { + + DeviceManagementProviderService dmService = getDeviceManagementService(); + if (dmService.isEnrolled(deviceIdentifier)) { + Device device=dmService.getDevice(deviceIdentifier); + if (device.getEnrolmentInfo().getOwner().equals(owner)) { + return true; + } + } + + return false; + } + + public DeviceManagementProviderService getDeviceManagementService() { + return (DeviceManagementProviderService) CarbonContext.getThreadLocalCarbonContext().getOSGiService( + DeviceManagementProviderService.class, null); + } + + public Device[] getActiveDevices(String username) + throws DeviceManagementException { + List devices = getDeviceManagementService().getDevicesOfUser( + username); + List activeDevices = new ArrayList<>(); + if (devices != null) { + for (Device device : devices) { + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { + activeDevices.add(device); + } + } + } + return activeDevices.toArray(new Device[activeDevices.size()]); + } + + public int getActiveDeviceCount(String username) + throws DeviceManagementException { + List devices = getDeviceManagementService().getDevicesOfUser(username); + + if (devices != null) { + List activeDevices = new ArrayList<>(); + for (Device device : devices) { + if (device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { + activeDevices.add(device); + } + } + return activeDevices.size(); + } + return 0; + } + + public ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams) + throws DeviceManagementException { + /* create a context and add data */ + try { + return IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, + contextParams); + } catch (IOException e) { + throw new DeviceManagementException("Zip File Creation Failed",e); + } + } + + public DeviceTypes[] getDeviceTypes(int tenantId) throws DeviceManagementDAOException { + List deviceTypes = DeviceManagementDAOFactory.getDeviceTypeDAO().getDeviceTypes(tenantId); + DeviceTypes dTypes[] = new DeviceTypes[deviceTypes.size()]; + int iter = 0; + for (DeviceType type : deviceTypes) { + + DeviceTypes dt = new DeviceTypes(); + dt.setName(type.getName()); + dTypes[iter] = dt; + iter++; + } + return dTypes; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceValidator.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceValidator.java new file mode 100644 index 00000000000..8414402fcfd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/DeviceValidator.java @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2014, 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.etc; + +import org.apache.commons.collections.map.LRUMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.context.PrivilegedCarbonContext; +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.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; + +public class DeviceValidator { + + private static Log log = LogFactory.getLog(DeviceValidator.class); + private static LRUMap cache; + + // private static Log log = LogFactory.getLog(DeviceValidator.class); + static { + int cacheSize = DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getDeviceUserValidator() + .getCacheSize(); + cache = new LRUMap(cacheSize); + } + + private PrivilegedCarbonContext ctx; + + public boolean isExist(String owner, String tenantDomain, DeviceIdentifier deviceId) + throws DeviceManagementException { + return true; + //TODO check cache impl + //return cacheCheck(owner,tenantDomain, deviceId); + } + + private boolean cacheCheck(String owner, String tenantDomain, DeviceIdentifier deviceId) + throws DeviceManagementException { + + String value = (String) cache.get(deviceId); + + if (value != null && !value.isEmpty()) { + return value.equals(owner); + } else { + boolean status = isExist(owner, deviceId); + if (status) { + addToCache(owner, deviceId); + } + return status; + } + } + + private void addToCache(String owner, DeviceIdentifier deviceId) { + cache.put(deviceId, owner); + } + + private boolean isExist(String owner, DeviceIdentifier deviceIdentifier) throws DeviceManagementException { + try { + DeviceManagementProviderService dmService = getServiceProvider(); + if (dmService.isEnrolled(deviceIdentifier)) { + Device device = dmService.getDevice(deviceIdentifier); + if (device.getEnrolmentInfo().getOwner().equals(owner)) { + return true; + } + } + + return false; + } finally { + endTenantFlow(); + } + } + + private DeviceManagementProviderService getServiceProvider() { + String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); + PrivilegedCarbonContext.startTenantFlow(); + ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantDomain(tenantDomain, true); + if (log.isDebugEnabled()) { + log.debug("Getting thread local carbon context for tenant domain: " + tenantDomain); + } + return (DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null); + } + + private void endTenantFlow() { + PrivilegedCarbonContext.endTenantFlow(); + ctx = null; + if (log.isDebugEnabled()) { + log.debug("Tenant flow ended"); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/UserManagement.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/UserManagement.java new file mode 100644 index 00000000000..b12863347c4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/UserManagement.java @@ -0,0 +1,240 @@ +package org.wso2.carbon.device.mgt.etc; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.context.CarbonContext; +import org.wso2.carbon.device.mgt.etc.util.Role; +import org.wso2.carbon.device.mgt.etc.util.User; +import org.wso2.carbon.user.api.Claim; +import org.wso2.carbon.user.api.Permission; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.api.UserStoreManager; +import org.wso2.carbon.user.core.UserCoreConstants; +import org.wso2.carbon.user.core.service.RealmService; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserManagement { + private static Log log = LogFactory.getLog(UserManagement.class); + + public static final String GIVEN_NAME = UserCoreConstants.ClaimTypeURIs.GIVEN_NAME; + public static final String EMAIL_ADDRESS = UserCoreConstants.ClaimTypeURIs.EMAIL_ADDRESS; + public static final String SURNAME = UserCoreConstants.ClaimTypeURIs.SURNAME; + public static final String STREET_ADDRESS = UserCoreConstants.ClaimTypeURIs.STREET_ADDRESS; + public static final String LOCALITY = UserCoreConstants.ClaimTypeURIs.LOCALITY; + public static final String REGION = UserCoreConstants.ClaimTypeURIs.REGION; + public static final String POSTAL_CODE = UserCoreConstants.ClaimTypeURIs.POSTAL_CODE; + public static final String COUNTRY = UserCoreConstants.ClaimTypeURIs.COUNTRY; + public static final String HONE = UserCoreConstants.ClaimTypeURIs.HONE; + public static final String IM = UserCoreConstants.ClaimTypeURIs.IM; + public static final String ORGANIZATION = UserCoreConstants.ClaimTypeURIs.ORGANIZATION; + public static final String URL = UserCoreConstants.ClaimTypeURIs.URL; + public static final String TITLE = UserCoreConstants.ClaimTypeURIs.TITLE; + public static final String ROLE = UserCoreConstants.ClaimTypeURIs.ROLE; + public static final String MOBILE = UserCoreConstants.ClaimTypeURIs.MOBILE; + public static final String NICKNAME = UserCoreConstants.ClaimTypeURIs.NICKNAME; + public static final String DATE_OF_BIRTH = UserCoreConstants.ClaimTypeURIs.DATE_OF_BIRTH; + public static final String GENDER = UserCoreConstants.ClaimTypeURIs.GENDER; + public static final String ACCOUNT_STATUS = UserCoreConstants.ClaimTypeURIs.ACCOUNT_STATUS; + public static final String CHALLENGE_QUESTION_URI + = UserCoreConstants.ClaimTypeURIs.CHALLENGE_QUESTION_URI; + public static final String IDENTITY_CLAIM_URI + = UserCoreConstants.ClaimTypeURIs.IDENTITY_CLAIM_URI; + public static final String TEMPORARY_EMAIL_ADDRESS + = UserCoreConstants.ClaimTypeURIs.TEMPORARY_EMAIL_ADDRESS; + + private static final String DEVICE_API_ACCESS_ROLE_NAME="deviceRole"; + private static final String DEVICE_USER_API_ACCESS_ROLE_NAME="deviceUser"; + private static RealmService realmService; + + public static RealmService getRealmService() { + return realmService; + } + + public static void setRealmService(RealmService realmService) { + UserManagement.realmService = realmService; + } + + public int getUserCount() { + + try { + String[] users = getUserStoreManager().listUsers("", -1); + if (users == null) { + return 0; + } + return users.length; + } catch (UserStoreException e) { + String msg + = + "Error occurred while retrieving the list of users that exist within the " + + "current tenant"; + log.error(msg, e); + return 0; + } + } + + + + //=========================================================================== + //TODO: Below methods are implemented to support jaggery code upon removal of org.wso2.carbon + // .device.mgt.user.core from CDMF + //=========================================================================== + + private static UserStoreManager getUserStoreManager() throws UserStoreException { + + UserStoreManager userStoreManager; + try { + + if (realmService == null) { + String msg = "Realm service not initialized"; + log.error(msg); + throw new UserStoreException(msg); + } + int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); + userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager(); + } catch (UserStoreException e) { + String msg = "Error occurred while retrieving current user store manager"; + log.error(msg, e); + throw new UserStoreException(msg, e); + } finally { + //PrivilegedCarbonContext.endTenantFlow(); + } + return userStoreManager; + + + } + + public List getUsersForTenantAndRole(int tenantId, String roleName) + throws UserStoreException { + + UserStoreManager userStoreManager = getUserStoreManager(); + String[] userNames; + ArrayList usersList = new ArrayList(); + + userNames = userStoreManager.getUserListOfRole(roleName); + User newUser; + for (String userName : userNames) { + newUser = new User(userName); + Claim[] claims = userStoreManager.getUserClaimValues(userName, null); + Map claimMap = new HashMap(); + for (Claim claim : claims) { + String claimURI = claim.getClaimUri(); + String value = claim.getValue(); + claimMap.put(claimURI, value); + } + setUserClaims(newUser, claimMap); + usersList.add(newUser); + } + + return usersList; + } + + public List getRolesForTenant(int tenantId) throws UserStoreException { + + String[] roleNames; + ArrayList rolesList = new ArrayList(); + Role newRole; + UserStoreManager userStoreManager = getUserStoreManager(); + + roleNames = userStoreManager.getRoleNames(); + for (String roleName : roleNames) { + newRole = new Role(roleName); + rolesList.add(newRole); + } + + return rolesList; + } + + public List getUsersForTenant(int tenantId) throws UserStoreException { + + UserStoreManager userStoreManager; + String[] userNames; + ArrayList usersList = new ArrayList(); + + userStoreManager = getUserStoreManager(); + + userNames = userStoreManager.listUsers("", -1); + User newUser; + for (String userName : userNames) { + newUser = new User(userName); + Claim[] claims = userStoreManager.getUserClaimValues(userName, null); + Map claimMap = new HashMap(); + for (Claim claim : claims) { + String claimURI = claim.getClaimUri(); + String value = claim.getValue(); + claimMap.put(claimURI, value); + } + setUserClaims(newUser, claimMap); + usersList.add(newUser); + } + + return usersList; + } + + public User getUser(String username, int tenantId) throws UserStoreException { + UserStoreManager userStoreManager; + User user; + userStoreManager = getUserStoreManager(); + user = new User(username); + + Claim[] claims = userStoreManager.getUserClaimValues(username, null); + Map claimMap = new HashMap(); + for (Claim claim : claims) { + String claimURI = claim.getClaimUri(); + String value = claim.getValue(); + claimMap.put(claimURI, value); + } + + setUserClaims(user, claimMap); + + return user; + } + + private void setUserClaims(User newUser, Map claimMap) { + newUser.setRoleName(UserCoreConstants.ClaimTypeURIs.ROLE); + newUser.setAccountStatus(claimMap.get(ACCOUNT_STATUS)); + newUser.setChallengeQuestion(claimMap.get(CHALLENGE_QUESTION_URI)); + newUser.setCountry(claimMap.get(COUNTRY)); + newUser.setDateOfBirth(claimMap.get(DATE_OF_BIRTH)); + newUser.setEmail(claimMap.get(EMAIL_ADDRESS)); + newUser.setFirstName(claimMap.get(GIVEN_NAME)); + newUser.setGender(claimMap.get(GENDER)); + newUser.setHone(claimMap.get(HONE)); + newUser.setIm(claimMap.get(IM)); + newUser.setIdentityClaimUri(claimMap.get(IDENTITY_CLAIM_URI)); + newUser.setLastName(claimMap.get(SURNAME)); + newUser.setLocality(claimMap.get(LOCALITY)); + newUser.setEmail(claimMap.get(EMAIL_ADDRESS)); + newUser.setMobile(claimMap.get(MOBILE)); + newUser.setNickName(claimMap.get(NICKNAME)); + newUser.setOrganization(claimMap.get(ORGANIZATION)); + newUser.setPostalCode(claimMap.get(POSTAL_CODE)); + newUser.setRegion(claimMap.get(REGION)); + newUser.setStreatAddress(claimMap.get(STREET_ADDRESS)); + newUser.setTitle(claimMap.get(TITLE)); + newUser.setTempEmailAddress(claimMap.get(TEMPORARY_EMAIL_ADDRESS)); + } + + public static void registerApiAccessRoles() { + UserStoreManager userStoreManager = null; + try { + userStoreManager = getUserStoreManager(); + String[] userList = new String[]{"admin"}; + Permission permissions[] = new Permission[]{}; + if (!userStoreManager.isExistingRole(DEVICE_API_ACCESS_ROLE_NAME)) { + userStoreManager.addRole(DEVICE_API_ACCESS_ROLE_NAME, userList, permissions); + } + if (!userStoreManager.isExistingRole(DEVICE_USER_API_ACCESS_ROLE_NAME)) { + userStoreManager.addRole(DEVICE_USER_API_ACCESS_ROLE_NAME, userList, permissions); + } + } catch (UserStoreException e) { + log.error("error on wso2 user component"); + } + + + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceEventsStatisticsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceEventsStatisticsException.java new file mode 100644 index 00000000000..ba91c762d6d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceEventsStatisticsException.java @@ -0,0 +1,36 @@ +/* + * 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.common.impl.analytics.statistics; + +public class DeviceEventsStatisticsException extends Exception{ + + private static final long serialVersionUID = -5743346027793277063L; + + public DeviceEventsStatisticsException(String msg) { + super(msg); + } + + public DeviceEventsStatisticsException(String msg, Throwable e) { + super(msg, e); + } + + public DeviceEventsStatisticsException(Throwable throwable) { + super(throwable); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtEventsStatisticsClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtEventsStatisticsClient.java new file mode 100644 index 00000000000..564aa702342 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtEventsStatisticsClient.java @@ -0,0 +1,139 @@ +/* + * 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.common.impl.analytics.statistics; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.impl.analytics.statistics.dto.DeviceEventsDTO; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class DeviceMgtEventsStatisticsClient { + + private static final Log log = LogFactory.getLog(DeviceMgtEventsStatisticsClient.class); + + private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB"; + + private static volatile DataSource dataSource = null; + + + public static void initializeDataSource() throws DeviceEventsStatisticsException { + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME); + } catch (NamingException e) { + throw new DeviceEventsStatisticsException("Error while looking up the data " + + "source: " + DATA_SOURCE_NAME); + } + } + + public List getRecentDeviceStats(String owner, int recordLimit) + throws DeviceEventsStatisticsException { + + if (dataSource == null) { + throw new DeviceEventsStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration."); + } + + Connection connection = null; + Statement statement = null; + ResultSet rs = null; + try { + connection = dataSource.getConnection(); + statement = connection.createStatement(); + String query = null; + String table = "DEVICE_EVENTS"; + + if(owner==null){ + throw new DeviceEventsStatisticsException("Owner cannot be null!"); + } + + String ownerString = ""; + ownerString = String.format(" AND owner = '%s'", owner); + + String limitString = ""; + if(recordLimit > 0){ + limitString = String.format(" LIMIT %d", recordLimit); + } + + query = String.format("SELECT * FROM %s WHERE 1=1 %s ORDER BY `time` DESC %s" + ,table, ownerString, limitString); + + log.info("query: " + query); + + if (query == null) { + throw new DeviceEventsStatisticsException("SQL query is null!"); + } + + List DeviceEventsDTOs = new ArrayList(); + rs = statement.executeQuery(query); + while (rs.next()) { + DeviceEventsDTO DeviceEventsDTO = new DeviceEventsDTO(); + DeviceEventsDTO.setTime(rs.getString("TIME")); + DeviceEventsDTO.setDeviceActivity(rs.getString("ACTIVITY")); + //(id + type) uniquely identifies a device + DeviceEventsDTO.setDeviceId(rs.getString("DEVICEID")); + DeviceEventsDTO.setDeviceType(rs.getString("DEVICETYPE")); + + DeviceEventsDTOs.add(DeviceEventsDTO); + + } + + return DeviceEventsDTOs; + + } catch (Exception e) { +// throw new IoTEventsStatisticsException( +// "Error occurred while querying from JDBC database", e); + //Exception hiding to avoid GC error + log.error("Error occurred while querying from JDBC database: " + e.getMessage()); + return new ArrayList<>(); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ignore) { + + } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException ignore) { + + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignore) { + + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtUsageStatisticsClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtUsageStatisticsClient.java new file mode 100644 index 00000000000..4e56dcf85ca --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceMgtUsageStatisticsClient.java @@ -0,0 +1,176 @@ +/* + * 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.common.impl.analytics.statistics; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.impl.analytics.statistics.dto.DeviceUsageDTO; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class DeviceMgtUsageStatisticsClient { + + private static final Log log = LogFactory.getLog(DeviceMgtUsageStatisticsClient.class); + + private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB"; + + private static volatile DataSource dataSource = null; + + + public static void initializeDataSource() throws DeviceUsageStatisticsException { + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME); + } catch (NamingException e) { + throw new DeviceUsageStatisticsException("Error while looking up the data " + + "source: " + DATA_SOURCE_NAME); + } + } +// +// public List getTemperatureData(String user, String deviceId, String fromDate, +// String toDate) +// throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching temperature data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, fromDate, +// toDate); +// } +// +// public List getBulbStatusData(String user, String deviceId, String fromDate, +// String toDate) +// throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching bulb status data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_BULB_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate, +// toDate); +// } +// +// public List getFanStatusData(String user, String deviceId, String fromDate, +// String toDate) throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching fan status data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_FAN_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate, +// toDate); +// } + + public List getDeviceStats(String table, String valueColumn, String owner, + String deviceId, String fromDate, String toDate) + throws DeviceUsageStatisticsException { + + if (dataSource == null) { + throw new DeviceUsageStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration."); + } + + Connection connection = null; + Statement statement = null; + ResultSet rs = null; + try { + connection = dataSource.getConnection(); + statement = connection.createStatement(); + String query = null; + + String ownerString = ""; + if (owner != null) { + ownerString = String.format("owner = '%s' AND ", owner); + } + + if (fromDate != null && toDate != null) { + //fromDate = getConvertedTime(fromDate); + //toDate = getConvertedTime(toDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` " + + "BETWEEN '%s' AND '%s'", table, deviceId, fromDate, toDate); + } else if (fromDate != null) { + //fromDate = getConvertedTime(fromDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` >= " + + "'%s'", table, deviceId, fromDate); + } else if (toDate != null) { + //toDate = getConvertedTime(toDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` <= " + + "'%s'", table, deviceId, toDate); + } + + log.info("query: " + query); + + if (query == null) { + return null; + } + + List deviceUsageDTOs = new ArrayList(); + rs = statement.executeQuery(query); + while (rs.next()) { + DeviceUsageDTO deviceUsageDTO = new DeviceUsageDTO(); + deviceUsageDTO.setTime(rs.getString("TIME")); + deviceUsageDTO.setValue(rs.getString(valueColumn)); + + deviceUsageDTOs.add(deviceUsageDTO); + + } + + return deviceUsageDTOs; + + } catch (Exception e) { +// throw new IoTUsageStatisticsException( +// "Error occurred while querying from JDBC database", e); + //Exception hiding to avoid GC error + log.error("Error occurred while querying from JDBC database: " + e.getMessage()); + return new ArrayList<>(); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ignore) { + + } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException ignore) { + + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignore) { + + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceUsageStatisticsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceUsageStatisticsException.java new file mode 100644 index 00000000000..57b0dd390a2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/DeviceUsageStatisticsException.java @@ -0,0 +1,36 @@ +/* + * 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.common.impl.analytics.statistics; + +public class DeviceUsageStatisticsException extends Exception{ + + private static final long serialVersionUID = -5743346027793277063L; + + public DeviceUsageStatisticsException(String msg) { + super(msg); + } + + public DeviceUsageStatisticsException(String msg, Throwable e) { + super(msg, e); + } + + public DeviceUsageStatisticsException(Throwable throwable) { + super(throwable); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceEventsDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceEventsDTO.java new file mode 100644 index 00000000000..064acd52a8d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceEventsDTO.java @@ -0,0 +1,60 @@ +/* + * 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.common.impl.analytics.statistics.dto; + +public class DeviceEventsDTO { + + private String time; + private String deviceId; + private String deviceType; + private String deviceActivity; + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getDeviceActivity() { + return deviceActivity; + } + + public void setDeviceActivity(String deviceActivity) { + this.deviceActivity = deviceActivity; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceId() { + return deviceId; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceUsageDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceUsageDTO.java new file mode 100644 index 00000000000..2927b8a054d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/analytics/statistics/dto/DeviceUsageDTO.java @@ -0,0 +1,42 @@ +/* + * 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.common.impl.analytics.statistics.dto; + +public class DeviceUsageDTO { + + private String time; + private String value; + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/AccessTokenInfo.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/AccessTokenInfo.java new file mode 100644 index 00000000000..e6ac4e24034 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/AccessTokenInfo.java @@ -0,0 +1,60 @@ +/* + * 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.etc.apimgt; + +public class AccessTokenInfo { + + private String token_type; + private int expires_in; + private String refresh_token; + private String access_token; + + public String getToken_type() { + return token_type; + } + + public void setToken_type(String token_type) { + this.token_type = token_type; + } + + public int getExpires_in() { + return expires_in; + } + + public void setExpires_in(int expres_in) { + this.expires_in = expres_in; + } + + public String getRefresh_token() { + return refresh_token; + } + + public void setRefresh_token(String refresh_token) { + this.refresh_token = refresh_token; + } + + public String getAccess_token() { + return access_token; + } + + public void setAccess_token(String access_token) { + this.access_token = access_token; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/ApisAppClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/ApisAppClient.java new file mode 100644 index 00000000000..54287e818f6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/apimgt/ApisAppClient.java @@ -0,0 +1,182 @@ +/* + * 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.etc.apimgt; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ApiManagerConfig; +import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException; +import org.wso2.carbon.device.mgt.etc.util.IoTUtil; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +public class ApisAppClient { + + private static ConcurrentHashMap deviceTypeToApiAppMap = new ConcurrentHashMap<>(); + private static ApisAppClient instance = null; + + private String loginEndpoint; + private String subscriptionListEndpoint; + private static Log log = LogFactory.getLog(ApisAppClient.class); + private boolean isEnabled; + + public static ApisAppClient getInstance() { + + if (instance == null) { + instance = new ApisAppClient(); + } + return instance; + } + + private ApisAppClient() { + ApiManagerConfig apiManagerConfig = + DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager(); + String serverUrl = apiManagerConfig.getServerURL(); + String serverPort = apiManagerConfig.getServerPort(); + isEnabled = apiManagerConfig.isEnabled(); + + String loginURL = serverUrl + ":" + serverPort + apiManagerConfig.getLoginURL(); + loginEndpoint = loginURL + "?action=login&username=" + apiManagerConfig.getUsername() + + "&password=" + apiManagerConfig.getPassword(); + + String subscriptionListUrl = serverUrl + ":" + serverPort + apiManagerConfig.getSubscriptionListURL(); + subscriptionListEndpoint = subscriptionListUrl + "?action=getAllSubscriptions"; + } + + public String getBase64EncodedConsumerKeyAndSecret(String deviceType) { + if (!isEnabled) return null; + String consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType); + if (consumerKeyAndSecret == null) { + ArrayList iotDeviceTypeConfigs = new ArrayList<>(); + DeviceTypeConfig DeviceTypeConfig = + DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap().get(deviceType); + if (DeviceTypeConfig != null) { + iotDeviceTypeConfigs.add(DeviceTypeConfig); + setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigs); + consumerKeyAndSecret = deviceTypeToApiAppMap.get(deviceType); + if (consumerKeyAndSecret == null) { + log.warn("There is no API application for the device type " + deviceType); + } + } + } + return consumerKeyAndSecret; + } + + public void setBase64EncodedConsumerKeyAndSecret(List iotDeviceTypeConfigList) { + if (!isEnabled) { + return; + } + URL loginURL; + try { + loginURL = new URL(loginEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed URL " + loginEndpoint; + log.error(errMsg); + return; + } + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(loginURL.getPort(), loginURL.getProtocol()); + } catch (Exception e) { + log.error("Error on getting a http client for port :" + loginURL.getPort() + " protocol :" + + loginURL.getProtocol()); + return; + } + + HttpPost postMethod = new HttpPost(loginEndpoint); + JSONObject apiJsonResponse; + try { + HttpResponse httpResponse = httpClient.execute(postMethod); + String response = IoTUtil.getResponseString(httpResponse); + if (log.isDebugEnabled()) { + log.debug(response); + } + JSONObject jsonObject = new JSONObject(response); + + + boolean apiError = jsonObject.getBoolean("error"); + if (!apiError) { + String cookie = httpResponse.getHeaders("Set-Cookie")[0].getValue().split(";")[0]; + HttpGet getMethod = new HttpGet(subscriptionListEndpoint); + getMethod.setHeader("cookie", cookie); + httpResponse = httpClient.execute(getMethod); + response = IoTUtil.getResponseString(httpResponse); + + if (log.isDebugEnabled()) { + log.debug(response); + } + apiJsonResponse = new JSONObject(response); + apiError = apiJsonResponse.getBoolean("error"); + if (apiError) { + log.error("invalid subscription endpoint " + subscriptionListEndpoint); + return; + } + } else { + log.error("invalid access for login endpoint " + loginEndpoint); + return; + } + } catch (IOException | JSONException | DeviceMgtCommonsException e) { + log.warn("Trying to connect to the Api manager"); + return; + } + + try { + JSONArray jsonSubscriptions = apiJsonResponse.getJSONObject("subscriptions").getJSONArray("applications"); + + HashMap subscriptionMap = new HashMap<>(); + for (int n = 0; n < jsonSubscriptions.length(); n++) { + + JSONObject object = jsonSubscriptions.getJSONObject(n); + String appName = object.getString("name"); + String prodConsumerKey = object.getString("prodConsumerKey"); + String prodConsumerSecret = object.getString("prodConsumerSecret"); + subscriptionMap.put(appName, new String(Base64.encodeBase64( + (prodConsumerKey + ":" + prodConsumerSecret).getBytes()))); + } + + for (DeviceTypeConfig iotDeviceTypeConfig : iotDeviceTypeConfigList) { + String deviceType = iotDeviceTypeConfig.getType(); + String deviceTypeApiApplicationName = iotDeviceTypeConfig.getApiApplicationName(); + String base64EncodedString = subscriptionMap.get(deviceTypeApiApplicationName); + if (base64EncodedString != null && base64EncodedString.length() != 0) { + deviceTypeToApiAppMap.put(deviceType, base64EncodedString); + } + } + } catch (JSONException e) { + log.error("Json exception: " + e.getMessage(), e); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/DeviceTypeConfigurationManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/DeviceTypeConfigurationManager.java new file mode 100644 index 00000000000..1b9977b05b5 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/DeviceTypeConfigurationManager.java @@ -0,0 +1,127 @@ +/* + * 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.etc.config.devicetype; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.etc.ApisAppClient; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfigManager; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.ValidationEvent; +import javax.xml.bind.ValidationEventHandler; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import java.io.File; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Class responsible for the iot device manager configuration initialization. + */ +public class DeviceTypeConfigurationManager { + private static final Log log = LogFactory.getLog(DeviceTypeConfigurationManager.class); + + private static final String DEVICE_TYPE_CONFIG_XML_NAME = "devicetype-config.xml"; + private static final String DEVICE_TYPE_CONFIG_XSD_NAME = "devicetype-config.xsd"; + private DeviceTypeConfigManager currentDeviceTypeConfig; + private static DeviceTypeConfigurationManager + deviceConfigManager = new DeviceTypeConfigurationManager(); + + private final String deviceMgtConfigXMLPath = CarbonUtils.getCarbonConfigDirPath() + + File.separator + DEVICE_TYPE_CONFIG_XML_NAME; + + private final String deviceMgtConfigXSDPath = CarbonUtils.getCarbonConfigDirPath() + + File.separator + DEVICE_TYPE_CONFIG_XSD_NAME; + + private HashMap deviceTypeConfigMap = new HashMap<>(); + + public static DeviceTypeConfigurationManager getInstance() { + return deviceConfigManager; + } + + public synchronized void initConfig() throws DeviceManagementException { + try { + SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + Schema schema = sf.newSchema(new File(deviceMgtConfigXSDPath)); + + File iotDeviceMgtConfig = new File(deviceMgtConfigXMLPath); + Document doc = IotDeviceManagementUtil.convertToDocument(iotDeviceMgtConfig); + JAXBContext iotDeviceMgmtContext = JAXBContext.newInstance(DeviceTypeConfigManager.class); + Unmarshaller unmarshaller = iotDeviceMgmtContext.createUnmarshaller(); + unmarshaller.setSchema(schema); + unmarshaller.setEventHandler(new IotConfigValidationEventHandler()); + this.currentDeviceTypeConfig = (DeviceTypeConfigManager) unmarshaller.unmarshal(doc); + + List iotDeviceTypeConfigList= currentDeviceTypeConfig.getDeviceTypeConfigs(); + for(DeviceTypeConfig iotDeviceTypeConfig:iotDeviceTypeConfigList){ + String applicationName=iotDeviceTypeConfig.getApiApplicationName(); + + if(applicationName==null||applicationName.isEmpty()){ + iotDeviceTypeConfig.setApiApplicationName(iotDeviceTypeConfig.getType()); + } + deviceTypeConfigMap.put(iotDeviceTypeConfig.getType(), iotDeviceTypeConfig); + } + ApisAppClient.getInstance().setBase64EncodedConsumerKeyAndSecret(iotDeviceTypeConfigList); + } catch (Exception e) { + String error = "Error occurred while initializing device configurations"; + log.error(error, e); + } + } + + public DeviceTypeConfigManager getDeviceManagementConfig() { + return currentDeviceTypeConfig; + } + + + public Map getDeviceTypeConfigMap(){ + return Collections.unmodifiableMap(deviceTypeConfigMap); + } + + + private class IotConfigValidationEventHandler implements ValidationEventHandler { + @Override + public boolean handleEvent(ValidationEvent event) { + String error= "\nEVENT" +"\nSEVERITY: " + event.getSeverity() + + "\nMESSAGE: " + event.getMessage() + +"\nLINKED EXCEPTION: " + event.getLinkedException() + +"\nLOCATOR" + +"\n LINE NUMBER: " + event.getLocator().getLineNumber() + +"\n COLUMN NUMBER: " + event.getLocator().getColumnNumber() + +"\n OFFSET: " + event.getLocator().getOffset() + +"\n OBJECT: " + event.getLocator().getObject() + +"\n NODE: " + event.getLocator().getNode() + +"\n URL: " + event.getLocator().getURL(); + + + log.error(error); + return true; + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfig.java new file mode 100644 index 00000000000..943e45d2de6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfig.java @@ -0,0 +1,135 @@ +/* + * 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.etc.config.devicetype.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DeviceTypeConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *       
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DeviceTypeConfig", propOrder = { + "datasourceName", + "apiApplicationName" +}) +public class DeviceTypeConfig { + + @XmlElement(name = "DatasourceName", required = true) + protected String datasourceName; + @XmlElement(name = "ApiApplicationName") + protected String apiApplicationName; + @XmlAttribute(name = "type", required = true) + protected String type; + + /** + * Gets the value of the datasourceName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDatasourceName() { + return datasourceName; + } + + /** + * Sets the value of the datasourceName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDatasourceName(String value) { + this.datasourceName = value; + } + + /** + * Gets the value of the apiApplicationName property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getApiApplicationName() { + return apiApplicationName; + } + + /** + * Sets the value of the apiApplicationName property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setApiApplicationName(String value) { + this.apiApplicationName = value; + } + + /** + * Gets the value of the type property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getType() { + return type; + } + + /** + * Sets the value of the type property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setType(String value) { + this.type = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfigManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfigManager.java new file mode 100644 index 00000000000..ee64418a455 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/DeviceTypeConfigManager.java @@ -0,0 +1,89 @@ +/* + * 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.etc.config.devicetype.datasource; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DeviceTypeConfigManager complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DeviceTypeConfigManager", propOrder = { + "deviceTypeConfigs" +}) + +@XmlRootElement(name = "DeviceTypeConfigManager") +public class DeviceTypeConfigManager { + + @XmlElement(name = "DeviceTypeConfig") + protected List deviceTypeConfigs; + + /** + * Gets the value of the DeviceTypeConfig property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the iotDeviceTypeConfig property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getDeviceTypeConfigs().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link DeviceTypeConfig } + * + * + */ + public List getDeviceTypeConfigs() { + if (deviceTypeConfigs == null) { + deviceTypeConfigs = new ArrayList<>(); + } + return this.deviceTypeConfigs; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/ObjectFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/ObjectFactory.java new file mode 100644 index 00000000000..1a3129ce60f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/devicetype/datasource/ObjectFactory.java @@ -0,0 +1,80 @@ + +/* + * 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.etc.config.devicetype.datasource; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.wso2.carbon.device.mgt.iot.common.config.server.configs package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + * + */ +@XmlRegistry +public class ObjectFactory { + + private final static QName _DeviceTypeConfigManager_QNAME = new QName("", "DeviceTypeConfigManager"); + + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.wso2.carbon.device.mgt.iot.common.config.server.configs + * + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link DeviceTypeConfigManager } + * + */ + public DeviceTypeConfigManager createDeviceTypeConfigManager() { + return new DeviceTypeConfigManager(); + } + + /** + * Create an instance of {@link DeviceTypeConfig } + * + */ + public DeviceTypeConfig createDeviceTypeConfig() { + return new DeviceTypeConfig(); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DeviceTypeConfigManager }{@code >}} + * + */ + @XmlElementDecl(namespace = "", name = "DeviceTypeConfigManager") + public JAXBElement createDeviceTypeConfigManager( + DeviceTypeConfigManager value) { + return new JAXBElement(_DeviceTypeConfigManager_QNAME, DeviceTypeConfigManager.class, null, value); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/DeviceCloudConfigManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/DeviceCloudConfigManager.java new file mode 100644 index 00000000000..d37c564535e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/DeviceCloudConfigManager.java @@ -0,0 +1,131 @@ +/* + * 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.etc.config.server; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DeviceCloudConfig; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.ValidationEvent; +import javax.xml.bind.ValidationEventHandler; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import java.io.File; +import java.util.List; + +/** + * Class responsible for the iot device manager configuration initialization. + */ +public class DeviceCloudConfigManager { + private static final Log log = LogFactory.getLog(DeviceCloudConfigManager.class); + + private static final String DEVICE_CONFIG_XML_NAME = "devicemgt-config.xml"; + private final String XMLCONFIGS_FILE_LOCATION = + CarbonUtils.getCarbonConfigDirPath() + File.separator + DEVICE_CONFIG_XML_NAME; + + private static final String DEVICE_CONFIG_XSD_NAME = "devicemgt-config.xsd"; + private final String XSDCONFIGS_FILE_LOCATION = + CarbonUtils.getCarbonConfigDirPath() + File.separator + DEVICE_CONFIG_XSD_NAME; + + private DeviceCloudConfig currentDeviceCloudConfig; + private static DeviceCloudConfigManager + deviceConfigurationManager = new DeviceCloudConfigManager(); + + private DeviceCloudConfigManager() { + } + + public static DeviceCloudConfigManager getInstance() { + return deviceConfigurationManager; + } + + public void initConfig() throws DeviceControllerException { + try { + SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + Schema schema = sf.newSchema(new File(XSDCONFIGS_FILE_LOCATION)); + + File deviceCloudMgtConfig = new File(XMLCONFIGS_FILE_LOCATION); + Document doc = IotDeviceManagementUtil.convertToDocument(deviceCloudMgtConfig); + JAXBContext deviceCloudContext = JAXBContext.newInstance(DeviceCloudConfig.class); + Unmarshaller unmarshaller = deviceCloudContext.createUnmarshaller(); + unmarshaller.setSchema(schema); + unmarshaller.setEventHandler(new IotConfigValidationEventHandler()); + this.currentDeviceCloudConfig = (DeviceCloudConfig) unmarshaller.unmarshal(doc); + } catch (Exception e) { + String error = "Error occurred while initializing DeviceController configurations"; + log.error(error); + throw new DeviceControllerException(error, e); + } + } + + public DeviceCloudConfig getDeviceCloudMgtConfig() { + return currentDeviceCloudConfig; + } + + public DataStore getDataStore(String name){ + List dataStores= currentDeviceCloudConfig.getDataStores().getDataStore(); + if(dataStores!=null) { + for (DataStore dataStore : dataStores) { + if (dataStore.getName().equals(name)) { + return dataStore; + } + } + } + return null; + } + + public ControlQueue getControlQueue(String name){ + List controlQueues= currentDeviceCloudConfig.getControlQueues().getControlQueue(); + if(controlQueues!=null) { + for (ControlQueue controlQueue : controlQueues) { + if (controlQueue.getName().equals(name)) { + return controlQueue; + } + } + } + return null; + } + + private class IotConfigValidationEventHandler implements ValidationEventHandler { + @Override + public boolean handleEvent(ValidationEvent event) { + String error= "\nEVENT" +"\nSEVERITY: " + event.getSeverity() + + "\nMESSAGE: " + event.getMessage() + +"\nLINKED EXCEPTION: " + event.getLinkedException() + +"\nLOCATOR" + +"\n LINE NUMBER: " + event.getLocator().getLineNumber() + +"\n COLUMN NUMBER: " + event.getLocator().getColumnNumber() + +"\n OFFSET: " + event.getLocator().getOffset() + +"\n OBJECT: " + event.getLocator().getObject() + +"\n NODE: " + event.getLocator().getNode() + +"\n URL: " + event.getLocator().getURL(); + log.error(error); + return true; + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ApiManagerConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ApiManagerConfig.java new file mode 100644 index 00000000000..73d43341d19 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ApiManagerConfig.java @@ -0,0 +1,351 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for ApiManagerConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ApiManagerConfig", propOrder = { + "enabled", + "accessTokenURL", + "serverURL", + "serverPort", + "gatewayPort", + "loginURL", + "subscriptionListURL", + "username", + "password", + "deviceGrantType", + "deviceScopes" +}) +public class ApiManagerConfig { + + @XmlElement(name = "Enabled") + protected boolean enabled; + @XmlElement(name = "AccessTokenURL", required = true) + protected String accessTokenURL; + @XmlElement(name = "ServerURL", required = true) + protected String serverURL; + @XmlElement(name = "ServerPort", required = true) + protected String serverPort; + @XmlElement(name = "GatewayPort", required = true) + protected String gatewayPort; + @XmlElement(name = "LoginURL", required = true) + protected String loginURL; + @XmlElement(name = "SubscriptionListURL", required = true) + protected String subscriptionListURL; + @XmlElement(name = "Username", required = true) + protected String username; + @XmlElement(name = "Password", required = true) + protected String password; + @XmlElement(name = "DeviceGrantType", required = true) + protected String deviceGrantType; + @XmlElement(name = "DeviceScopes", required = true) + protected String deviceScopes; + + /** + * Gets the value of the enabled property. + * + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Sets the value of the enabled property. + * + */ + public void setEnabled(boolean value) { + this.enabled = value; + } + + /** + * Gets the value of the accessTokenURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getAccessTokenURL() { + return accessTokenURL; + } + + /** + * Sets the value of the accessTokenURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setAccessTokenURL(String value) { + this.accessTokenURL = value; + } + + /** + * Gets the value of the serverURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getServerURL() { + return serverURL; + } + + /** + * Sets the value of the serverURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setServerURL(String value) { + this.serverURL = value; + } + + /** + * Gets the value of the serverPort property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getServerPort() { + return serverPort; + } + + /** + * Sets the value of the serverPort property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setServerPort(String value) { + this.serverPort = value; + } + + /** + * Gets the value of the gatewayPort property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getGatewayPort() { + return gatewayPort; + } + + /** + * Sets the value of the gatewayPort property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setGatewayPort(String value) { + this.gatewayPort = value; + } + + /** + * Gets the value of the loginURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getLoginURL() { + return loginURL; + } + + /** + * Sets the value of the loginURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setLoginURL(String value) { + this.loginURL = value; + } + + /** + * Gets the value of the subscriptionListURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getSubscriptionListURL() { + return subscriptionListURL; + } + + /** + * Sets the value of the subscriptionListURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setSubscriptionListURL(String value) { + this.subscriptionListURL = value; + } + + /** + * Gets the value of the username property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getUsername() { + return username; + } + + /** + * Sets the value of the username property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setUsername(String value) { + this.username = value; + } + + /** + * Gets the value of the password property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPassword() { + return password; + } + + /** + * Sets the value of the password property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPassword(String value) { + this.password = value; + } + + /** + * Gets the value of the deviceGrantType property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDeviceGrantType() { + return deviceGrantType; + } + + /** + * Sets the value of the deviceGrantType property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDeviceGrantType(String value) { + this.deviceGrantType = value; + } + + /** + * Gets the value of the deviceScopes property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getDeviceScopes() { + return deviceScopes; + } + + /** + * Sets the value of the deviceScopes property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setDeviceScopes(String value) { + this.deviceScopes = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueue.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueue.java new file mode 100644 index 00000000000..278b9b6da9e --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueue.java @@ -0,0 +1,259 @@ +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for ControlQueue complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ControlQueue", propOrder = { + "name", + "enabled", + "controlClass", + "protocol", + "serverURL", + "port", + "username", + "password" +}) +public class ControlQueue { + + @XmlElement(name = "Name", required = true) + protected String name; + @XmlElement(name = "Enabled") + protected boolean enabled; + @XmlElement(name = "ControlClass", required = true) + protected String controlClass; + @XmlElement(name = "Protocol", required = true) + protected String protocol; + @XmlElement(name = "ServerURL", required = true) + protected String serverURL; + @XmlElement(name = "Port") + protected short port; + @XmlElement(name = "Username", required = true) + protected String username; + @XmlElement(name = "Password", required = true) + protected String password; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the enabled property. + * + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Sets the value of the enabled property. + * + */ + public void setEnabled(boolean value) { + this.enabled = value; + } + + /** + * Gets the value of the controlClass property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getControlClass() { + return controlClass; + } + + /** + * Sets the value of the controlClass property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setControlClass(String value) { + this.controlClass = value; + } + + /** + * Gets the value of the protocol property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getProtocol() { + return protocol; + } + + /** + * Sets the value of the protocol property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setProtocol(String value) { + this.protocol = value; + } + + /** + * Gets the value of the serverURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getServerURL() { + return serverURL; + } + + /** + * Sets the value of the serverURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setServerURL(String value) { + this.serverURL = value; + } + + /** + * Gets the value of the port property. + * + */ + public short getPort() { + return port; + } + + /** + * Sets the value of the port property. + * + */ + public void setPort(short value) { + this.port = value; + } + + /** + * Gets the value of the username property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getUsername() { + return username; + } + + /** + * Sets the value of the username property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setUsername(String value) { + this.username = value; + } + + /** + * Gets the value of the password property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPassword() { + return password; + } + + /** + * Sets the value of the password property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPassword(String value) { + this.password = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueuesConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueuesConfig.java new file mode 100644 index 00000000000..8216ac296e9 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ControlQueuesConfig.java @@ -0,0 +1,69 @@ + +package org.wso2.carbon.device.mgt.etc.config.server.datasource; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for ControlQueuesConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "ControlQueuesConfig", propOrder = { + "controlQueue" +}) +public class ControlQueuesConfig { + + @XmlElement(name = "ControlQueue") + protected List controlQueue; + + /** + * Gets the value of the controlQueue property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the controlQueue property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getControlQueue().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link ControlQueue } + * + * + */ + public List getControlQueue() { + if (controlQueue == null) { + controlQueue = new ArrayList(); + } + return this.controlQueue; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStore.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStore.java new file mode 100644 index 00000000000..3cf0caf007f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStore.java @@ -0,0 +1,231 @@ +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DataStore complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DataStore", propOrder = { + "name", + "enabled", + "publisherClass", + "serverURL", + "port", + "username", + "password" +}) +public class DataStore { + + @XmlElement(name = "Name", required = true) + protected String name; + @XmlElement(name = "Enabled") + protected boolean enabled; + @XmlElement(name = "PublisherClass", required = true) + protected String publisherClass; + @XmlElement(name = "ServerURL", required = true) + protected String serverURL; + @XmlElement(name = "Port") + protected short port; + @XmlElement(name = "Username", required = true) + protected String username; + @XmlElement(name = "Password", required = true) + protected String password; + + /** + * Gets the value of the name property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getName() { + return name; + } + + /** + * Sets the value of the name property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setName(String value) { + this.name = value; + } + + /** + * Gets the value of the enabled property. + * + */ + public boolean isEnabled() { + return enabled; + } + + /** + * Sets the value of the enabled property. + * + */ + public void setEnabled(boolean value) { + this.enabled = value; + } + + /** + * Gets the value of the publisherClass property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPublisherClass() { + return publisherClass; + } + + /** + * Sets the value of the publisherClass property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPublisherClass(String value) { + this.publisherClass = value; + } + + /** + * Gets the value of the serverURL property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getServerURL() { + return serverURL; + } + + /** + * Sets the value of the serverURL property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setServerURL(String value) { + this.serverURL = value; + } + + /** + * Gets the value of the port property. + * + */ + public short getPort() { + return port; + } + + /** + * Sets the value of the port property. + * + */ + public void setPort(short value) { + this.port = value; + } + + /** + * Gets the value of the username property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getUsername() { + return username; + } + + /** + * Sets the value of the username property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setUsername(String value) { + this.username = value; + } + + /** + * Gets the value of the password property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPassword() { + return password; + } + + /** + * Sets the value of the password property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPassword(String value) { + this.password = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStoresConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStoresConfig.java new file mode 100644 index 00000000000..b9c2e028833 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DataStoresConfig.java @@ -0,0 +1,86 @@ +/* + * 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.etc.config.server.datasource; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DataStoresConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DataStoresConfig", propOrder = { + "dataStore" +}) +public class DataStoresConfig { + + @XmlElement(name = "DataStore") + protected List dataStore; + + /** + * Gets the value of the dataStore property. + * + *

+ * This accessor method returns a reference to the live list, + * not a snapshot. Therefore any modification you make to the + * returned list will be present inside the JAXB object. + * This is why there is not a set method for the dataStore property. + * + *

+ * For example, to add a new item, do as follows: + *

+     *    getDataStore().add(newItem);
+     * 
+ * + * + *

+ * Objects of the following type(s) are allowed in the list + * {@link DataStore } + * + * + */ + public List getDataStore() { + if (dataStore == null) { + dataStore = new ArrayList(); + } + return this.dataStore; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceCloudConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceCloudConfig.java new file mode 100644 index 00000000000..f685e0dfe29 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceCloudConfig.java @@ -0,0 +1,193 @@ +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DeviceCloudConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *         
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DeviceCloudConfig", propOrder = { + "dataStores", + "controlQueues", + "security", + "apiManager", + "deviceUserValidator" +}) +@XmlRootElement(name = "DeviceCloudConfiguration") +public class DeviceCloudConfig { + + @XmlElement(name = "DataStores", required = true) + protected DataStoresConfig dataStores; + @XmlElement(name = "ControlQueues", required = true) + protected ControlQueuesConfig controlQueues; + @XmlElement(name = "Security", required = true) + protected SecurityConfig security; + @XmlElement(name = "ApiManager", required = true) + protected ApiManagerConfig apiManager; + @XmlElement(name = "DeviceUserValidator", required = true) + protected DeviceUserValidatorConfig deviceUserValidator; + + /** + * Gets the value of the dataStores property. + * + * @return + * possible object is + * {@link DataStoresConfig } + * + */ + public DataStoresConfig getDataStores() { + return dataStores; + } + + /** + * Sets the value of the dataStores property. + * + * @param value + * allowed object is + * {@link DataStoresConfig } + * + */ + public void setDataStores(DataStoresConfig value) { + this.dataStores = value; + } + + /** + * Gets the value of the controlQueues property. + * + * @return + * possible object is + * {@link ControlQueuesConfig } + * + */ + public ControlQueuesConfig getControlQueues() { + return controlQueues; + } + + /** + * Sets the value of the controlQueues property. + * + * @param value + * allowed object is + * {@link ControlQueuesConfig } + * + */ + public void setControlQueues(ControlQueuesConfig value) { + this.controlQueues = value; + } + + /** + * Gets the value of the security property. + * + * @return + * possible object is + * {@link SecurityConfig } + * + */ + public SecurityConfig getSecurity() { + return security; + } + + /** + * Sets the value of the security property. + * + * @param value + * allowed object is + * {@link SecurityConfig } + * + */ + public void setSecurity(SecurityConfig value) { + this.security = value; + } + + /** + * Gets the value of the apiManager property. + * + * @return + * possible object is + * {@link ApiManagerConfig } + * + */ + public ApiManagerConfig getApiManager() { + return apiManager; + } + + /** + * Sets the value of the apiManager property. + * + * @param value + * allowed object is + * {@link ApiManagerConfig } + * + */ + public void setApiManager(ApiManagerConfig value) { + this.apiManager = value; + } + + /** + * Gets the value of the deviceUserValidator property. + * + * @return + * possible object is + * {@link DeviceUserValidatorConfig } + * + */ + public DeviceUserValidatorConfig getDeviceUserValidator() { + return deviceUserValidator; + } + + /** + * Sets the value of the deviceUserValidator property. + * + * @param value + * allowed object is + * {@link DeviceUserValidatorConfig } + * + */ + public void setDeviceUserValidator(DeviceUserValidatorConfig value) { + this.deviceUserValidator = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceUserValidatorConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceUserValidatorConfig.java new file mode 100644 index 00000000000..2de33f66056 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/DeviceUserValidatorConfig.java @@ -0,0 +1,108 @@ + +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for DeviceUserValidatorConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "DeviceUserValidatorConfig", propOrder = { + "cacheSize", + "ttl" +}) +public class DeviceUserValidatorConfig { + + @XmlElement(name = "CacheSize", required = true) + protected int cacheSize; + @XmlElement(name = "TTL", required = true) + protected int ttl; + + /** + * Gets the value of the cacheSize property. + * + * @return + * possible object is + * {@link int } + * + */ + public int getCacheSize() { + return cacheSize; + } + + /** + * Sets the value of the cacheSize property. + * + * @param value + * allowed object is + * {@link int } + * + */ + public void setCacheSize(int value) { + this.cacheSize = value; + } + + /** + * Gets the value of the ttl property. + * + * @return + * possible object is + * {@link int } + * + */ + public int getTTL() { + return ttl; + } + + /** + * Sets the value of the ttl property. + * + * @param value + * allowed object is + * {@link int } + * + */ + public void setTTL(int value) { + this.ttl = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ObjectFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ObjectFactory.java new file mode 100644 index 00000000000..6084d9ebc7c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/ObjectFactory.java @@ -0,0 +1,116 @@ +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.annotation.XmlElementDecl; +import javax.xml.bind.annotation.XmlRegistry; +import javax.xml.namespace.QName; + + +/** + * This object contains factory methods for each + * Java content interface and Java element interface + * generated in the org.wso2.carbon.device.mgt.etc.config.server.configs package. + *

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. + */ +@XmlRegistry +public class ObjectFactory { + + private final static QName _DeviceCloudConfiguration_QNAME = new QName("", "DeviceCloudConfiguration"); + + /** + * Create a new ObjectFactory that can be used to create new instances of + * schema derived classes for package: org.wso2.carbon.device.mgt.etc.config.server.configs + */ + public ObjectFactory() { + } + + /** + * Create an instance of {@link DeviceCloudConfig } + */ + public DeviceCloudConfig createDeviceCloudConfig() { + return new DeviceCloudConfig(); + } + + /** + * Create an instance of {@link ApiManagerConfig } + */ + public ApiManagerConfig createApiManagerConfig() { + return new ApiManagerConfig(); + } + + /** + * Create an instance of {@link ControlQueuesConfig } + */ + public ControlQueuesConfig createControlQueuesConfig() { + return new ControlQueuesConfig(); + } + + /** + * Create an instance of {@link SecurityConfig } + */ + public SecurityConfig createSecurityConfig() { + return new SecurityConfig(); + } + + /** + * Create an instance of {@link ControlQueue } + */ + public ControlQueue createControlQueue() { + return new ControlQueue(); + } + + /** + * Create an instance of {@link DeviceUserValidatorConfig } + */ + public DeviceUserValidatorConfig createDeviceUserValidatorConfig() { + return new DeviceUserValidatorConfig(); + } + + /** + * Create an instance of {@link DataStore } + */ + public DataStore createDataStore() { + return new DataStore(); + } + + /** + * Create an instance of {@link DataStoresConfig } + */ + public DataStoresConfig createDataStoresConfig() { + return new DataStoresConfig(); + } + + /** + * Create an instance of {@link JAXBElement }{@code <}{@link DeviceCloudConfig }{@code >}} + */ + @XmlElementDecl(namespace = "", name = "DeviceCloudConfiguration") + public JAXBElement createDeviceCloudConfiguration(DeviceCloudConfig value) { + return new JAXBElement(_DeviceCloudConfiguration_QNAME, DeviceCloudConfig.class, null, value); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/SecurityConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/SecurityConfig.java new file mode 100644 index 00000000000..5e501a23b8c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/config/server/datasource/SecurityConfig.java @@ -0,0 +1,108 @@ + +/* + * 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.etc.config.server.datasource; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlType; + + +/** + *

Java class for SecurityConfig complex type. + * + *

The following schema fragment specifies the expected content contained within this class. + * + *

+ * 
+ *   
+ *     
+ *       
+ *         
+ *         
+ *       
+ *     
+ *   
+ * 
+ * 
+ * + * + */ +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "SecurityConfig", propOrder = { + "clientTrustStore", + "password" +}) +public class SecurityConfig { + + @XmlElement(name = "ClientTrustStore", required = true) + protected String clientTrustStore; + @XmlElement(name = "Password", required = true) + protected String password; + + /** + * Gets the value of the clientTrustStore property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getClientTrustStore() { + return clientTrustStore; + } + + /** + * Sets the value of the clientTrustStore property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setClientTrustStore(String value) { + this.clientTrustStore = value; + } + + /** + * Gets the value of the password property. + * + * @return + * possible object is + * {@link String } + * + */ + public String getPassword() { + return password; + } + + /** + * Sets the value of the password property. + * + * @param value + * allowed object is + * {@link String } + * + */ + public void setPassword(String value) { + this.password = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/ControlQueueConnector.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/ControlQueueConnector.java new file mode 100644 index 00000000000..6d4dc2fa755 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/ControlQueueConnector.java @@ -0,0 +1,53 @@ +/* + * 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.etc.controlqueue; + +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; + +import java.util.HashMap; + +/** + * The Interface ControlQueueConnector. + * + */ +public interface ControlQueueConnector { + + /** + * Initializes the control queue. + * This method loads the initial configurations relevant to the + * Control-Queue implementation + * + * @return A status message according to the outcome of the + * method execution. + */ + void initControlQueue() throws DeviceControllerException; + + /** + * Pushes the control messages received to the implemented queue + * + * @param deviceControls + * A Hash Map which contains the parameters relevant to the + * control message and the actual control message to be pushed to + * the queue + * @return A status message according to the outcome of the + * method execution. + */ + void enqueueControls(HashMap deviceControls) throws + DeviceControllerException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttConfig.java new file mode 100644 index 00000000000..02fb7f7220f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttConfig.java @@ -0,0 +1,73 @@ +/* + * 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.etc.controlqueue.mqtt; + +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue; + +public class MqttConfig { + private String mqttQueueEndpoint; + private String mqttQueueUsername; + private String mqttQueuePassword; + private boolean isEnabled; + + private static final String MQTT_QUEUE_CONFIG_NAME = "MQTT"; + + private ControlQueue mqttControlQueue; + + private static MqttConfig mqttConfig = new MqttConfig(); + + public String getMqttQueueEndpoint() { + return mqttQueueEndpoint; + } + + public String getMqttQueueUsername() { + return mqttQueueUsername; + } + + public String getMqttQueuePassword() { + return mqttQueuePassword; + } + + public ControlQueue getMqttControlQueue() { + return mqttControlQueue; + } + + public boolean isEnabled() { + return isEnabled; + } + + public static String getMqttQueueConfigName() { + return MQTT_QUEUE_CONFIG_NAME; + } + + private MqttConfig() { + mqttControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue( + MQTT_QUEUE_CONFIG_NAME); + mqttQueueEndpoint = mqttControlQueue.getServerURL() + ":" + mqttControlQueue.getPort(); + mqttQueueUsername = mqttControlQueue.getUsername(); + mqttQueuePassword = mqttControlQueue.getPassword(); + isEnabled = mqttControlQueue.isEnabled(); + } + + public static MqttConfig getInstance() { + return mqttConfig; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttControlPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttControlPublisher.java new file mode 100644 index 00000000000..bd584e48548 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttControlPublisher.java @@ -0,0 +1,162 @@ +/* + * 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.etc.controlqueue.mqtt; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; + +import java.io.File; +import java.util.HashMap; + +import static java.nio.charset.StandardCharsets.UTF_8; + + +/** + * The Class MqttControlPublisher. It is an implementation of the interface + * ControlQueueConnector. + * This implementation supports publishing of control signals received to an + * MQTT end-point. + * The configuration settings for the MQTT end-point are read from the + * 'controller.xml' file of the project. + * This is done using the class 'DefaultDeviceControlConfigs.java' which loads + * the settings from the default xml org.wso2.carbon.device.mgt.iot.common.devicecloud.org.wso2.carbon.device.mgt.iot.common.config.server.configs + * file - + * /resources/conf/device-controls/controller.xml + */ +//TODO-Make these MQTT, XMPP publishers/ subscribers into "transport" package +public class MqttControlPublisher implements ControlQueueConnector, MqttCallback { + + private static final Log log = LogFactory.getLog(MqttControlPublisher.class); + + private String mqttEndpoint; + private String mqttUsername; + private String mqttPassword; + private boolean mqttEnabled = false; + + public MqttControlPublisher() { + } + + @Override + public void initControlQueue() throws DeviceControllerException { + mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); + mqttUsername = MqttConfig.getInstance().getMqttQueueUsername(); + mqttPassword = MqttConfig.getInstance().getMqttQueuePassword(); + mqttEnabled = MqttConfig.getInstance().isEnabled(); + } + + + @Override + public void enqueueControls(HashMap deviceControls) + throws DeviceControllerException { + + if (mqttEnabled) { + MqttClient client; + MqttConnectOptions options; + + String owner = deviceControls.get("owner"); + String deviceType = deviceControls.get("deviceType"); + String deviceId = deviceControls.get("deviceId"); + String key = deviceControls.get("key"); + String value = deviceControls.get("value"); + + String clientId = owner + "." + deviceId; + + if (clientId.length() > 24) { + String errorString = + "No of characters '" + clientId.length() + "' for ClientID: '" + clientId + + "' is invalid (should be less than 24, hence please provide a " + + "simple " + + + + "'owner' tag)"; + log.error(errorString); + throw new DeviceControllerException(errorString); + } else { + log.info("No of Characters " + clientId.length() + " for ClientID : '" + clientId + + "' is acceptable"); + } + + String publishTopic = + "wso2" + File.separator + "iot" + File.separator + owner + File.separator + + deviceType + File.separator + + deviceId; + String payLoad = key + ":" + value; + + log.info("Publish-Topic: " + publishTopic); + log.info("PayLoad: " + payLoad); + + try { + client = new MqttClient(mqttEndpoint,clientId); + options = new MqttConnectOptions(); + options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true); + client.setCallback(this); + client.connect(options); + + MqttMessage message = new MqttMessage(); + message.setPayload(payLoad.getBytes(UTF_8)); + client.publish(publishTopic, payLoad.getBytes(UTF_8), 0, true); + + if (log.isDebugEnabled()) { + log.debug("MQTT Client successfully published to topic: " + publishTopic + + ", with payload - " + payLoad); + } + client.disconnect(); + } catch (MqttException ex) { + String errorMsg = + "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + + "\n\tMessage: " + + ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + + "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; + + log.error(errorMsg, ex); + throw new DeviceControllerException(errorMsg, ex); + } + } else { + log.warn("MQTT set to false in 'device-mgt-config.xml'"); + } + } + + @Override + public void connectionLost(Throwable arg0) { + log.error("Connection to MQTT Endpoint Lost"); + } + + + @Override + public void deliveryComplete(IMqttDeliveryToken topic) { + log.info("Published topic: '" + topic.getTopics()[0] + "' successfully to client: '" + + topic.getClient().getClientId() + "'"); + } + + @Override + public void messageArrived(String arg0, MqttMessage arg1) throws Exception { + log.info("MQTT Message received: " + arg1.toString()); + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttSubscriber.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttSubscriber.java new file mode 100644 index 00000000000..426b1c87919 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/mqtt/MqttSubscriber.java @@ -0,0 +1,289 @@ +/* + * 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.etc.controlqueue.mqtt; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.MqttSecurityException; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * This class contains the Agent specific implementation for all the MQTT functionality. This + * includes connecting to a MQTT Broker & subscribing to the appropriate MQTT-topic, action plan + * upon losing connection or successfully delivering a message to the broker and processing + * incoming messages. Makes use of the 'Paho-MQTT' library provided by Eclipse Org. + *

+ * It is an abstract class with an abstract method 'postMessageArrived' allowing the user to have + * their own implementation of the actions to be taken upon receiving a message to the subscribed + * MQTT-Topic. + */ +public abstract class MqttSubscriber implements MqttCallback { + private static final Log log = LogFactory.getLog(MqttSubscriber.class); + + private MqttClient client; + private String clientId; + private MqttConnectOptions options; + private String subscribeTopic; + private String clientWillTopic; + private String mqttBrokerEndPoint; + private int reConnectionInterval; + + /** + * Constructor for the MQTTClient which takes in the owner, type of the device and the MQTT + * Broker URL and the topic to subscribe. + * + * @param owner the owner of the device. + * @param deviceType the CDMF Device-Type of the device. + * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. + * @param subscribeTopic the MQTT topic to which the client is to be subscribed + */ + protected MqttSubscriber(String owner, String deviceType, String mqttBrokerEndPoint, String subscribeTopic) { + this.clientId = owner + ":" + deviceType; + this.subscribeTopic = subscribeTopic; + this.clientWillTopic = deviceType + File.separator + "disconnection"; + this.mqttBrokerEndPoint = mqttBrokerEndPoint; + this.reConnectionInterval = 5000; + this.initSubscriber(); + } + + /** + * Constructor for the MQTTClient which takes in the owner, type of the device and the MQTT + * Broker URL and the topic to subscribe. Additionally this constructor takes in the + * reconnection-time interval between successive attempts to connect to the broker. + * + * @param deviceOwner the owner of the device. + * @param deviceType the CDMF Device-Type of the device. + * @param mqttBrokerEndPoint the IP/URL of the MQTT broker endpoint. + * @param subscribeTopic the MQTT topic to which the client is to be subscribed + * @param reConnectionInterval time interval in SECONDS between successive attempts to connect + * to the broker. + */ + protected MqttSubscriber(String deviceOwner, String deviceType, String mqttBrokerEndPoint, + String subscribeTopic, int reConnectionInterval) { + this.clientId = deviceOwner + ":" + deviceType; + this.subscribeTopic = subscribeTopic; + this.clientWillTopic = deviceType + File.separator + "disconnection"; + this.mqttBrokerEndPoint = mqttBrokerEndPoint; + this.reConnectionInterval = reConnectionInterval; + this.initSubscriber(); + } + + /** + * Initializes the MQTT-Client. + * Creates a client using the given MQTT-broker endpoint and the clientId (which is + * constructed by a concatenation of [deviceOwner]:[deviceType]). Also sets the client's + * options parameter with the clientWillTopic (in-case of connection failure) and other info. + * Also sets the call-back this current class. + */ + private void initSubscriber() { + if(!MqttConfig.getInstance().isEnabled()){ + log.info("Mqtt Queue is not enabled"); + return; + } + try { + client = new MqttClient(this.mqttBrokerEndPoint, clientId, null); + log.info("MQTT subscriber was created with ClientID : " + clientId); + } catch (MqttException ex) { + String errorMsg = "MQTT Client Error\n" + "\tReason: " + ex.getReasonCode() + + "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + + ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + + "\n\tException: " + ex; + log.error(errorMsg); + } + + options = new MqttConnectOptions(); + options.setCleanSession(false); + options.setWill(clientWillTopic, "connection crashed".getBytes(StandardCharsets.UTF_8), 2, true); + client.setCallback(this); + } + + /** + * Checks whether the connection to the MQTT-Broker persists. + * + * @return true if the client is connected to the MQTT-Broker, else false. + */ + public boolean isConnected() { + return client.isConnected(); + } + + /** + * Connects to the MQTT-Broker and if successfully established connection, then tries to + * subscribe to the MQTT-Topic specific to the device. (The MQTT-Topic specific to the + * device is created is taken in as a constructor parameter of this class) . + * + * @throws DeviceManagementException in the event of 'Connecting to' or 'Subscribing to' the + * MQTT broker fails. + */ + public void connectAndSubscribe() throws DeviceManagementException { + if(!MqttConfig.getInstance().isEnabled()){ + log.info("Mqtt Queue is not enabled"); + return; + } + + try { + client.connect(options); + + if (log.isDebugEnabled()) { + log.debug("Subscriber connected to queue at: " + this.mqttBrokerEndPoint); + } + } catch (MqttSecurityException ex) { + String errorMsg = "MQTT Security Exception when connecting to queue\n" + "\tReason: " + + ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + + "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + + ex.getCause() + "\n\tException: " + ex; //throw + if (log.isDebugEnabled()) { + log.debug(errorMsg); + } + throw new DeviceManagementException(errorMsg, ex); + + } catch (MqttException ex) { + String errorMsg = "MQTT Exception when connecting to queue\n" + "\tReason: " + + ex.getReasonCode() + "\n\tMessage: " + ex.getMessage() + + "\n\tLocalMsg: " + ex.getLocalizedMessage() + "\n\tCause: " + + ex.getCause() + "\n\tException: " + ex; //throw + if (log.isDebugEnabled()) { + log.debug(errorMsg); + } + throw new DeviceManagementException(errorMsg, ex); + } + + try { + client.subscribe(subscribeTopic, 0); + + log.info("Subscribed with client id: " + clientId); + log.info("Subscribed to topic: " + subscribeTopic); + } catch (MqttException ex) { + String errorMsg = "MQTT Exception when trying to subscribe to topic: " + + subscribeTopic + "\n\tReason: " + ex.getReasonCode() + + "\n\tMessage: " + ex.getMessage() + "\n\tLocalMsg: " + + ex.getLocalizedMessage() + "\n\tCause: " + ex.getCause() + + "\n\tException: " + ex; + if (log.isDebugEnabled()) { + log.debug(errorMsg); + } + throw new DeviceManagementException(errorMsg, ex); + } + } + + /** + * Callback method which is triggered once the MQTT client losers its connection to the broker. + * A scheduler thread is spawned to continuously re-attempt and connect to the broker and + * subscribe to the device's topic. This thread is scheduled to execute after every break + * equal to that of the 'reConnectionInterval' of the MQTTClient. + * + * @param throwable a Throwable Object containing the details as to why the failure occurred. + */ + @Override + public void connectionLost(Throwable throwable) { + log.warn("Lost Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint + ".\nThis was due to - " + throwable.getMessage()); + + Runnable reSubscriber = new Runnable() { + @Override + public void run() { + if (!isConnected()) { + if (log.isDebugEnabled()) { + log.debug("Subscriber reconnecting to queue........"); + } + try { + connectAndSubscribe(); + } catch (DeviceManagementException e) { + if (log.isDebugEnabled()) { + log.debug("Could not reconnect and subscribe to ControlQueue."); + } + } + } else { + return; + } + } + }; + + ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); + service.scheduleAtFixedRate(reSubscriber, 0, this.reConnectionInterval, TimeUnit.SECONDS); + } + + /** + * Callback method which is triggered upon receiving a MQTT Message from the broker. Spawns a + * new thread that executes any actions to be taken with the received message. + * + * @param topic the MQTT-Topic to which the received message was published to and the + * client was subscribed to. + * @param mqttMessage the actual MQTT-Message that was received from the broker. + */ + @Override + public void messageArrived(final String topic, final MqttMessage mqttMessage) { + Thread subscriberThread = new Thread() { + public void run() { + postMessageArrived(topic, mqttMessage); + } + }; + subscriberThread.start(); + } + + /** + * Callback method which gets triggered upon successful completion of a message delivery to + * the broker. + * + * @param iMqttDeliveryToken the MQTT-DeliveryToken which includes the details about the + * specific message delivery. + */ + public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) { + String message = ""; + try { + message = iMqttDeliveryToken.getMessage().toString(); + } catch (MqttException e) { + log.error("Error occurred whilst trying to read the message from the MQTT delivery token."); + } + String topic = iMqttDeliveryToken.getTopics()[0]; + String client = iMqttDeliveryToken.getClient().getClientId(); + log.info("Message - '" + message + "' of client [" + client + "] for the topic (" + topic + ") was delivered successfully."); + } + + /** + * This is an abstract method used for post processing the received MQTT-message. This + * method will be implemented as per requirement at the time of creating an object of this + * class. + * + * @param topic The topic for which the message was received for. + * @param message The message received for the subscription to the above topic. + */ + protected abstract void postMessageArrived(String topic, MqttMessage message); + + /** + * Gets the MQTTClient object. + * + * @return the MQTTClient object. + */ + public MqttClient getClient() { + return client; +} + +} + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppAccount.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppAccount.java new file mode 100644 index 00000000000..66b6fc97491 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppAccount.java @@ -0,0 +1,59 @@ +/* + * 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.etc.controlqueue.xmpp; + +public class XmppAccount { + private String username; + private String password; + private String accountName; + private String email; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConfig.java new file mode 100644 index 00000000000..a2c3fd1238d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConfig.java @@ -0,0 +1,95 @@ +/* + * 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.etc.controlqueue.xmpp; + +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; + +public class XmppConfig { + private String xmppServerIP; + private int xmppServerPort; + private String xmppEndpoint; + private String xmppUsername; + private String xmppPassword; + private boolean isEnabled; + + private static final String XMPP_QUEUE_CONFIG_NAME = "XMPP"; + private final int SERVER_CONNECTION_PORT = 5222; + + private ControlQueue xmppControlQueue; + + private static XmppConfig xmppConfig = new XmppConfig(); + + public String getXmppServerIP() { + return xmppServerIP; + } + + public int getXmppServerPort() { + return xmppServerPort; + } + + public String getXmppEndpoint() { + return xmppEndpoint; + } + + public String getXmppUsername() { + return xmppUsername; + } + + public String getXmppPassword() { + return xmppPassword; + } + + public ControlQueue getXmppControlQueue() { + return xmppControlQueue; + } + + public boolean isEnabled() { + return isEnabled; + } + + public static String getXmppQueueConfigName() { + return XMPP_QUEUE_CONFIG_NAME; + } + + private XmppConfig() { + xmppControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue( + XMPP_QUEUE_CONFIG_NAME); + + xmppServerIP = xmppControlQueue.getServerURL(); + int indexOfChar = xmppServerIP.lastIndexOf('/'); + if (indexOfChar != -1) { + xmppServerIP = xmppServerIP.substring((indexOfChar + 1), xmppServerIP.length()); + } + + xmppServerPort = xmppControlQueue.getPort(); + xmppEndpoint = xmppControlQueue.getServerURL() + ":" + xmppServerPort; + xmppUsername = xmppControlQueue.getUsername(); + xmppPassword = xmppControlQueue.getPassword(); + isEnabled = xmppControlQueue.isEnabled(); + } + + public static XmppConfig getInstance() { + return xmppConfig; + } + + public int getSERVER_CONNECTION_PORT() { + return SERVER_CONNECTION_PORT; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConnector.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConnector.java new file mode 100644 index 00000000000..c98f4a14422 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppConnector.java @@ -0,0 +1,303 @@ +/* + * 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.etc.controlqueue.xmpp; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jivesoftware.smack.ConnectionConfiguration; +import org.jivesoftware.smack.PacketListener; +import org.jivesoftware.smack.SmackConfiguration; +import org.jivesoftware.smack.XMPPConnection; +import org.jivesoftware.smack.XMPPException; +import org.jivesoftware.smack.filter.AndFilter; +import org.jivesoftware.smack.filter.FromContainsFilter; +import org.jivesoftware.smack.filter.OrFilter; +import org.jivesoftware.smack.filter.PacketFilter; +import org.jivesoftware.smack.filter.PacketTypeFilter; +import org.jivesoftware.smack.filter.ToContainsFilter; +import org.jivesoftware.smack.packet.Message; +import org.jivesoftware.smack.packet.Packet; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; + +/** + * This class contains the Agent specific implementation for all the XMPP functionality. This + * includes connecting to a XMPP Server & Login using the device's XMPP-Account, Setting + * listeners and filters on incoming XMPP messages and Sending XMPP replies for control signals + * received. Makes use of the 'Smack-XMPP' library provided by jivesoftware/igniterealtime. + *

+ * It is an abstract class with an abstract method 'processXMPPMessage' allowing the user to have + * their own implementation of the actions to be taken upon receiving an appropriate XMPP message. + */ +public abstract class XmppConnector { + private static final Log log = LogFactory.getLog(XmppConnector.class); + + private int replyTimeoutInterval = 500; // millis + private String server; + private int port; + private ConnectionConfiguration config; + private XMPPConnection connection; + private PacketFilter filter; + private PacketListener listener; + + /** + * Constructor for XMPPClient passing server-IP and the XMPP-port. + * + * @param server the IP of the XMPP server. + * @param port the XMPP server's port to connect to. (default - 5222) + */ + public XmppConnector(String server, int port) { + this.server = server; + this.port = port; + initXMPPClient(); + } + + /** + * Initializes the XMPP Client. + * Sets the time-out-limit whilst waiting for XMPP-replies from server. Creates the XMPP + * configurations to connect to the server and creates the XMPPConnection object used for + * connecting and Logging-In. + */ + private void initXMPPClient() { + log.info(String.format( + "Initializing connection to XMPP Server at %1$s via port %2$d......", server, + port)); + SmackConfiguration.setPacketReplyTimeout(replyTimeoutInterval); + config = new ConnectionConfiguration(server, port); +// TODO:: Need to enable SASL-Authentication appropriately + config.setSASLAuthenticationEnabled(false); + config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); + connection = new XMPPConnection(config); + } + + /** + * Connects to the XMPP-Server and if successfully established connection, then tries to Log + * in using the device's XMPP Account credentials. (The XMPP-Account specific to the device is + * created in the XMPP server whilst downloading the Agent from the IoT Server) . + * + * @param username the username of the device's XMPP-Account. + * @param password the password of the device's XMPP-Account. + * @param resource the resource the resource, specific to the XMPP-Account to which the login + * is made to + * @throws DeviceManagementException in the event of 'Connecting to' or 'Logging into' the + * XMPP server fails. + */ + public void connectAndLogin(String username, String password, String resource) + throws DeviceManagementException { + try { + connection.connect(); + log.info(String.format( + "Connection to XMPP Server at %1$s established successfully......", server)); + + } catch (XMPPException xmppExcepion) { + String errorMsg = + "Connection attempt to the XMPP Server at " + server + " via port " + port + + " failed."; + log.info(errorMsg); + throw new DeviceManagementException(errorMsg, xmppExcepion); + } + + if (connection.isConnected()) { + try { + if (resource == null) { + connection.login(username, password); + log.info(String.format("Logged into XMPP Server at %1$s as user %2$s......", + server, username)); + } else { + connection.login(username, password, resource); + log.info(String.format( + "Logged into XMPP Server at %1$s as user %2$s on resource %3$s......", + server, username, resource)); + } + } catch (XMPPException xmppException) { + String errorMsg = + "Login attempt to the XMPP Server at " + server + " with username - " + + username + " failed."; + log.info(errorMsg); + throw new DeviceManagementException(errorMsg, xmppException); + } + } + } + + /** + * Sets a filter on all the incoming XMPP-Messages for the JID (XMPP-Account ID) passed in. + * Also creates a listener for the incoming messages and connects the listener to the + * XMPPConnection alongside the set filter. + * + * @param senderJID the JID (XMPP-Account ID) to which the filter is to be set. + */ + public void setMessageFilterOnSender(String senderJID) { + filter = new AndFilter(new PacketTypeFilter(Message.class), new FromContainsFilter( + senderJID)); + listener = new PacketListener() { + @Override + public void processPacket(Packet packet) { + if (packet instanceof Message) { + final Message xmppMessage = (Message) packet; + Thread msgProcessThread = new Thread() { + public void run() { + processXMPPMessage(xmppMessage); + } + }; + msgProcessThread.start(); + } + } + }; + connection.addPacketListener(listener, filter); + } + + + public void setMessageFilterOnReceiver(String receiverJID) { + filter = new AndFilter(new PacketTypeFilter(Message.class), new ToContainsFilter( + receiverJID)); + listener = new PacketListener() { + @Override + public void processPacket(Packet packet) { + if (packet instanceof Message) { + final Message xmppMessage = (Message) packet; + Thread msgProcessThread = new Thread() { + public void run() { + processXMPPMessage(xmppMessage); + } + }; + msgProcessThread.start(); + } + } + }; + connection.addPacketListener(listener, filter); + } + + /** + * Sets a filter on all the incoming XMPP-Messages for the From-JID & To-JID (XMPP-Account IDs) + * passed in. Also creates a listener for the incoming messages and connects the listener to + * the XMPPConnection alongside the set filter. + * + * @param senderJID the From-JID (XMPP-Account ID) to which the filter is to be set. + * @param receiverJID the To-JID (XMPP-Account ID) to which the filter is to be set. + * @param andCondition if true: then filter is set with 'AND' operator (senderJID && + * receiverJID), + * if false: then the filter is set with 'OR' operator (senderJID | + * receiverJID) + */ + public void setSenderReceiverMessageFilter(String senderJID, String receiverJID, boolean + andCondition) { + PacketFilter jidFilter; + + if (andCondition) { + jidFilter = new AndFilter(new FromContainsFilter(senderJID), new ToContainsFilter( + receiverJID)); + } else { + jidFilter = new OrFilter(new FromContainsFilter(senderJID), new ToContainsFilter( + receiverJID)); + } + + filter = new AndFilter(new PacketTypeFilter(Message.class), jidFilter); + listener = new PacketListener() { + @Override + public void processPacket(Packet packet) { + if (packet instanceof Message) { + final Message xmppMessage = (Message) packet; + Thread msgProcessThread = new Thread() { + public void run() { + processXMPPMessage(xmppMessage); + } + }; + msgProcessThread.start(); + } + } + }; + connection.addPacketListener(listener, filter); + } + + /** + * Sends an XMPP message + * + * @param JID the JID (XMPP Account ID) to which the message is to be sent to. + * @param message the XMPP-Message that is to be sent. + */ + public void sendXMPPMessage(String JID, String message) { + sendXMPPMessage(JID, message, "Reply-From-Device"); + if (log.isDebugEnabled()) { + log.debug("Message: " + message + " to XMPP JID [" + JID + "] sent successfully"); + } + } + + /** + * Overloaded method to send an XMPP message. Includes the subject to be mentioned in the + * message that is sent. + * + * @param JID the JID (XMPP Account ID) to which the message is to be sent to. + * @param message the XMPP-Message that is to be sent. + * @param subject the subject that the XMPP-Message would carry. + */ + public void sendXMPPMessage(String JID, String message, String subject) { + Message xmppMessage = new Message(); + xmppMessage.setTo(JID); + xmppMessage.setSubject(subject); + xmppMessage.setBody(message); + xmppMessage.setType(Message.Type.chat); + connection.sendPacket(xmppMessage); + } + + /** + * Checks whether the connection to the XMPP-Server persists. + * + * @return true if the client is connected to the XMPP-Server, else false. + */ + public boolean isConnected() { + return connection.isConnected(); + } + + /** + * Sets the client's time-out-limit whilst waiting for XMPP-replies from server. + * + * @param millis the time in millis to be set as the time-out-limit whilst waiting for a + * XMPP-reply. + */ + public void setReplyTimeoutInterval(int millis) { + this.replyTimeoutInterval = millis; + } + + /** + * Disables default debugger provided by the XMPPConnection. + */ + public void disableDebugger() { + connection.DEBUG_ENABLED = false; + } + + /** + * Closes the connection to the XMPP Server. + */ + public void closeConnection() { + if (connection != null && connection.isConnected()) { + connection.disconnect(); + } + } + + /** + * This is an abstract method used for post processing the received XMPP-message. This + * method will be implemented as per requirement at the time of creating an object of this + * class. + * + * @param xmppMessage the xmpp message received by the listener. + */ + protected abstract void processXMPPMessage(Message xmppMessage); + +} + + diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppServerClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppServerClient.java new file mode 100644 index 00000000000..5b2955a199b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/controlqueue/xmpp/XmppServerClient.java @@ -0,0 +1,160 @@ +/* + * 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.etc.controlqueue.xmpp; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.device.mgt.etc.controlqueue.ControlQueueConnector; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException; +import org.wso2.carbon.device.mgt.etc.util.IoTUtil; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; + +public class XmppServerClient implements ControlQueueConnector { + + private static final Log log = LogFactory.getLog(XmppServerClient.class); + + private static final String XMPP_SERVER_API_CONTEXT = "/plugins/restapi/v1"; + private static final String USERS_API = "/users"; + private static final String GROUPS_API = "/groups"; + private static final String APPLICATION_JSON_MT = "application/json"; + + private String xmppEndpoint; + private String xmppUsername; + private String xmppPassword; + private boolean xmppEnabled = false; + + public XmppServerClient() { + } + + @Override + public void initControlQueue() throws DeviceControllerException { + xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint(); + xmppUsername = XmppConfig.getInstance().getXmppUsername(); + xmppPassword = XmppConfig.getInstance().getXmppPassword(); + xmppEnabled = XmppConfig.getInstance().isEnabled(); + } + + @Override + public void enqueueControls(HashMap deviceControls) + throws DeviceControllerException { + if (!xmppEnabled) { + log.warn("XMPP set to false in 'device-mgt-config.xml'"); + } + } + + public boolean createXMPPAccount(XmppAccount newUserAccount) throws DeviceControllerException { + if (xmppEnabled) { + String xmppUsersAPIEndpoint = xmppEndpoint + XMPP_SERVER_API_CONTEXT + USERS_API; + if (log.isDebugEnabled()) { + log.debug("The API Endpoint URL of the XMPP Server is set to: " + + xmppUsersAPIEndpoint); + } + + String encodedString = xmppUsername + ":" + xmppPassword; + encodedString = new String(Base64.encodeBase64(encodedString.getBytes(StandardCharsets.UTF_8))); + String authorizationHeader = "Basic " + encodedString; + String jsonRequest ="{\n" + + " \"username\": \""+newUserAccount.getUsername()+"\"," + + " \"password\": \""+newUserAccount.getPassword()+"\"," + + " \"name\": \""+newUserAccount.getAccountName()+"\"," + + " \"email\": \""+newUserAccount.getEmail()+"\"," + + " \"properties\": {" + + " \"property\": [" + + " {" + + " \"@key\": \"console.rows_per_page\"," + + " \"@value\": \"user-summary=8\"" + + " }," + + " {" + + " \"@key\": \"console.order\"," + + " \"@value\": \"session-summary=1\"" + + " }" + + " ]" + + " }" + + "}"; + StringEntity requestEntity; + try { + requestEntity = new StringEntity(jsonRequest,"application/json","UTF-8"); + } catch (UnsupportedEncodingException e) { + return false; + } + + URL xmppUserApiUrl; + try { + xmppUserApiUrl = new URL(xmppUsersAPIEndpoint); + } catch (MalformedURLException e) { + String errMsg = "Malformed URL + " + xmppUsersAPIEndpoint; + log.error(errMsg); + throw new DeviceControllerException(errMsg); + } + HttpClient httpClient; + try { + httpClient = IoTUtil.getHttpClient(xmppUserApiUrl.getPort(), xmppUserApiUrl.getProtocol()); + } catch (Exception e) { + log.error("Error on getting a http client for port :" + xmppUserApiUrl.getPort() + " protocol :" + + xmppUserApiUrl.getProtocol()); + return false; + } + HttpPost httpPost = new HttpPost(xmppUsersAPIEndpoint); + + httpPost.addHeader(HttpHeaders.AUTHORIZATION, authorizationHeader); + httpPost.setEntity(requestEntity); + + + + try { + HttpResponse httpResponse = httpClient.execute(httpPost); + + if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) { + String response = IoTUtil.getResponseString(httpResponse); + String errorMsg = "XMPP Server returned status: '" + httpResponse.getStatusLine().getStatusCode() + + "' for account creation with error:\n" + response; + log.error(errorMsg); + throw new DeviceControllerException(errorMsg); + } else { + EntityUtils.consume(httpResponse.getEntity()); + return true; + } + } catch (IOException | DeviceMgtCommonsException e) { + String errorMsg = + "Error occurred whilst trying a 'POST' at : " + xmppUsersAPIEndpoint + " error: " + e.getMessage(); + log.error(errorMsg); + throw new DeviceControllerException(errorMsg, e); + } + + } else { + log.warn("XMPP set to false in 'device-mgt-config.xml'"); + return false; + } + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/DataStoreConnector.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/DataStoreConnector.java new file mode 100644 index 00000000000..5b86a9ca798 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/DataStoreConnector.java @@ -0,0 +1,55 @@ +/* + * 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.etc.datastore; + +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; + +import java.util.HashMap; + +/** + * The Interface DataStoreConnector. + * + */ +public interface DataStoreConnector { + + /** + * Initializes the data store. + * This method loads the initial configurations relevant to the + * Data-Store implementation where the sensor data will pushed into + * + * @return A status message according to the outcome of the + * method execution. + */ + void initDataStore(DataStore config) throws DeviceControllerException; + + /** + * Pushes the device/sensor data received from the devices into the + * implemented data-store + * + * @param deviceData + * A Hash Map which contains the parameters relevant to the + * device and the actual device-data to be pushed into + * the datastore + * @return A status message according to the outcome of the + * method execution. + */ + void publishDeviceData(HashMap deviceData) + throws DeviceControllerException; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/DataStreamDefinitions.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/DataStreamDefinitions.java new file mode 100644 index 00000000000..005e54210d6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/DataStreamDefinitions.java @@ -0,0 +1,125 @@ +/* + * 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.etc.datastore.impl; + +public class DataStreamDefinitions { + + public final class StreamTypeLabel { + + public static final String TEMPERATURE = "TEMPERATURE"; + public static final String FAN = "FAN"; + public static final String BULB = "BULB"; + public static final String SONAR = "SONAR"; + public static final String LIGHT = "LIGHT"; + public static final String MOTION = "MOTION"; + + } + + public final static String TEMPERATURE_STREAM_DEFINITION = + "{" + " 'name':'org.wso2.iot.devices.temperature'," + " 'version':'1.0.0'," + + " 'nickName': 'Temperature Data'," + + " 'description': 'Temperature data received from the Device'," + + " 'tags': ['iot', 'temperature']," + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'temperature','type':'STRING'}" + + " ]" + "}"; + + public final static String BULB_STREAM_DEFINITION = + "{" + " 'name':'org_wso2_iot_devices_bulb'," + " 'version':'1.0.0'," + + " 'nickName': 'Bulb Status'," + + " 'description': 'State of the bulb attached to a Device'," + + " 'tags': ['iot', 'bulb']," + + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'status','type':'STRING'}" + + " ]" + "}"; + + public final static String FAN_STREAM_DEFINITION = + "{" + " 'name':'org_wso2_iot_devices_fan'," + " 'version':'1.0.0'," + + " 'nickName': 'Fan Status'," + + " 'description': 'State of the Fan attached to a Device'," + + " 'tags': ['iot', 'fan']," + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'status','type':'STRING'}" + + " ]" + "}"; + + public final static String MOTION_STREAM_DEFINITION = + "{" + " 'name':'org_wso2_iot_devices_motion'," + " 'version':'1.0.0'," + + " 'nickName': 'Motion Data'," + + " 'description': 'Motion data received from the Device'," + + " 'tags': ['iot', 'motion']," + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'motion','type':'STRING'}" + + " ]" + "}"; + + public final static String SONAR_STREAM_DEFINITION = + "{" + " 'name':'org_wso2_iot_devices_sonar'," + " 'version':'1.0.0'," + + " 'nickName': 'Sonar Data'," + + " 'description': 'Sonar data received from the Device'," + + " 'tags': ['iot', 'sonar']," + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'sonar','type':'STRING'}" + + " ]" + "}"; + + public final static String LIGHT_STREAM_DEFINITION = + "{" + " 'name':'org_wso2_iot_devices_light'," + " 'version':'1.0.0'," + + " 'nickName': 'Light Data'," + + " 'description': 'Light data received from the Device'," + + " 'tags': ['iot', 'light']," + " 'metaData': [" + + " {'name':'owner','type':'STRING'}," + + " {'name':'deviceType','type':'STRING'}," + + " {'name':'deviceId','type':'STRING'}," + + " {'name':'time','type':'LONG'}" + " " + + "]," + + " " + + " 'payloadData': [" + + " {'name':'light','type':'STRING'}" + + " ]" + "}"; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/ThriftDataStoreConnector.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/ThriftDataStoreConnector.java new file mode 100644 index 00000000000..6c409ebabc0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/datastore/impl/ThriftDataStoreConnector.java @@ -0,0 +1,192 @@ +/* + * 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.etc.datastore.impl; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.databridge.agent.DataPublisher; +import org.wso2.carbon.databridge.agent.exception.DataEndpointAgentConfigurationException; +import org.wso2.carbon.databridge.agent.exception.DataEndpointAuthenticationException; +import org.wso2.carbon.databridge.agent.exception.DataEndpointConfigurationException; +import org.wso2.carbon.databridge.agent.exception.DataEndpointException; +import org.wso2.carbon.databridge.commons.exception.AuthenticationException; +import org.wso2.carbon.databridge.commons.exception.DifferentStreamDefinitionAlreadyDefinedException; +import org.wso2.carbon.databridge.commons.exception.MalformedStreamDefinitionException; +import org.wso2.carbon.databridge.commons.exception.SessionTimeoutException; +import org.wso2.carbon.databridge.commons.exception.TransportException; +import org.wso2.carbon.databridge.core.DataBridgeReceiverService; +import org.wso2.carbon.device.mgt.etc.config.server.datasource.DataStore; +import org.wso2.carbon.device.mgt.etc.datastore.DataStoreConnector; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.etc.internal.DeviceMgtCommonDataHolder; + +import java.util.HashMap; + +public class ThriftDataStoreConnector implements DataStoreConnector { + + private static final Log log = LogFactory.getLog(ThriftDataStoreConnector.class); + + private String dataStoreEndpoint; + private String dataStoreUsername; + private String dataStorePassword; + private boolean enabled = false; + + @Override + public void initDataStore(DataStore config) throws DeviceControllerException { + dataStoreEndpoint = config.getServerURL() + ":" + config.getPort(); + dataStoreUsername = config.getUsername(); + dataStorePassword = config.getPassword(); + enabled = config.isEnabled(); + } + + private DataPublisher getDataPublisher() throws DeviceControllerException { + + try { + DataPublisher dataPublisher = new DataPublisher(dataStoreEndpoint, dataStoreUsername, + dataStorePassword); + if (log.isDebugEnabled()) { + log.info("data publisher created for endpoint " + dataStoreEndpoint); + } + return dataPublisher; + } catch (DataEndpointAuthenticationException | DataEndpointAgentConfigurationException | DataEndpointException + | DataEndpointConfigurationException | TransportException e) { + String error = "Error creating data publisher for endpoint: " + dataStoreEndpoint + + "with credentials, username-" + dataStoreUsername + " and password-" + + dataStorePassword + ": "; + log.error(error); + throw new DeviceControllerException(error); + } + } + + @Override + public void publishDeviceData(HashMap deviceData) throws + DeviceControllerException { + //TODO: Create a threadpool and publish the Data or use a queue and publish to it and + // have a data retreiver. + DataPublisher dataPublisher = getDataPublisher(); + if (!enabled || dataPublisher == null) { + throw new DeviceControllerException(); + } + + String owner = deviceData.get("owner"); + String deviceType = deviceData.get("deviceType"); + String deviceId = deviceData.get("deviceId"); + String time = deviceData.get("time"); + String key = deviceData.get("key"); + String value = deviceData.get("value"); + String description = deviceData.get("description"); + String deviceDataStream = null; + String sessionId; + + DataBridgeReceiverService dataBridgeReceiverService = DeviceMgtCommonDataHolder.getDataBridgeReceiverService(); + try { + //TODO: read from configuration + sessionId = dataBridgeReceiverService.login("admin", "admin"); + } catch (AuthenticationException e) { + String error = "Error in login in to data publisher"; + log.error(error); + throw new DeviceControllerException(error, e); + } + try { + //TODO: read from configuration + switch (description) { + case DataStreamDefinitions.StreamTypeLabel.TEMPERATURE: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Temperature"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, DataStreamDefinitions.TEMPERATURE_STREAM_DEFINITION); + + break; + case DataStreamDefinitions.StreamTypeLabel.MOTION: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Motion (PIR)"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, + DataStreamDefinitions.MOTION_STREAM_DEFINITION); + break; + case DataStreamDefinitions.StreamTypeLabel.SONAR: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Sonar"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, + DataStreamDefinitions.SONAR_STREAM_DEFINITION); + break; + case DataStreamDefinitions.StreamTypeLabel.LIGHT: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Light"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, + DataStreamDefinitions.LIGHT_STREAM_DEFINITION); + break; + case DataStreamDefinitions.StreamTypeLabel.BULB: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Bulb Status"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, + DataStreamDefinitions.BULB_STREAM_DEFINITION); + break; + case DataStreamDefinitions.StreamTypeLabel.FAN: + if (log.isDebugEnabled()) { + log.debug("Stream definition set to Fan Status"); + } + deviceDataStream = dataBridgeReceiverService.defineStream(sessionId, + DataStreamDefinitions.FAN_STREAM_DEFINITION); + break; + default: + break; + } + } catch (MalformedStreamDefinitionException | DifferentStreamDefinitionAlreadyDefinedException | SessionTimeoutException e) { + String error = "Error in defining streams for data publisher"; + log.error(error); + throw new DeviceControllerException(error, e); + } + + if (log.isDebugEnabled()) { + log.debug("Publishing data"); + } + dataPublisher.publish(deviceDataStream, System.currentTimeMillis(), + new Object[]{owner, deviceType, deviceId, Long.parseLong( + time)}, null, + new Object[]{value}); + + if (log.isDebugEnabled()) { + String logMsg = "event published to devicePinDataStream\n" + "\tOwner: " + owner + + "\tDeviceType: " + deviceType + "\n" + "\tDeviceId: " + deviceId + + "\tTime: " + + time + "\n" + "\tDescription: " + description + "\n" + "\tKey: " + key + + "\tValue: " + value + "\n"; + log.info(logMsg); + } + + try { + dataBridgeReceiverService.logout(sessionId); + } catch (Exception e) { + String error = "Error in login out from DataBridge Receiver Service"; + log.error(error); + throw new DeviceControllerException(error, e); + } + } + + public final class DataStoreConstants { + public final static String BAM = "WSO2-BAM"; + public final static String CEP = "WSO2-CEP"; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/AccessTokenException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/AccessTokenException.java new file mode 100644 index 00000000000..814733f8089 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/AccessTokenException.java @@ -0,0 +1,41 @@ +/* + * 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.etc.exception; + + +public class AccessTokenException extends Exception { + + + public AccessTokenException(String message) { + super(message); + } + + public AccessTokenException(String message, Throwable cause) { + super(message, cause); + } + + public AccessTokenException(Throwable cause) { + super(cause); + } + + public AccessTokenException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceControllerException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceControllerException.java new file mode 100644 index 00000000000..41eaf5f5bdc --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceControllerException.java @@ -0,0 +1,42 @@ +/* + * 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.etc.exception; + +public class DeviceControllerException extends Exception{ + + public DeviceControllerException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public DeviceControllerException(Throwable cause) { + super(cause); + } + + public DeviceControllerException(String message, Throwable cause) { + super(message, cause); + } + + public DeviceControllerException(String message) { + super(message); + } + + public DeviceControllerException() { + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceMgtCommonsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceMgtCommonsException.java new file mode 100644 index 00000000000..36db714c6ef --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/DeviceMgtCommonsException.java @@ -0,0 +1,42 @@ +/* + * 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.etc.exception; + +public class DeviceMgtCommonsException extends Exception { + public DeviceMgtCommonsException() { + super(); + } + + public DeviceMgtCommonsException(String message) { + super(message); + } + + public DeviceMgtCommonsException(String message, Throwable cause) { + super(message, cause); + } + + public DeviceMgtCommonsException(Throwable cause) { + super(cause); + } + + protected DeviceMgtCommonsException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/NotImplementedException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/NotImplementedException.java new file mode 100644 index 00000000000..79299f960a1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/NotImplementedException.java @@ -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.etc.exception; + +public class NotImplementedException extends RuntimeException { + + public NotImplementedException() { + super(); + } + + public NotImplementedException(String message) { + super(message); + } + + public NotImplementedException(String message, Throwable cause) { + super(message, cause); + } + + public NotImplementedException(Throwable cause) { + super(cause); + } + + protected NotImplementedException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/UnauthorizedException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/UnauthorizedException.java new file mode 100644 index 00000000000..5d18ad5e7b6 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/exception/UnauthorizedException.java @@ -0,0 +1,42 @@ +/* + * 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.etc.exception; + + +public class UnauthorizedException extends Exception{ + + + + public UnauthorizedException(String message) { + super(message); + } + + public UnauthorizedException(String message, Throwable cause) { + super(message, cause); + } + + public UnauthorizedException(Throwable cause) { + super(cause); + } + + public UnauthorizedException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceManagementServiceComponent.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceManagementServiceComponent.java new file mode 100644 index 00000000000..5b861a15de0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceManagementServiceComponent.java @@ -0,0 +1,225 @@ +/* + * 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.etc.internal; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.databridge.core.DataBridgeReceiverService; +import org.wso2.carbon.device.mgt.etc.DeviceController; +import org.wso2.carbon.device.mgt.etc.UserManagement; +import org.wso2.carbon.device.mgt.etc.statistics.DeviceMgtEventsStatisticsClient; +import org.wso2.carbon.device.mgt.etc.statistics.DeviceMgtUsageStatisticsClient; +import org.wso2.carbon.device.mgt.etc.config.devicetype.DeviceTypeConfigurationManager; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.device.mgt.etc.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.etc.service.DeviceTypeServiceImpl; +import org.wso2.carbon.device.mgt.etc.startup.StartupUrlPrinter; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dao.DeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dao.util.DeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.exception.DeviceMgtPluginException; +import org.wso2.carbon.ndatasource.core.DataSourceService; +import org.wso2.carbon.user.core.service.RealmService; +import org.wso2.carbon.utils.ConfigurationContextService; + +import java.util.Map; + +/** + * @scr.component name="org.wso2.carbon.device.mgt.common.DeviceManagementServiceComponent" + * immediate="true" + * @scr.reference name="user.realmservice.default" + * interface="org.wso2.carbon.user.core.service.RealmService" + * cardinality="1..1" + * policy="dynamic" + * bind="setRealmService" + * unbind="unsetRealmService" + * @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="config.context.service" + * interface="org.wso2.carbon.utils.ConfigurationContextService" + * cardinality="0..1" + * policy="dynamic" + * bind="setConfigurationContextService" + * unbind="unsetConfigurationContextService" + * @scr.reference name="databridge.component" + * interface="org.wso2.carbon.databridge.core.DataBridgeReceiverService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDataBridgeReceiverService" + * unbind="unsetDataBridgeReceiverService" + */ +public class DeviceManagementServiceComponent { + + private static final Log log = LogFactory.getLog(DeviceManagementServiceComponent.class); + public static ConfigurationContextService configurationContextService; + + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Iot Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); /* Initialize the data source configuration */ + DeviceCloudConfigManager.getInstance().initConfig(); + DeviceTypeConfigurationManager.getInstance().initConfig(); + Map dsConfigMap = + DeviceTypeConfigurationManager.getInstance().getDeviceTypeConfigMap(); + + DeviceManagementDAOFactory.init(dsConfigMap); + + 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 { + for (String pluginType : dsConfigMap.keySet()) { + DeviceManagementDAOUtil + .setupDeviceManagementSchema( + DeviceManagementDAOFactory.getDataSourceMap + ().get(pluginType)); + } + } catch (DeviceMgtPluginException e) { + log.error( + "Exception occurred while initializing device management database schema", + e); + } + } + + DeviceMgtCommonDataHolder.getInstance().initialize(); + + //TODO: handle + + DeviceController.init(); + DeviceMgtUsageStatisticsClient.initializeDataSource(); + DeviceMgtEventsStatisticsClient.initializeDataSource(); + UserManagement.registerApiAccessRoles(); + + + bundleContext.registerService(DeviceTypeService.class.getName(), + new DeviceTypeServiceImpl(), null); + + if (log.isDebugEnabled()) { + log.debug("Iot Device Management Service Component has been successfully activated"); + } + + bundleContext.registerService(ServerStartupObserver.class, new StartupUrlPrinter(), null); + } catch (Throwable e) { + log.error("Error occurred while activating Iot Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Iot Device Management Service Component"); + } + + } + + protected void setDataSourceService(DataSourceService dataSourceService) { + /* This is to avoid iot device management component getting initialized before the + underlying datasources + are registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to mobile service component"); + } + } + + protected void unsetDataSourceService(DataSourceService dataSourceService) { + //do nothing + } + + protected void setConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Setting ConfigurationContextService"); + } + + DeviceManagementServiceComponent.configurationContextService = configurationContextService; + + } + + protected void unsetConfigurationContextService( + ConfigurationContextService configurationContextService) { + if (log.isDebugEnabled()) { + log.debug("Un-setting ConfigurationContextService"); + } + DeviceManagementServiceComponent.configurationContextService = null; + } + + /** + * Sets Realm Service + * + * @param realmService associated realm service reference + */ + protected void setRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Setting Realm Service"); + + } + UserManagement.setRealmService(realmService); + + } + + /** + * Unsets Realm Service + * + * @param realmService associated realm service reference + */ + protected void unsetRealmService(RealmService realmService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting Realm Service"); + } + UserManagement.setRealmService(realmService); + } + + /** + * Sets DataBridge Receiver Service + * + * @param dataBridgeReceiverService associated DataBridge service reference + */ + protected void setDataBridgeReceiverService( + DataBridgeReceiverService dataBridgeReceiverService) { + if (log.isDebugEnabled()) { + log.debug("Setting DataBridge Receiver Service"); + } + DeviceMgtCommonDataHolder.setDataBridgeReceiverService(dataBridgeReceiverService); + } + + /** + * Unsets Realm Service + * + * @param dataBridgeReceiverService associated DataBridge service reference + */ + protected void unsetDataBridgeReceiverService( + DataBridgeReceiverService dataBridgeReceiverService) { + if (log.isDebugEnabled()) { + log.debug("Unsetting DataBridge Receiver Service"); + } + DeviceMgtCommonDataHolder.setDataBridgeReceiverService(null); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceMgtCommonDataHolder.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceMgtCommonDataHolder.java new file mode 100644 index 00000000000..95d2251948b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/internal/DeviceMgtCommonDataHolder.java @@ -0,0 +1,63 @@ +/* + * 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.etc.internal; + +import org.wso2.carbon.base.ServerConfiguration; +import org.wso2.carbon.databridge.core.DataBridgeReceiverService; + +public class DeviceMgtCommonDataHolder { + + private static DeviceMgtCommonDataHolder thisInstance = new DeviceMgtCommonDataHolder(); + private String trustStoreLocaiton; + private String trustStorePassword; + + private static DataBridgeReceiverService dataBridgeReceiverService; + + private DeviceMgtCommonDataHolder() {} + + public void initialize(){ + setTrustStore(); + } + + public static DeviceMgtCommonDataHolder getInstance() { + return thisInstance; + } + + private void setTrustStore(){ + this.trustStoreLocaiton = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Location"); + this.trustStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Password"); + } + + public String getTrustStoreLocation(){ + return trustStoreLocaiton; + } + + public String getTrustStorePassword(){ + return trustStorePassword; + } + + public static DataBridgeReceiverService getDataBridgeReceiverService() { + return dataBridgeReceiverService; + } + + public static void setDataBridgeReceiverService( + DataBridgeReceiverService dataBridgeReceiverService) { + DeviceMgtCommonDataHolder.dataBridgeReceiverService = dataBridgeReceiverService; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttConfig.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttConfig.java new file mode 100644 index 00000000000..fdd6028126b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttConfig.java @@ -0,0 +1,73 @@ +/* + * 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.etc.mqtt; + +import org.wso2.carbon.device.mgt.etc.config.server.datasource.ControlQueue; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; + +public class MqttConfig { + private String mqttQueueEndpoint; + private String mqttQueueUsername; + private String mqttQueuePassword; + private boolean isEnabled; + + private static final String MQTT_QUEUE_CONFIG_NAME = "MQTT"; + + private ControlQueue mqttControlQueue; + + private static MqttConfig mqttConfig = new MqttConfig(); + + public String getMqttQueueEndpoint() { + return mqttQueueEndpoint; + } + + public String getMqttQueueUsername() { + return mqttQueueUsername; + } + + public String getMqttQueuePassword() { + return mqttQueuePassword; + } + + public ControlQueue getMqttControlQueue() { + return mqttControlQueue; + } + + public boolean isEnabled() { + return isEnabled; + } + + public static String getMqttQueueConfigName() { + return MQTT_QUEUE_CONFIG_NAME; + } + + private MqttConfig() { + mqttControlQueue = DeviceCloudConfigManager.getInstance().getControlQueue( + MQTT_QUEUE_CONFIG_NAME); + mqttQueueEndpoint = mqttControlQueue.getServerURL() + ":" + mqttControlQueue.getPort(); + mqttQueueUsername = mqttControlQueue.getUsername(); + mqttQueuePassword = mqttControlQueue.getPassword(); + isEnabled = mqttControlQueue.isEnabled(); + } + + public static MqttConfig getInstance() { + return mqttConfig; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttPublisher.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttPublisher.java new file mode 100644 index 00000000000..f033e01dc4d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/mqtt/MqttPublisher.java @@ -0,0 +1,128 @@ +/* + * 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.etc.mqtt; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.paho.client.mqttv3.*; +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; + +import static java.nio.charset.StandardCharsets.UTF_8; + +/** + * The Class MqttControlPublisher. It is an implementation of the interface + * ControlQueueConnector. + * This implementation supports publishing of control signals received to an + * MQTT end-point. + * The configuration settings for the MQTT end-point are read from the + * 'device-mgt-config.xml' file of the project. + * This is done using the class 'DeviceCloudConfigManager.java' which loads + * the settings from the default xml org.wso2.carbon.device.mgt.common + * file - + * /resources/conf/device-mgt-config.xml + */ +public class MqttPublisher implements MqttCallback { + + private static final Log log = LogFactory.getLog(MqttPublisher.class); + + private String mqttEndpoint; + private String mqttUsername; + private String mqttPassword; + private boolean mqttEnabled = false; + + public MqttPublisher() { + } + + public void initControlQueue() throws DeviceControllerException { + mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); + mqttUsername = MqttConfig.getInstance().getMqttQueueUsername(); + mqttPassword = MqttConfig.getInstance().getMqttQueuePassword(); + mqttEnabled = MqttConfig.getInstance().isEnabled(); + } + + public void publish(String publishClientId, String publishTopic, byte[] payload) + throws DeviceControllerException { + + if (mqttEnabled) { + MqttClient client; + MqttConnectOptions options; + + if (publishClientId.length() > 24) { + String errorString = + "No of characters '" + publishClientId.length() + "' for ClientID: '" + publishClientId + + "' is invalid (should be less than 24, hence please provide a " + + "simple " + + + + "'owner' tag)"; + log.error(errorString); + throw new DeviceControllerException(errorString); + } else { + log.info("No of Characters " + publishClientId.length() + " for ClientID : '" + publishClientId + + "' is acceptable"); + } + + try { + client = new MqttClient(mqttEndpoint,publishClientId); + options = new MqttConnectOptions(); + options.setWill("device/clienterrors", "crashed".getBytes(UTF_8), 2, true); + client.setCallback(this); + client.connect(options); + + client.publish(publishTopic, payload, 0, true); + + if (log.isDebugEnabled()) { + log.debug("MQTT Client successfully published to topic: " + publishTopic + + ", with payload - " + payload); + } + client.disconnect(); + } catch (MqttException ex) { + String errorMsg = + "MQTT Client Error" + "\n\tReason: " + ex.getReasonCode() + + "\n\tMessage: " + + ex.getMessage() + "\n\tLocalMsg: " + ex.getLocalizedMessage() + + "\n\tCause: " + ex.getCause() + "\n\tException: " + ex; + + log.error(errorMsg, ex); + throw new DeviceControllerException(errorMsg, ex); + } + } else { + log.warn("MQTT set to false in 'device-mgt-config.xml'"); + } + } + + @Override + public void connectionLost(Throwable arg0) { + log.error("Connection to MQTT Endpoint Lost"); + } + + + @Override + public void deliveryComplete(IMqttDeliveryToken topic) { + log.info("Published topic: '" + topic.getTopics()[0] + "' successfully to client: '" + + topic.getClient().getClientId() + "'"); + } + + @Override + public void messageArrived(String arg0, MqttMessage arg1) throws Exception { + log.info("MQTT Message received: " + arg1.toString()); + } + + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/DeviceRecord.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/DeviceRecord.java new file mode 100644 index 00000000000..b31692d3226 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/DeviceRecord.java @@ -0,0 +1,41 @@ +/* + * 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.etc.sensormgt; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; + +@XmlRootElement +public class DeviceRecord implements Serializable{ + private Map sensorDataList = new HashMap<>(); + + public DeviceRecord(String sensorName, String sensorValue, long time) { + sensorDataList.put(sensorName, new SensorRecord(sensorValue, time)); + } + + @XmlElement + public Map getSensorDataList() { + return sensorDataList; + } + + public void addDeviceRecord(String sensorName, String sensorValue, long time){ + sensorDataList.put(sensorName, new SensorRecord(sensorValue, time)); + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorDataManager.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorDataManager.java new file mode 100644 index 00000000000..2b15c1e833b --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorDataManager.java @@ -0,0 +1,129 @@ +/* + * 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.etc.sensormgt; + +import org.wso2.carbon.device.mgt.etc.exception.DeviceControllerException; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +/** + * This class is used to store latest sensor value readings against a device id in an in-memory map. + */ +public class SensorDataManager { + + private static final SensorDataManager instance = new SensorDataManager(); + private Map deviceMap = new HashMap<>(); + + private SensorDataManager() { + } + + public static SensorDataManager getInstance() { + return instance; + } + + /** + * Store sensor record in a map. + * @param deviceId + * @param sensorName + * @param sensorValue + * @param time + * @return if success returns true + */ + public boolean setSensorRecord(String deviceId, String sensorName, String sensorValue, long time){ + + DeviceRecord deviceRecord = deviceMap.get(deviceId); + if(deviceRecord==null){ + deviceRecord = new DeviceRecord(sensorName, sensorValue, time); + }else{ + deviceRecord.addDeviceRecord(sensorName, sensorValue, time); + } + deviceMap.put(deviceId, deviceRecord); + return true; + } + + /** + * Returns last updated sensor records list for a device + * @param deviceId + * @return list of sensor records + */ + public SensorRecord[] getSensorRecords(String deviceId) throws DeviceControllerException{ + DeviceRecord deviceRecord = deviceMap.get(deviceId); + if(deviceRecord != null){ + Collection list = deviceRecord.getSensorDataList().values(); + return list.toArray(new SensorRecord[list.size()]); + } + throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId); + } + + /** + * Returns last updated sensor record for a device's sensor + * @param deviceId + * @param sensorName + * @return sensor record + */ + public SensorRecord getSensorRecord(String deviceId, String sensorName) throws + DeviceControllerException{ + DeviceRecord deviceRecord = deviceMap.get(deviceId); + if(deviceRecord != null){ + SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName); + if(sensorRecord != null){ + return sensorRecord; + } + throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName); + } + throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId); + } + + /** + * Returns last updated sensor value for a device's sensor + * @param deviceId + * @param sensorName + * @return sensor reading + */ + public String getSensorRecordValue(String deviceId, String sensorName) throws DeviceControllerException{ + DeviceRecord deviceRecord = deviceMap.get(deviceId); + if(deviceRecord != null){ + SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName); + if(sensorRecord != null){ + return sensorRecord.getSensorValue(); + } + throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName); + } + throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId); + } + + /** + * Returns last updated sensor value reading time for a device's sensor + * @param deviceId + * @param sensorName + * @return time in millis + */ + public long getSensorRecordTime(String deviceId, String sensorName) throws DeviceControllerException{ + DeviceRecord deviceRecord = deviceMap.get(deviceId); + if(deviceRecord != null){ + SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName); + if(sensorRecord != null){ + return sensorRecord.getTime(); + } + throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId + " Sensor Name: "+sensorName); + } + throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorRecord.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorRecord.java new file mode 100644 index 00000000000..2ef46cac735 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/sensormgt/SensorRecord.java @@ -0,0 +1,46 @@ +/* + * 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.etc.sensormgt; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class SensorRecord implements Serializable{ + //sensor value float, int, boolean all should be converted into string + private String sensorValue; + private long time; + + public SensorRecord(String sensorValue, long time) { + this.sensorValue = sensorValue; + this.time = time; + } + + @XmlElement + public String getSensorValue() { + return sensorValue; + } + + @XmlElement + public long getTime() { + return time; + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeService.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeService.java new file mode 100644 index 00000000000..9f0e3cdc24d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeService.java @@ -0,0 +1,23 @@ +/* + * 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.etc.service; + + +public interface DeviceTypeService { +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeServiceImpl.java new file mode 100644 index 00000000000..65d11d3b08a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/service/DeviceTypeServiceImpl.java @@ -0,0 +1,23 @@ +/* + * 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.etc.service; + + +public class DeviceTypeServiceImpl implements DeviceTypeService { +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/startup/StartupUrlPrinter.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/startup/StartupUrlPrinter.java new file mode 100644 index 00000000000..afde2330c6a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/startup/StartupUrlPrinter.java @@ -0,0 +1,58 @@ +/* + * 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.etc.startup; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.core.ServerStartupObserver; +import org.wso2.carbon.device.mgt.etc.internal.DeviceManagementServiceComponent; +import org.wso2.carbon.utils.CarbonUtils; +import org.wso2.carbon.utils.ConfigurationContextService; +import org.wso2.carbon.utils.NetworkUtils; + +public class StartupUrlPrinter implements ServerStartupObserver { + private static final Log log = LogFactory.getLog(StartupUrlPrinter.class); + @Override + public void completingServerStartup() { + + } + + @Override + public void completedServerStartup() { + printUrl(); + + + } + private void printUrl() { + // Hostname + String hostName = "localhost"; + try { + hostName = NetworkUtils.getMgtHostName(); + } catch (Exception ignored) { + } + // HTTPS port + String mgtConsoleTransport = CarbonUtils.getManagementTransport(); + ConfigurationContextService configContextService = DeviceManagementServiceComponent.configurationContextService; + + int httpsPort = CarbonUtils.getTransportPort(configContextService, mgtConsoleTransport); + + log.info("CDM - Device Common API Service: https://" + hostName + ":" + httpsPort + "/common"); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceEventsStatisticsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceEventsStatisticsException.java new file mode 100644 index 00000000000..ed0e75ca7ec --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceEventsStatisticsException.java @@ -0,0 +1,36 @@ +/* + * 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.etc.statistics; + +public class DeviceEventsStatisticsException extends Exception{ + + private static final long serialVersionUID = -5743346027793277063L; + + public DeviceEventsStatisticsException(String msg) { + super(msg); + } + + public DeviceEventsStatisticsException(String msg, Throwable e) { + super(msg, e); + } + + public DeviceEventsStatisticsException(Throwable throwable) { + super(throwable); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtEventsStatisticsClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtEventsStatisticsClient.java new file mode 100644 index 00000000000..4828bbedb1a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtEventsStatisticsClient.java @@ -0,0 +1,139 @@ +/* + * 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.etc.statistics; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.statistics.dto.DeviceEventsDTO; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class DeviceMgtEventsStatisticsClient { + + private static final Log log = LogFactory.getLog(DeviceMgtEventsStatisticsClient.class); + + private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB"; + + private static volatile DataSource dataSource = null; + + + public static void initializeDataSource() throws DeviceEventsStatisticsException { + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME); + } catch (NamingException e) { + throw new DeviceEventsStatisticsException("Error while looking up the data " + + "source: " + DATA_SOURCE_NAME); + } + } + + public List getRecentDeviceStats(String owner, int recordLimit) + throws DeviceEventsStatisticsException { + + if (dataSource == null) { + throw new DeviceEventsStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration."); + } + + Connection connection = null; + Statement statement = null; + ResultSet rs = null; + try { + connection = dataSource.getConnection(); + statement = connection.createStatement(); + String query = null; + String table = "DEVICE_EVENTS"; + + if(owner==null){ + throw new DeviceEventsStatisticsException("Owner cannot be null!"); + } + + String ownerString = ""; + ownerString = String.format(" AND owner = '%s'", owner); + + String limitString = ""; + if(recordLimit > 0){ + limitString = String.format(" LIMIT %d", recordLimit); + } + + query = String.format("SELECT * FROM %s WHERE 1=1 %s ORDER BY `time` DESC %s" + ,table, ownerString, limitString); + + log.info("query: " + query); + + if (query == null) { + throw new DeviceEventsStatisticsException("SQL query is null!"); + } + + List DeviceEventsDTOs = new ArrayList(); + rs = statement.executeQuery(query); + while (rs.next()) { + DeviceEventsDTO DeviceEventsDTO = new DeviceEventsDTO(); + DeviceEventsDTO.setTime(rs.getString("TIME")); + DeviceEventsDTO.setDeviceActivity(rs.getString("ACTIVITY")); + //(id + type) uniquely identifies a device + DeviceEventsDTO.setDeviceId(rs.getString("DEVICEID")); + DeviceEventsDTO.setDeviceType(rs.getString("DEVICETYPE")); + + DeviceEventsDTOs.add(DeviceEventsDTO); + + } + + return DeviceEventsDTOs; + + } catch (Exception e) { +// throw new IoTEventsStatisticsException( +// "Error occurred while querying from JDBC database", e); + //Exception hiding to avoid GC error + log.error("Error occurred while querying from JDBC database: " + e.getMessage()); + return new ArrayList<>(); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ignore) { + + } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException ignore) { + + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignore) { + + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtUsageStatisticsClient.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtUsageStatisticsClient.java new file mode 100644 index 00000000000..23353b63df2 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceMgtUsageStatisticsClient.java @@ -0,0 +1,176 @@ +/* + * 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.etc.statistics; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.statistics.dto.DeviceUsageDTO; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; + +public class DeviceMgtUsageStatisticsClient { + + private static final Log log = LogFactory.getLog(DeviceMgtUsageStatisticsClient.class); + + private static final String DATA_SOURCE_NAME = "jdbc/WSO2DM_STATS_DB"; + + private static volatile DataSource dataSource = null; + + + public static void initializeDataSource() throws DeviceUsageStatisticsException { + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(DATA_SOURCE_NAME); + } catch (NamingException e) { + throw new DeviceUsageStatisticsException("Error while looking up the data " + + "source: " + DATA_SOURCE_NAME); + } + } +// +// public List getTemperatureData(String user, String deviceId, String fromDate, +// String toDate) +// throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching temperature data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_TEMPERATURE_SUMMARY", "TEMPERATURE", user, deviceId, fromDate, +// toDate); +// } +// +// public List getBulbStatusData(String user, String deviceId, String fromDate, +// String toDate) +// throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching bulb status data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_BULB_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate, +// toDate); +// } +// +// public List getFanStatusData(String user, String deviceId, String fromDate, +// String toDate) throws IoTUsageStatisticsException { +// +// log.debug(String.format( +// "Fetching fan status data. user : %s, deviceId : %s, from : %s, to : %s", user, +// deviceId, fromDate, toDate)); +// return getDeviceStats("DEVICE_FAN_USAGE_SUMMARY", "STATUS", user, deviceId, fromDate, +// toDate); +// } + + public List getDeviceStats(String table, String valueColumn, String owner, + String deviceId, String fromDate, String toDate) + throws DeviceUsageStatisticsException { + + if (dataSource == null) { + throw new DeviceUsageStatisticsException("BAM data source hasn't been initialized. Ensure that the data source is properly configured in the APIUsageTracker configuration."); + } + + Connection connection = null; + Statement statement = null; + ResultSet rs = null; + try { + connection = dataSource.getConnection(); + statement = connection.createStatement(); + String query = null; + + String ownerString = ""; + if (owner != null) { + ownerString = String.format("owner = '%s' AND ", owner); + } + + if (fromDate != null && toDate != null) { + //fromDate = getConvertedTime(fromDate); + //toDate = getConvertedTime(toDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` " + + "BETWEEN '%s' AND '%s'", table, deviceId, fromDate, toDate); + } else if (fromDate != null) { + //fromDate = getConvertedTime(fromDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` >= " + + "'%s'", table, deviceId, fromDate); + } else if (toDate != null) { + //toDate = getConvertedTime(toDate); + query = String.format( + "SELECT * FROM %s WHERE " + ownerString + "deviceid = '%s' AND `time` <= " + + "'%s'", table, deviceId, toDate); + } + + log.info("query: " + query); + + if (query == null) { + return null; + } + + List deviceUsageDTOs = new ArrayList(); + rs = statement.executeQuery(query); + while (rs.next()) { + DeviceUsageDTO deviceUsageDTO = new DeviceUsageDTO(); + deviceUsageDTO.setTime(rs.getString("TIME")); + deviceUsageDTO.setValue(rs.getString(valueColumn)); + + deviceUsageDTOs.add(deviceUsageDTO); + + } + + return deviceUsageDTOs; + + } catch (Exception e) { +// throw new IoTUsageStatisticsException( +// "Error occurred while querying from JDBC database", e); + //Exception hiding to avoid GC error + log.error("Error occurred while querying from JDBC database: " + e.getMessage()); + return new ArrayList<>(); + } finally { + if (rs != null) { + try { + rs.close(); + } catch (SQLException ignore) { + + } + } + if (statement != null) { + try { + statement.close(); + } catch (SQLException ignore) { + + } + } + if (connection != null) { + try { + connection.close(); + } catch (SQLException ignore) { + + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceUsageStatisticsException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceUsageStatisticsException.java new file mode 100644 index 00000000000..33709cdf6ff --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/DeviceUsageStatisticsException.java @@ -0,0 +1,36 @@ +/* + * 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.etc.statistics; + +public class DeviceUsageStatisticsException extends Exception{ + + private static final long serialVersionUID = -5743346027793277063L; + + public DeviceUsageStatisticsException(String msg) { + super(msg); + } + + public DeviceUsageStatisticsException(String msg, Throwable e) { + super(msg, e); + } + + public DeviceUsageStatisticsException(Throwable throwable) { + super(throwable); + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceEventsDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceEventsDTO.java new file mode 100644 index 00000000000..34391ad4ed1 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceEventsDTO.java @@ -0,0 +1,60 @@ +/* + * 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.etc.statistics.dto; + +public class DeviceEventsDTO { + + private String time; + private String deviceId; + private String deviceType; + private String deviceActivity; + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getDeviceActivity() { + return deviceActivity; + } + + public void setDeviceActivity(String deviceActivity) { + this.deviceActivity = deviceActivity; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public String getDeviceId() { + return deviceId; + } + + public String getDeviceType() { + return deviceType; + } + + public void setDeviceType(String deviceType) { + this.deviceType = deviceType; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceUsageDTO.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceUsageDTO.java new file mode 100644 index 00000000000..5a51028a9a4 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/statistics/dto/DeviceUsageDTO.java @@ -0,0 +1,42 @@ +/* + * 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.etc.statistics.dto; + +public class DeviceUsageDTO { + + private String time; + private String value; + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Claims.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Claims.java new file mode 100644 index 00000000000..1ae25809456 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Claims.java @@ -0,0 +1,59 @@ +/* + * 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.etc.util; + +public class Claims { + + private String dialectUrl; + private String description; + private String claimUrl; + private String value; + + public String getDialectUrl() { + return dialectUrl; + } + + public void setDialectUrl(String dialectUrl) { + this.dialectUrl = dialectUrl; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getClaimUrl() { + return claimUrl; + } + + public void setClaimUrl(String claimUrl) { + this.claimUrl = claimUrl; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/DeviceTypes.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/DeviceTypes.java new file mode 100644 index 00000000000..05cc6ca3c4d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/DeviceTypes.java @@ -0,0 +1,27 @@ +package org.wso2.carbon.device.mgt.etc.util; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.io.Serializable; + +@XmlRootElement +public class DeviceTypes implements Serializable{ + + //private static final long serialVersionUID = 7526472295622776147L; + + private String name; + + + public DeviceTypes() { + } + + @XmlElement + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/IoTUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/IoTUtil.java new file mode 100644 index 00000000000..f705888b45c --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/IoTUtil.java @@ -0,0 +1,92 @@ +package org.wso2.carbon.device.mgt.etc.util; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.conn.scheme.PlainSocketFactory; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.conn.PoolingClientConnectionManager; +import org.apache.http.params.BasicHttpParams; +import org.apache.http.params.HttpParams; +import org.apache.http.util.EntityUtils; +import org.wso2.carbon.device.mgt.etc.exception.DeviceMgtCommonsException; +import org.wso2.carbon.device.mgt.etc.internal.DeviceMgtCommonDataHolder; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.UnrecoverableKeyException; + + +public class IoTUtil { + + private static final Log log = LogFactory.getLog(IoTUtil.class); + + /** + * Return a http client instance + * @param port - server port + * @param protocol- service endpoint protocol http/https + * @return + */ + public static HttpClient getHttpClient(int port, String protocol) + throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, + KeyManagementException { + SchemeRegistry registry = new SchemeRegistry(); + + if ("https".equals(protocol)) { + System.setProperty("javax.net.ssl.trustStrore", DeviceMgtCommonDataHolder.getInstance().getTrustStoreLocation()); + System.setProperty("javax.net.ssl.trustStorePassword", DeviceMgtCommonDataHolder.getInstance().getTrustStorePassword()); + + if (port >= 0) { + registry.register(new Scheme("https", port, SSLSocketFactory.getSocketFactory())); + } else { + registry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); + } + } else if ("http".equals(protocol)) { + if (port >= 0) { + registry.register(new Scheme("http", port, PlainSocketFactory.getSocketFactory())); + } else { + registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); + } + } + HttpParams params = new BasicHttpParams(); + PoolingClientConnectionManager tcm = new PoolingClientConnectionManager(registry); + HttpClient client = new DefaultHttpClient(tcm, params); + return client; + } + + public static String getResponseString(HttpResponse httpResponse) throws + DeviceMgtCommonsException { + BufferedReader br = null; + try { + br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent())); + String readLine; + String response = ""; + while (((readLine = br.readLine()) != null)) { + response += readLine; + } + return response; + } catch (IOException e) { + throw new DeviceMgtCommonsException("Error while reading the response from the remote. " + + e.getMessage(), e); + } finally { + EntityUtils.consumeQuietly(httpResponse.getEntity()); + if (br != null) { + try { + br.close(); + } catch (IOException e) { + log.warn("Error while closing the connection! " + e.getMessage()); + } + } + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ResourceFileLoader.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ResourceFileLoader.java new file mode 100644 index 00000000000..181cfc3b224 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ResourceFileLoader.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2014, 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.etc.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; + +public class ResourceFileLoader { + + private static Log log = LogFactory.getLog(ResourceFileLoader.class); + private String filePath; + + public ResourceFileLoader(String fileName) { + String path = ResourceFileLoader.class.getClassLoader().getResource("").getPath(); + + String fullPath = path; + try { + fullPath = URLDecoder.decode(path, "UTF-8"); + } catch (UnsupportedEncodingException e) { + + } + //log.info(fullPath); + String pathArr[] = fullPath.split("/WEB-INF/classes/"); + filePath = pathArr[0] + fileName; + + } + + public String getPath() { + return filePath; + } + + public File getFile() { + File file = new File(filePath); + return file; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Role.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Role.java new file mode 100644 index 00000000000..ad61631d47d --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/Role.java @@ -0,0 +1,37 @@ +/* + * 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.etc.util; + +public class Role { + + private String roleName; + + public Role(String roleName) { + this.roleName = roleName; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/User.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/User.java new file mode 100644 index 00000000000..075e0f12048 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/User.java @@ -0,0 +1,252 @@ +/* + * 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.etc.util; + +import java.util.ArrayList; + +public class User { + + private String userName; + private String roleName; + private String firstName; + private String email; + private String lastName; + private String streatAddress; + private String locality; + private String region; + private String postalCode; + private String country; + private String hone; + private String im; + private String organization; + private String url; + private String title; + private String mobile; + private String nickName; + private String dateOfBirth; + private String gender; + private String accountStatus; + private String challengeQuestion; + private String identityClaimUri; + private String tempEmailAddress; + + + private ArrayList claimList; + + public User(String userName) { + this.userName = userName; + } + + public User(String userName, String roleName) { + this.userName = userName; + this.roleName = roleName; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getRoleName() { + return roleName; + } + + public void setRoleName(String roleName) { + this.roleName = roleName; + } + + public ArrayList getClaimList() { + return claimList; + } + + public void setClaimList(ArrayList claimList) { + this.claimList = claimList; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getStreatAddress() { + return streatAddress; + } + + public void setStreatAddress(String streatAddress) { + this.streatAddress = streatAddress; + } + + public String getLocality() { + return locality; + } + + public void setLocality(String locality) { + this.locality = locality; + } + + public String getRegion() { + return region; + } + + public void setRegion(String region) { + this.region = region; + } + + public String getPostalCode() { + return postalCode; + } + + public void setPostalCode(String postalCode) { + this.postalCode = postalCode; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getHone() { + return hone; + } + + public void setHone(String hone) { + this.hone = hone; + } + + public String getIm() { + return im; + } + + public void setIm(String im) { + this.im = im; + } + + public String getOrganization() { + return organization; + } + + public void setOrganization(String organization) { + this.organization = organization; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getMobile() { + return mobile; + } + + public void setMobile(String mobile) { + this.mobile = mobile; + } + + public String getNickName() { + return nickName; + } + + public void setNickName(String nickName) { + this.nickName = nickName; + } + + public String getDateOfBirth() { + return dateOfBirth; + } + + public void setDateOfBirth(String dateOfBirth) { + this.dateOfBirth = dateOfBirth; + } + + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public String getAccountStatus() { + return accountStatus; + } + + public void setAccountStatus(String accountStatus) { + this.accountStatus = accountStatus; + } + + public String getChallengeQuestion() { + return challengeQuestion; + } + + public void setChallengeQuestion(String challengeQuestion) { + this.challengeQuestion = challengeQuestion; + } + + public String getIdentityClaimUri() { + return identityClaimUri; + } + + public void setIdentityClaimUri(String identityClaimUri) { + this.identityClaimUri = identityClaimUri; + } + + public String getTempEmailAddress() { + return tempEmailAddress; + } + + public void setTempEmailAddress(String tempEmailAddress) { + this.tempEmailAddress = tempEmailAddress; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipArchive.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipArchive.java new file mode 100644 index 00000000000..70195cb480f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipArchive.java @@ -0,0 +1,30 @@ +package org.wso2.carbon.device.mgt.etc.util; + +import java.io.File; + +public class ZipArchive { + private File zipFile = null; + private String fileName = null; + private String deviceId = null; + + public ZipArchive(String fileName, File zipFile) { + this.fileName = fileName; + this.zipFile = zipFile; + } + + public String getDeviceId() { + return deviceId; + } + + public void setDeviceId(String deviceId) { + this.deviceId = deviceId; + } + + public File getZipFile() { + return zipFile; + } + + public String getFileName() { + return fileName; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipUtil.java new file mode 100644 index 00000000000..ded4be8b456 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/ZipUtil.java @@ -0,0 +1,97 @@ +package org.wso2.carbon.device.mgt.etc.util; + +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.etc.controlqueue.mqtt.MqttConfig; +import org.wso2.carbon.device.mgt.etc.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.etc.config.server.DeviceCloudConfigManager; +import org.wso2.carbon.utils.CarbonUtils; + +import java.io.File; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + + +public class ZipUtil { + + public ZipArchive downloadSketch(String owner, String tenantDomain, String deviceType, + String deviceId, String deviceName, String token, + String refreshToken) + throws DeviceManagementException { + + if (owner == null || deviceType == null) { + throw new DeviceManagementException("Invalid parameters for `owner` or `deviceType`"); + } + + String sep = File.separator; + String sketchFolder = "repository" + sep + "resources" + sep + "sketches"; + String archivesPath = CarbonUtils.getCarbonHome() + sep + sketchFolder + sep + "archives" + + sep + deviceId; + String templateSketchPath = sketchFolder + sep + deviceType; + +// String iotServerIP = System.getProperty("bind.address"); + String iotServerIP = System.getProperty("server.host"); + String httpsServerPort = System.getProperty("httpsPort"); + String httpServerPort = System.getProperty("httpPort"); + + String httpsServerEP = "https://" + iotServerIP + ":" + httpsServerPort; + String httpServerEP = "http://" + iotServerIP + ":" + httpServerPort; + + String apimHost = + DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager() + .getServerURL(); + +// int indexOfChar = apimIP.lastIndexOf(File.separator); +// if (indexOfChar != -1) { +// apimIP = apimIP.substring((indexOfChar + 1), apimIP.length()); +// } + + String apimGatewayPort = + DeviceCloudConfigManager.getInstance().getDeviceCloudMgtConfig().getApiManager() + .getGatewayPort(); + + String apimEndpoint = apimHost + ":" + apimGatewayPort; + + String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint(); +// indexOfChar = mqttEndpoint.lastIndexOf(File.separator); +// if (indexOfChar != -1) { +// mqttEndpoint = mqttEndpoint.substring((indexOfChar + 1), mqttEndpoint.length()); +// } + + String xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint(); +// indexOfChar = xmppEndpoint.lastIndexOf(File.separator); +// if (indexOfChar != -1) { +// xmppEndpoint = xmppEndpoint.substring((indexOfChar + 1), xmppEndpoint.length()); +// } + + int indexOfChar = xmppEndpoint.lastIndexOf(":"); + if (indexOfChar != -1) { + xmppEndpoint = xmppEndpoint.substring(0, indexOfChar); + } + + xmppEndpoint = xmppEndpoint + ":" + XmppConfig.getInstance().getSERVER_CONNECTION_PORT(); + + Map contextParams = new HashMap(); + contextParams.put("DEVICE_OWNER", owner); + contextParams.put("DEVICE_ID", deviceId); + contextParams.put("DEVICE_NAME", deviceName); + contextParams.put("HTTPS_EP", httpsServerEP); + contextParams.put("HTTP_EP", httpServerEP); + contextParams.put("APIM_EP", apimEndpoint); + contextParams.put("MQTT_EP", mqttEndpoint); + contextParams.put("XMPP_EP", xmppEndpoint); + contextParams.put("DEVICE_TOKEN", token); + contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken); + + ZipArchive zipFile; + try { + zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, + contextParams); + } catch (IOException e) { + throw new DeviceManagementException("Zip File Creation Failed", e); + } + + return zipFile; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/constants/PluginConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/constants/PluginConstants.java new file mode 100644 index 00000000000..5c615e8b59a --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/constants/PluginConstants.java @@ -0,0 +1,22 @@ +/* + * 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.etc.util.cdmdevice.constants; + +public class PluginConstants { + public static final String DB_SCRIPTS_FOLDER = "cdm"; +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/DeviceManagementDAOFactory.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/DeviceManagementDAOFactory.java new file mode 100644 index 00000000000..9f87f546377 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/DeviceManagementDAOFactory.java @@ -0,0 +1,77 @@ +/* + * 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.etc.util.cdmdevice.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.config.devicetype.datasource.DeviceTypeConfig; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.exception.DeviceMgtPluginException; + +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; +import javax.sql.DataSource; +import java.util.*; + +/** + * Factory class used to create IotDeviceManagement related DAO objects. + */ +public abstract class DeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(DeviceManagementDAOFactory.class); + private static Map dataSourceMap = new HashMap(); + private static boolean isInitialized; + + public static void init(Map iotDataSourceConfigMap) + throws DeviceMgtPluginException { + DataSource dataSource; + for (Map.Entry plugin : iotDataSourceConfigMap.entrySet()) { + String pluginType = plugin.getKey(); + if (dataSourceMap.get(pluginType) == null) { + dataSource = DeviceManagementDAOFactory.resolveDataSource(plugin.getValue().getDatasourceName()); + dataSourceMap.put(pluginType, dataSource); + } + } + //Todo:check + isInitialized = true; + } + + + /** + * Resolve data source from the data source definition. + * @return data source resolved from the data source definition + */ + public static DataSource resolveDataSource(String dataSourceName) throws + DeviceMgtPluginException { + + DataSource dataSource = null; + try { + Context ctx = new InitialContext(); + dataSource = (DataSource) ctx.lookup(dataSourceName); + } catch (NamingException e) { + throw new DeviceMgtPluginException("Error while looking up the data " + + "source: " + dataSourceName); + } + return dataSource; + } + + public static Map getDataSourceMap() { + return dataSourceMap; + } +} \ No newline at end of file diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceDAO.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceDAO.java new file mode 100644 index 00000000000..4b138a6b275 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceDAO.java @@ -0,0 +1,75 @@ +/* + * 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.etc.util.cdmdevice.dao; + +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dto.IotDevice; + +import java.util.List; + +/** + * This class represents the key operations associated with persisting iot-device related + * information. + */ +public interface IotDeviceDAO { + + /** + * Fetches a IotDevice from Iot database. + * + * @param iotDeviceId Id of the Iot-Device. + * @return IotDevice corresponding to given device-id. + * @throws IotDeviceManagementDAOException + */ + IotDevice getIotDevice(String iotDeviceId) throws IotDeviceManagementDAOException; + + /** + * Adds a new IotDevice to the MDM database. + * + * @param iotDevice IotDevice to be added. + * @return The status of the operation. + * @throws IotDeviceManagementDAOException + */ + boolean addIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException; + + /** + * Updates IotDevice information in MDM database. + * + * @param iotDevice IotDevice to be updated. + * @return The status of the operation. + * @throws IotDeviceManagementDAOException + */ + boolean updateIotDevice(IotDevice iotDevice) throws IotDeviceManagementDAOException; + + /** + * Deletes a given IotDevice from MDM database. + * + * @param mblDeviceId Id of IotDevice to be deleted. + * @return The status of the operation. + * @throws IotDeviceManagementDAOException + */ + boolean deleteIotDevice(String mblDeviceId) throws IotDeviceManagementDAOException; + + /** + * Fetches all IotDevices from MDM database. + * + * @return List of IotDevices. + * @throws IotDeviceManagementDAOException + */ + List getAllIotDevices() throws IotDeviceManagementDAOException; + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOException.java new file mode 100644 index 00000000000..a7ccb443533 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOException.java @@ -0,0 +1,80 @@ +/* + * 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.etc.util.cdmdevice.dao; + +/** + * Custom exception class for Iot device specific data access related exceptions. + */ +public class IotDeviceManagementDAOException extends Exception { + + private String message; + private static final long serialVersionUID = 2021891706072918865L; + + /** + * Constructs a new IotDeviceManagementDAOException with the specified detail message and + * nested exception. + * + * @param message error message + * @param nestedException exception + */ + public IotDeviceManagementDAOException(String message, Exception nestedException) { + super(message, nestedException); + setErrorMessage(message); + } + + /** + * Constructs a new IotDeviceManagementDAOException with the specified detail message + * and cause. + * + * @param message the detail message. + * @param cause the cause of this exception. + */ + public IotDeviceManagementDAOException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + /** + * Constructs a new IotDeviceManagementDAOException with the specified detail message. + * + * @param message the detail message. + */ + public IotDeviceManagementDAOException(String message) { + super(message); + setErrorMessage(message); + } + + /** + * Constructs a new IotDeviceManagementDAOException with the specified and cause. + * + * @param cause the cause of this exception. + */ + public IotDeviceManagementDAOException(Throwable cause) { + super(cause); + } + + public String getMessage() { + return message; + } + + public void setErrorMessage(String errorMessage) { + this.message = errorMessage; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOFactoryInterface.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOFactoryInterface.java new file mode 100644 index 00000000000..02433f83661 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/IotDeviceManagementDAOFactoryInterface.java @@ -0,0 +1,25 @@ +/* + * 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.etc.util.cdmdevice.dao; + +public interface IotDeviceManagementDAOFactoryInterface { + + IotDeviceDAO getIotDeviceDAO(); + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/util/DeviceManagementDAOUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/util/DeviceManagementDAOUtil.java new file mode 100644 index 00000000000..cb508cd6259 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dao/util/DeviceManagementDAOUtil.java @@ -0,0 +1,85 @@ +/* + * 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.etc.util.cdmdevice.dao.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.exception.DeviceMgtPluginException; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.util.IotDeviceManagementSchemaInitializer; +import javax.sql.DataSource; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * Utility method required by IotDeviceManagement DAO classes. + */ +public class DeviceManagementDAOUtil { + + private static final Log log = LogFactory.getLog(DeviceManagementDAOUtil.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 iot device management schema. + * + * @param dataSource Iot data source + */ + public static void setupDeviceManagementSchema(DataSource dataSource) throws + DeviceMgtPluginException { + IotDeviceManagementSchemaInitializer initializer = + new IotDeviceManagementSchemaInitializer(dataSource); + log.info("Initializing iot device management repository database schema"); + try { + initializer.createRegistryDatabase(); + } catch (Exception e) { + throw new DeviceMgtPluginException("Error occurred while initializing Iot Device " + + "Management database schema", e); + } + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dto/IotDevice.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dto/IotDevice.java new file mode 100644 index 00000000000..63e7a756835 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/dto/IotDevice.java @@ -0,0 +1,58 @@ +/* + * 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.etc.util.cdmdevice.dto; + +import java.io.Serializable; +import java.util.Map; + + +public class IotDevice implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 1L; + private String iotDeviceId; + private String iotDeviceName; + private Map deviceProperties; + + public void setIotDeviceName(String iotDeviceName){ + this.iotDeviceName=iotDeviceName; + + } + public String getIotDeviceName() { + return iotDeviceName; + } + + public String getIotDeviceId() { + return iotDeviceId; + } + + public void setIotDeviceId(String iotDeviceId) { + this.iotDeviceId = iotDeviceId; + } + + public Map getDeviceProperties() { + return deviceProperties; + } + + public void setDeviceProperties(Map deviceProperties) { + this.deviceProperties = deviceProperties; + } +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/exception/DeviceMgtPluginException.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/exception/DeviceMgtPluginException.java new file mode 100644 index 00000000000..41cf9c44ecd --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/exception/DeviceMgtPluginException.java @@ -0,0 +1,57 @@ +/* + * 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.etc.util.cdmdevice.exception; + + +public class DeviceMgtPluginException extends Exception{ + + private static final long serialVersionUID = -2297311387874900305L; + private String errorMessage; + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + + public DeviceMgtPluginException(String msg, Exception nestedEx) { + super(msg, nestedEx); + setErrorMessage(msg); + } + + public DeviceMgtPluginException(String message, Throwable cause) { + super(message, cause); + setErrorMessage(message); + } + + public DeviceMgtPluginException(String msg) { + super(msg); + setErrorMessage(msg); + } + + public DeviceMgtPluginException() { + super(); + } + + public DeviceMgtPluginException(Throwable cause) { + super(cause); + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementSchemaInitializer.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementSchemaInitializer.java new file mode 100644 index 00000000000..cd03fd633f0 --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementSchemaInitializer.java @@ -0,0 +1,57 @@ +/* + * 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.etc.util.cdmdevice.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.constants.PluginConstants; +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 final class IotDeviceManagementSchemaInitializer extends DatabaseCreator { + + private static final Log log = LogFactory.getLog(IotDeviceManagementSchemaInitializer.class); + private static final String setupSQLScriptBaseLocation = + CarbonUtils.getCarbonHome() + File.separator + "dbscripts" + File.separator + + PluginConstants.DB_SCRIPTS_FOLDER + + File.separator + "plugins" + File.separator; + + public IotDeviceManagementSchemaInitializer(DataSource dataSource) { + super(dataSource); + } + + protected String getDbScriptLocation(String databaseType) { + String scriptName = databaseType + ".sql"; + if (log.isDebugEnabled()) { + log.debug("Loading database script from :" + scriptName); + } + //TODO:test + return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName; + } + +} diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementUtil.java b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementUtil.java new file mode 100644 index 00000000000..3eb8f9e553f --- /dev/null +++ b/components/device-mgt/org.wso2.carbon.device.mgt.etc/src/main/java/org/wso2/carbon/device/mgt/etc/util/cdmdevice/util/IotDeviceManagementUtil.java @@ -0,0 +1,389 @@ +/* + * 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.etc.util.cdmdevice.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.w3c.dom.Document; +import org.wso2.carbon.device.mgt.common.Device; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.etc.util.ZipArchive; +import org.wso2.carbon.device.mgt.etc.util.cdmdevice.dto.IotDevice; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * Provides utility methods required by the iot device management bundle. + */ +public class IotDeviceManagementUtil { + + private static final Log log = LogFactory.getLog(IotDeviceManagementUtil.class.getName()); + + public static Document convertToDocument(File file) throws DeviceManagementException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); + try { + DocumentBuilder docBuilder = factory.newDocumentBuilder(); + return docBuilder.parse(file); + } catch (Exception e) { + throw new DeviceManagementException("Error occurred while parsing file, while converting " + + "to a org.w3c.dom.Document : " + e.getMessage(), e); + } + } + + private 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 IotDevice convertToIotDevice(Device device) { + IotDevice iotDevice = null; + if (device != null) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(device.getDeviceIdentifier()); + iotDevice.setIotDeviceName(device.getName()); + Map deviceProperties = new HashMap(); + + if (device.getProperties() != null) { + + for (Device.Property deviceProperty : device.getProperties()) { + deviceProperties.put(deviceProperty.getName(), deviceProperty.getValue()); + } + + iotDevice.setDeviceProperties(deviceProperties); + } else { + iotDevice.setDeviceProperties(deviceProperties); + } + } + return iotDevice; + } + + public static Device convertToDevice(IotDevice iotDevice) { + Device device = null; + if (iotDevice != null) { + device = new Device(); + List propertyList = new ArrayList(); + + if (iotDevice.getDeviceProperties() != null) { + for (Map.Entry deviceProperty : iotDevice.getDeviceProperties().entrySet()) { + propertyList.add(getProperty(deviceProperty.getKey(), deviceProperty.getValue())); + } + } + + device.setProperties(propertyList); + device.setName(iotDevice.getIotDeviceName()); + device.setDeviceIdentifier(iotDevice.getIotDeviceId()); + } + return device; + } + + public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams) + throws DeviceManagementException, IOException { + + String sep = File.separator; + String sketchPath = CarbonUtils.getCarbonHome() + sep + 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); + } + + String zipFileName = "zipFile.zip"; + + try { + Map> properties = getProperties(sketchPath + sep + "sketch" + ".properties"); + List templateFiles = properties.get("templates"); + +// zipFileName = properties.get("zipfilename").get(0); + zipFileName = contextParams.get("DEVICE_NAME") + ".zip"; + + for (String templateFile : templateFiles) { + parseTemplate(templateSketchPath + sep + templateFile, archivesPath + sep + templateFile, + contextParams); + } + + templateFiles.add("sketch.properties"); // ommit copying the props file + copyFolder(new File(sketchPath), new File(archivesPath), templateFiles); + + } catch (IOException ex) { + throw new DeviceManagementException( + "Error occurred when trying to read property " + "file sketch.properties", ex); + } + + try { + createZipArchive(archivesPath); + } catch (IOException e) { + String message = "Zip file for the specific device agent not found at path: " + archivesPath; + log.error(message); + log.error(e); + throw new DeviceManagementException(message, e); + } + FileUtils.deleteDirectory(new File(archivesPath));//clear folder + + /* now get the zip file */ + File zip = new File(archivesPath + ".zip"); + return new ZipArchive(zipFileName, zip); + } + + private static Map> 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> properties = new HashMap>(); + + String templates = prop.getProperty("templates"); + List list = new ArrayList(Arrays.asList(templates.split(","))); + properties.put("templates", list); + + final String filename = prop.getProperty("zipfilename"); + list = new ArrayList() {{ + add(filename); + }}; + properties.put("zipfilename", list); + return properties; + + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException { + //TODO add velocity 1.7, currently commented + //TODO conflicting when calling in CXF environment with the opensaml orbit + + // /* create a context and add data */ + // VelocityContext context = new VelocityContext(contextParams); + // + // /* first, get and initialize an engine */ + // VelocityEngine ve = new VelocityEngine(); + // ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, + // "org.apache.velocity.runtime.log.Log4JLogChute" ); + // ve.setProperty("runtime.log.logsystem.log4j.logger", IotDeviceManagementUtil.class.getName()); + // ve.init(); + // + // String sep = File.separator; + // Template t = ve.getTemplate(srcFile); + // FileWriter writer = null; + // try { + // writer = new FileWriter(dstFile); + // t.merge(context, writer); + // } finally { + // if (writer != null) { + // writer.flush(); + // writer.close(); + // } + // } + + //read from file + FileInputStream inputStream = new FileInputStream(srcFile); + 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()); + } + if (inputStream != null) { + inputStream.close(); + } + //write to file + FileOutputStream outputStream = new FileOutputStream(dstFile); + IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString()); + if (outputStream != null) { + outputStream.close(); + } + } + + private static void copyFolder(File src, File dest, List 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 { + silentClose(in); + silentClose(out); + } + } + } + + private static void silentClose(InputStream is) { + if (is == null) { + return; + } + + try { + is.close(); + } catch (IOException e) { + // do nothing + } + + } + + private static void silentClose(OutputStream os) { + if (os == null) { + return; + } + + try { + + os.close(); + } catch (IOException e) { + // do nothing + } + } + + 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 { + silentClose(origin); + silentClose(out); + } + return true; + } + +} diff --git a/components/device-mgt/pom.xml b/components/device-mgt/pom.xml index 7aa16b89db6..1de382fbd34 100644 --- a/components/device-mgt/pom.xml +++ b/components/device-mgt/pom.xml @@ -30,7 +30,6 @@ 4.0.0 org.wso2.carbon.devicemgt device-mgt - 1.1.0-SNAPSHOT pom WSO2 Carbon - Device Management Component http://wso2.org @@ -42,26 +41,7 @@ org.wso2.carbon.device.mgt.ui org.wso2.carbon.device.mgt.analytics org.wso2.carbon.device.mgt.analytics.data.publisher + org.wso2.carbon.device.mgt.etc - - - - - org.apache.felix - maven-scr-plugin - 1.7.2 - - - generate-scr-scrdescriptor - - scr - - - - - - - - diff --git a/pom.xml b/pom.xml index ecf574d2a10..d478f048092 100644 --- a/pom.xml +++ b/pom.xml @@ -1361,6 +1361,29 @@ ${httpclient.version} + + + org.igniterealtime.smack.wso2 + smack + ${smack.wso2.version} + + + org.igniterealtime.smack.wso2 + smackx + ${smackx.wso2.version} + + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + ${eclipse.paho.version} + + + + commons-configuration + commons-configuration + ${commons-configuration.version} + @@ -1371,7 +1394,6 @@ HEAD - @@ -1397,7 +1419,7 @@ org.apache.maven.plugins maven-compiler-plugin - 2.3.1 + 2.3.2 UTF-8 1.7 @@ -1419,6 +1441,16 @@ + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + UTF-8 + 1.7 + 1.7 + + org.apache.felix maven-scr-plugin @@ -1459,8 +1491,9 @@ + org.apache.maven.plugins maven-assembly-plugin - 2.2-beta-2 + 2.5.5 org.apache.maven.plugins @@ -1691,9 +1724,15 @@ 2.4.0.wso2v1 3.2.0.wso2v1 + 1.8 5.1.34 + + + 3.0.4.wso2v1 + 3.0.4.wso2v1 + 1.0.2