forked from community/device-mgt-plugins
Merge pull request #110 from Shabirmean/IoTS-1.0.0-M1
Updated RPi Agent to be able to get IPs in all POSIX systems and NT
commit
00db503798
@ -1,36 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.dto;
|
||||
|
||||
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
||||
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
@XmlRootElement
|
||||
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class DeviceJSON {
|
||||
@XmlElement(required = true) public String owner;
|
||||
@XmlElement(required = true) public String deviceId;
|
||||
@XmlElement(required = true) public String reply;
|
||||
@XmlElement public Long time;
|
||||
@XmlElement public String key;
|
||||
@XmlElement public float value;
|
||||
}
|
@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.exception;
|
||||
|
||||
public class VirtualFireAlarmException extends Exception {
|
||||
private static final long serialVersionUID = 118512086957330189L;
|
||||
|
||||
public VirtualFireAlarmException(String errorMessage) {
|
||||
super(errorMessage);
|
||||
}
|
||||
|
||||
public VirtualFireAlarmException(String errorMessage, Throwable throwable) {
|
||||
super(errorMessage, throwable);
|
||||
}
|
||||
}
|
@ -1,226 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.transport;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.exception.VirtualFireAlarmException;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.VerificationManager;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.VirtualFireAlarmServiceUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Calendar;
|
||||
import java.util.UUID;
|
||||
|
||||
@SuppressWarnings("no JAX-WS annotation")
|
||||
public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler {
|
||||
private static Log log = LogFactory.getLog(VirtualFireAlarmMQTTConnector.class);
|
||||
|
||||
private static String serverName = DeviceManagementConfigurationManager.getInstance().
|
||||
getDeviceManagementServerInfo().getName();
|
||||
|
||||
private static String subscribeTopic = serverName + File.separator + "+" + File.separator +
|
||||
VirtualFireAlarmConstants.DEVICE_TYPE + File.separator + "+" + File.separator + "publisher";
|
||||
|
||||
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
|
||||
|
||||
private VirtualFireAlarmMQTTConnector() {
|
||||
super(iotServerSubscriber, VirtualFireAlarmConstants.DEVICE_TYPE,
|
||||
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect() {
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
while (!isConnected()) {
|
||||
try {
|
||||
connectToQueue();
|
||||
subscribeToQueue();
|
||||
} catch (TransportHandlerException e) {
|
||||
log.warn("Connection/Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed");
|
||||
try {
|
||||
Thread.sleep(timeoutInterval);
|
||||
} catch (InterruptedException ex) {
|
||||
log.error("MQTT-Subscriber: Thread Sleep Interrupt Exception.", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread connectorThread = new Thread(connector);
|
||||
connectorThread.setDaemon(true);
|
||||
connectorThread.start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage(MqttMessage mqttMessage, String... messageParams) {
|
||||
String topic = messageParams[0];
|
||||
String ownerAndId = topic.replace(serverName + File.separator, "");
|
||||
ownerAndId = ownerAndId.replace(File.separator + VirtualFireAlarmConstants.DEVICE_TYPE + File.separator, ":");
|
||||
ownerAndId = ownerAndId.replace(File.separator + "publisher", "");
|
||||
|
||||
String owner = ownerAndId.split(":")[0];
|
||||
String deviceId = ownerAndId.split(":")[1];
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Received MQTT message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}");
|
||||
}
|
||||
|
||||
String actualMessage;
|
||||
|
||||
try {
|
||||
PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
|
||||
PrivateKey serverPrivateKey = VerificationManager.getServerPrivateKey();
|
||||
actualMessage = VirtualFireAlarmServiceUtils.extractMessageFromPayload(mqttMessage.toString(),
|
||||
serverPrivateKey, clientPublicKey);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("MQTT: Received Message [" + actualMessage + "] topic: [" + topic + "]");
|
||||
}
|
||||
|
||||
if (actualMessage.contains("PUBLISHER")) {
|
||||
float temperature = Float.parseFloat(actualMessage.split(":")[2]);
|
||||
|
||||
if (!VirtualFireAlarmServiceUtils.publishToDAS(owner, deviceId, temperature)) {
|
||||
log.error("MQTT Subscriber: Publishing data to DAS failed.");
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("MQTT Subscriber: Published data to DAS successfully.");
|
||||
}
|
||||
|
||||
} else if (actualMessage.contains("TEMPERATURE")) {
|
||||
String temperatureValue = actualMessage.split(":")[1];
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId, VirtualFireAlarmConstants.SENSOR_TEMP,
|
||||
temperatureValue,
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
}
|
||||
} catch (VirtualFireAlarmException e) {
|
||||
String errorMsg =
|
||||
"CertificateManagementService failure oo Signature-Verification/Decryption was unsuccessful.";
|
||||
log.error(errorMsg, e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(String... publishData) throws TransportHandlerException {
|
||||
if (publishData.length != 4) {
|
||||
String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " +
|
||||
"Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]";
|
||||
log.error(errorMsg);
|
||||
throw new TransportHandlerException(errorMsg);
|
||||
}
|
||||
|
||||
String deviceOwner = publishData[0];
|
||||
String deviceId = publishData[1];
|
||||
String resource = publishData[2];
|
||||
String state = publishData[3];
|
||||
|
||||
MqttMessage pushMessage = new MqttMessage();
|
||||
String publishTopic =
|
||||
serverName + File.separator + deviceOwner + File.separator +
|
||||
VirtualFireAlarmConstants.DEVICE_TYPE + File.separator + deviceId;
|
||||
|
||||
try {
|
||||
PublicKey devicePublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
|
||||
PrivateKey serverPrivateKey = VerificationManager.getServerPrivateKey();
|
||||
|
||||
String actualMessage = resource + ":" + state;
|
||||
String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage,
|
||||
devicePublicKey,
|
||||
serverPrivateKey);
|
||||
|
||||
pushMessage.setPayload(encryptedMsg.getBytes(StandardCharsets.UTF_8));
|
||||
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
|
||||
pushMessage.setRetained(false);
|
||||
|
||||
publishToQueue(publishTopic, pushMessage);
|
||||
|
||||
} catch (VirtualFireAlarmException e) {
|
||||
String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "] of owner - " +
|
||||
"[" + deviceOwner + "].";
|
||||
log.error(errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
Runnable stopConnection = new Runnable() {
|
||||
public void run() {
|
||||
while (isConnected()) {
|
||||
try {
|
||||
closeConnection();
|
||||
} catch (MqttException e) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
|
||||
+ " for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE, e);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(timeoutInterval);
|
||||
} catch (InterruptedException e1) {
|
||||
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " +
|
||||
VirtualFireAlarmConstants.DEVICE_TYPE, e1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread terminatorThread = new Thread(stopConnection);
|
||||
terminatorThread.setDaemon(true);
|
||||
terminatorThread.start();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void publishDeviceData() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage() {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
}
|
@ -1,287 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.transport;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.jivesoftware.smack.packet.Message;
|
||||
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
|
||||
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
|
||||
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
|
||||
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
|
||||
import org.wso2.carbon.device.mgt.iot.transport.xmpp.XMPPTransportHandler;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.exception.VirtualFireAlarmException;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.VerificationManager;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.VirtualFireAlarmServiceUtils;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.util.Calendar;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@SuppressWarnings("no JAX-WS annotation")
|
||||
public class VirtualFireAlarmXMPPConnector extends XMPPTransportHandler {
|
||||
private static Log log = LogFactory.getLog(VirtualFireAlarmXMPPConnector.class);
|
||||
|
||||
private static String xmppServerIP;
|
||||
private static String xmppVFireAlarmAdminUsername;
|
||||
private static String xmppVFireAlarmAdminAccountJID;
|
||||
private static final String V_FIREALARM_XMPP_PASSWORD = "vfirealarm@123";
|
||||
private ScheduledFuture<?> connectorServiceHandler;
|
||||
private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
|
||||
|
||||
private VirtualFireAlarmXMPPConnector() {
|
||||
super(XmppConfig.getInstance().getXmppServerIP(), XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
|
||||
}
|
||||
|
||||
public void initConnector() {
|
||||
String serverName =
|
||||
DeviceManagementConfigurationManager.getInstance().getDeviceManagementServerInfo().getName();
|
||||
xmppVFireAlarmAdminUsername = serverName + "_" + VirtualFireAlarmConstants.DEVICE_TYPE;
|
||||
|
||||
xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
|
||||
xmppVFireAlarmAdminAccountJID = xmppVFireAlarmAdminUsername + "@" + xmppServerIP;
|
||||
createXMPPAccountForDeviceType();
|
||||
}
|
||||
|
||||
public void createXMPPAccountForDeviceType() {
|
||||
boolean accountExists = false;
|
||||
XmppServerClient xmppServerClient = new XmppServerClient();
|
||||
xmppServerClient.initControlQueue();
|
||||
|
||||
try {
|
||||
accountExists = xmppServerClient.doesXMPPUserAccountExist(xmppVFireAlarmAdminUsername);
|
||||
} catch (DeviceControllerException e) {
|
||||
String errorMsg = "An error was encountered whilst trying to check whether Server XMPP account exists " +
|
||||
"for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE;
|
||||
log.error(errorMsg, e);
|
||||
}
|
||||
|
||||
if (!accountExists) {
|
||||
XmppAccount xmppAccount = new XmppAccount();
|
||||
|
||||
xmppAccount.setAccountName(xmppVFireAlarmAdminUsername);
|
||||
xmppAccount.setUsername(xmppVFireAlarmAdminUsername);
|
||||
xmppAccount.setPassword(V_FIREALARM_XMPP_PASSWORD);
|
||||
xmppAccount.setEmail("");
|
||||
|
||||
try {
|
||||
boolean xmppCreated = xmppServerClient.createXMPPAccount(xmppAccount);
|
||||
if (!xmppCreated) {
|
||||
log.warn("Server XMPP Account was not created for device-type - " +
|
||||
VirtualFireAlarmConstants.DEVICE_TYPE +
|
||||
". Check whether XMPP is enabled in \"devicemgt-config.xml\" & restart.");
|
||||
} else {
|
||||
log.info("Server XMPP Account [" + xmppVFireAlarmAdminUsername +
|
||||
"] was not created for device-type - " + VirtualFireAlarmConstants.DEVICE_TYPE);
|
||||
}
|
||||
} catch (DeviceControllerException e) {
|
||||
String errorMsg =
|
||||
"An error was encountered whilst trying to create Server XMPP account for device-type - "
|
||||
+ VirtualFireAlarmConstants.DEVICE_TYPE;
|
||||
log.error(errorMsg, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void connect() {
|
||||
Runnable connector = new Runnable() {
|
||||
public void run() {
|
||||
if (!isConnected()) {
|
||||
try {
|
||||
connectToServer();
|
||||
loginToServer(xmppVFireAlarmAdminUsername, V_FIREALARM_XMPP_PASSWORD, null);
|
||||
setFilterOnReceiver(xmppVFireAlarmAdminAccountJID);
|
||||
|
||||
} catch (TransportHandlerException e) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.warn("Connection/Login to XMPP server at: " + server + " as " +
|
||||
xmppVFireAlarmAdminUsername + " failed for device-type [" +
|
||||
VirtualFireAlarmConstants.DEVICE_TYPE + "].", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
connectorServiceHandler = service.scheduleAtFixedRate(connector, 0, timeoutInterval, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage(Message xmppMessage) throws TransportHandlerException {
|
||||
String from = xmppMessage.getFrom();
|
||||
String subject = xmppMessage.getSubject();
|
||||
String message = xmppMessage.getBody();
|
||||
|
||||
int indexOfAt = from.indexOf("@");
|
||||
int indexOfSlash = from.indexOf("/");
|
||||
|
||||
if (indexOfAt != -1 && indexOfSlash != -1) {
|
||||
String deviceId = from.substring(0, indexOfAt);
|
||||
String owner = from.substring(indexOfSlash + 1, from.length());
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Received XMPP message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
PublicKey clientPublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
|
||||
PrivateKey serverPrivateKey = VerificationManager.getServerPrivateKey();
|
||||
String actualMessage = VirtualFireAlarmServiceUtils.extractMessageFromPayload(message, serverPrivateKey,
|
||||
clientPublicKey);
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("XMPP: Received Message [" + actualMessage + "] from: [" + from + "]");
|
||||
}
|
||||
|
||||
if (subject != null) {
|
||||
switch (subject) {
|
||||
case "PUBLISHER":
|
||||
float temperature = Float.parseFloat(actualMessage.split(":")[1]);
|
||||
if (!VirtualFireAlarmServiceUtils.publishToDAS(owner, deviceId, temperature)) {
|
||||
log.error("XMPP Connector: Publishing VirtualFirealarm data to DAS failed.");
|
||||
}
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("XMPP: Publisher Message [" + actualMessage + "] from [" + from + "] " +
|
||||
"was successfully published to DAS");
|
||||
}
|
||||
break;
|
||||
|
||||
case "CONTROL-REPLY":
|
||||
String tempVal = actualMessage.split(":")[1];
|
||||
SensorDataManager.getInstance().setSensorRecord(deviceId,
|
||||
VirtualFireAlarmConstants.SENSOR_TEMP,
|
||||
tempVal,
|
||||
Calendar.getInstance().getTimeInMillis());
|
||||
break;
|
||||
|
||||
default:
|
||||
if (log.isDebugEnabled()) {
|
||||
log.warn("Unknown XMPP Message [" + actualMessage + "] from [" + from + "] received");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (VirtualFireAlarmException e) {
|
||||
String errorMsg =
|
||||
"CertificateManagementService failure oo Signature-Verification/Decryption was unsuccessful.";
|
||||
log.error(errorMsg, e);
|
||||
}
|
||||
} else {
|
||||
log.warn("Received XMPP message from client with unexpected JID [" + from + "].");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(String... publishData) throws TransportHandlerException {
|
||||
if (publishData.length != 4) {
|
||||
String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " +
|
||||
"Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]";
|
||||
log.error(errorMsg);
|
||||
throw new TransportHandlerException(errorMsg);
|
||||
}
|
||||
|
||||
String deviceOwner = publishData[0];
|
||||
String deviceId = publishData[1];
|
||||
String resource = publishData[2];
|
||||
String state = publishData[3];
|
||||
|
||||
try {
|
||||
PublicKey devicePublicKey = VirtualFireAlarmServiceUtils.getDevicePublicKey(deviceId);
|
||||
PrivateKey serverPrivateKey = VerificationManager.getServerPrivateKey();
|
||||
|
||||
String actualMessage = resource + ":" + state;
|
||||
String encryptedMsg = VirtualFireAlarmServiceUtils.prepareSecurePayLoad(actualMessage,
|
||||
devicePublicKey,
|
||||
serverPrivateKey);
|
||||
|
||||
String clientToConnect = deviceId + "@" + xmppServerIP + File.separator + deviceOwner;
|
||||
sendXMPPMessage(clientToConnect, encryptedMsg, "CONTROL-REQUEST");
|
||||
|
||||
} catch (VirtualFireAlarmException e) {
|
||||
String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "] of owner - " +
|
||||
"[" + deviceOwner + "].";
|
||||
log.error(errorMsg);
|
||||
throw new TransportHandlerException(errorMsg, e);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void disconnect() {
|
||||
Runnable stopConnection = new Runnable() {
|
||||
public void run() {
|
||||
while (isConnected()) {
|
||||
connectorServiceHandler.cancel(true);
|
||||
closeConnection();
|
||||
if (log.isDebugEnabled()) {
|
||||
log.warn("Unable to 'STOP' connection to XMPP server at: " + server +
|
||||
" for user - " + xmppVFireAlarmAdminUsername);
|
||||
}
|
||||
|
||||
try {
|
||||
Thread.sleep(timeoutInterval);
|
||||
} catch (InterruptedException e1) {
|
||||
log.error("XMPP-Terminator: Thread Sleep Interrupt Exception for "
|
||||
+ VirtualFireAlarmConstants.DEVICE_TYPE + " type.", e1);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Thread terminatorThread = new Thread(stopConnection);
|
||||
terminatorThread.setDaemon(true);
|
||||
terminatorThread.start();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage(Message message, String... messageParams) throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void processIncomingMessage() throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData() throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
|
||||
@Override
|
||||
public void publishDeviceData(Message publishData) throws TransportHandlerException {
|
||||
// nothing to do
|
||||
}
|
||||
}
|
||||
|
@ -1,254 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
|
||||
import org.wso2.carbon.certificate.mgt.core.util.ConfigurationUtil;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.exception.VirtualFireAlarmException;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.Key;
|
||||
import java.security.KeyStore;
|
||||
import java.security.KeyStoreException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.Signature;
|
||||
import java.security.SignatureException;
|
||||
import java.security.UnrecoverableKeyException;
|
||||
import java.security.cert.CertificateException;
|
||||
|
||||
|
||||
public class VerificationManager {
|
||||
private static final Log log = LogFactory.getLog(VerificationManager.class);
|
||||
|
||||
private static PrivateKey serverPrivateKey;
|
||||
private static final String SIGNATURE_ALG = "SHA1withRSA";
|
||||
private static final String CIPHER_PADDING = "RSA/ECB/PKCS1Padding";
|
||||
|
||||
private VerificationManager() {
|
||||
|
||||
}
|
||||
|
||||
public void initVerificationManager() {
|
||||
serverPrivateKey = retrievePrivateKey(ConfigurationUtil.CA_CERT_ALIAS,
|
||||
ConfigurationUtil.KEYSTORE_CA_CERT_PRIV_PASSWORD);
|
||||
}
|
||||
|
||||
public static PrivateKey retrievePrivateKey(String alias, String password){
|
||||
PrivateKey privateKey = null;
|
||||
InputStream inputStream = null;
|
||||
KeyStore keyStore;
|
||||
|
||||
try {
|
||||
keyStore = KeyStore.getInstance(ConfigurationUtil.getConfigEntry(ConfigurationUtil.CERTIFICATE_KEYSTORE));
|
||||
inputStream = new FileInputStream(ConfigurationUtil.getConfigEntry(
|
||||
ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE));
|
||||
|
||||
keyStore.load(inputStream, ConfigurationUtil.getConfigEntry(ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD)
|
||||
.toCharArray());
|
||||
|
||||
privateKey = (PrivateKey) (keyStore.getKey(ConfigurationUtil.getConfigEntry(alias),
|
||||
ConfigurationUtil.getConfigEntry(password).toCharArray()));
|
||||
|
||||
} catch (KeyStoreException e) {
|
||||
String errorMsg = "Could not load KeyStore of given type in [certificate-config.xml] file." ;
|
||||
log.error(errorMsg, e);
|
||||
} catch (FileNotFoundException e) {
|
||||
String errorMsg = "KeyStore file could not be loaded from path given in [certificate-config.xml] file.";
|
||||
log.error(errorMsg, e);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
String errorMsg = "Algorithm not found when loading KeyStore";
|
||||
log.error(errorMsg, e);
|
||||
} catch (CertificateException e) {
|
||||
String errorMsg = "CertificateException when loading KeyStore";
|
||||
log.error(errorMsg, e);
|
||||
} catch (IOException e) {
|
||||
String errorMsg = "Input output issue occurred when loading KeyStore";
|
||||
log.error(errorMsg, e);
|
||||
} catch (KeystoreException e) {
|
||||
String errorMsg = "An error occurred whilst trying load Configs for KeyStoreReader";
|
||||
log.error(errorMsg, e);
|
||||
} catch (UnrecoverableKeyException e) {
|
||||
String errorMsg = "Key is unrecoverable when retrieving CA private key";
|
||||
log.error(errorMsg, e);
|
||||
} finally {
|
||||
try {
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
log.error("Error closing KeyStore input stream", e);
|
||||
}
|
||||
}
|
||||
|
||||
return privateKey;
|
||||
}
|
||||
|
||||
public static PrivateKey getServerPrivateKey() {
|
||||
return serverPrivateKey;
|
||||
}
|
||||
|
||||
public static String encryptMessage(String message, Key encryptionKey) throws VirtualFireAlarmException {
|
||||
Cipher encrypter;
|
||||
byte[] cipherData;
|
||||
|
||||
try {
|
||||
encrypter = Cipher.getInstance(CIPHER_PADDING);
|
||||
encrypter.init(Cipher.ENCRYPT_MODE, encryptionKey);
|
||||
cipherData = encrypter.doFinal(message.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
String errorMsg = "Algorithm not found exception occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
String errorMsg = "No Padding error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (InvalidKeyException e) {
|
||||
String errorMsg = "InvalidKey exception occurred for encryptionKey \n[\n" + encryptionKey + "\n]\n";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (BadPaddingException e) {
|
||||
String errorMsg = "Bad Padding error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
String errorMsg = "Illegal blockSize error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
}
|
||||
|
||||
return Base64.encodeBase64String(cipherData);
|
||||
}
|
||||
|
||||
|
||||
public static String signMessage(String encryptedData, PrivateKey signatureKey) throws VirtualFireAlarmException {
|
||||
|
||||
Signature signature;
|
||||
String signedEncodedString;
|
||||
|
||||
try {
|
||||
signature = Signature.getInstance(SIGNATURE_ALG);
|
||||
signature.initSign(signatureKey);
|
||||
signature.update(Base64.decodeBase64(encryptedData));
|
||||
|
||||
byte[] signatureBytes = signature.sign();
|
||||
signedEncodedString = Base64.encodeBase64String(signatureBytes);
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (SignatureException e) {
|
||||
String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (InvalidKeyException e) {
|
||||
String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + signatureKey + "\n]\n";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
}
|
||||
|
||||
return signedEncodedString;
|
||||
}
|
||||
|
||||
|
||||
public static boolean verifySignature(String data, String signedData, PublicKey verificationKey)
|
||||
throws VirtualFireAlarmException {
|
||||
|
||||
Signature signature;
|
||||
boolean verified;
|
||||
|
||||
try {
|
||||
signature = Signature.getInstance(SIGNATURE_ALG);
|
||||
signature.initVerify(verificationKey);
|
||||
signature.update(Base64.decodeBase64(data));
|
||||
|
||||
verified = signature.verify(Base64.decodeBase64(signedData));
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
String errorMsg = "Algorithm not found exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (SignatureException e) {
|
||||
String errorMsg = "Signature exception occurred for Signature instance of [" + SIGNATURE_ALG + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (InvalidKeyException e) {
|
||||
String errorMsg = "InvalidKey exception occurred for signatureKey \n[\n" + verificationKey + "\n]\n";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
}
|
||||
|
||||
return verified;
|
||||
}
|
||||
|
||||
|
||||
public static String decryptMessage(String encryptedMessage, Key decryptKey) throws VirtualFireAlarmException {
|
||||
|
||||
Cipher decrypter;
|
||||
String decryptedMessage;
|
||||
|
||||
try {
|
||||
|
||||
decrypter = Cipher.getInstance(CIPHER_PADDING);
|
||||
decrypter.init(Cipher.DECRYPT_MODE, decryptKey);
|
||||
decryptedMessage = new String(decrypter.doFinal(Base64.decodeBase64(encryptedMessage)), StandardCharsets.UTF_8);
|
||||
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
String errorMsg = "Algorithm not found exception occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (NoSuchPaddingException e) {
|
||||
String errorMsg = "No Padding error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (InvalidKeyException e) {
|
||||
String errorMsg = "InvalidKey exception occurred for encryptionKey \n[\n" + decryptKey + "\n]\n";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (BadPaddingException e) {
|
||||
String errorMsg = "Bad Padding error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (IllegalBlockSizeException e) {
|
||||
String errorMsg = "Illegal blockSize error occurred for Cipher instance of [" + CIPHER_PADDING + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
}
|
||||
|
||||
return decryptedMessage;
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,312 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.concurrent.FutureCallback;
|
||||
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
|
||||
import org.apache.http.impl.nio.client.HttpAsyncClients;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
|
||||
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
|
||||
import org.wso2.carbon.context.PrivilegedCarbonContext;
|
||||
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
|
||||
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
|
||||
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.exception.VirtualFireAlarmException;
|
||||
|
||||
import javax.ws.rs.HttpMethod;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.ProtocolException;
|
||||
import java.net.URL;
|
||||
import java.security.Key;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
public class VirtualFireAlarmServiceUtils {
|
||||
private static final Log log = LogFactory.getLog(VirtualFireAlarmServiceUtils.class);
|
||||
|
||||
//TODO; replace this tenant domain
|
||||
private static final String SUPER_TENANT = "carbon.super";
|
||||
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
|
||||
private static final String JSON_MESSAGE_KEY = "Msg";
|
||||
private static final String JSON_SIGNATURE_KEY = "Sig";
|
||||
|
||||
public static CertificateManagementService getCertificateManagementService() throws
|
||||
VirtualFireAlarmException {
|
||||
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
CertificateManagementService certificateManagementService = (CertificateManagementService)
|
||||
ctx.getOSGiService(CertificateManagementService.class, null);
|
||||
|
||||
if (certificateManagementService == null) {
|
||||
String msg = "EnrollmentService is not initialized";
|
||||
log.error(msg);
|
||||
throw new VirtualFireAlarmException(msg);
|
||||
}
|
||||
|
||||
return certificateManagementService;
|
||||
}
|
||||
|
||||
|
||||
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
|
||||
boolean fireAndForgot) throws DeviceManagementException {
|
||||
|
||||
String responseMsg = "";
|
||||
String urlString = VirtualFireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug(urlString);
|
||||
}
|
||||
|
||||
if (!fireAndForgot) {
|
||||
HttpURLConnection httpConnection = getHttpConnection(urlString);
|
||||
|
||||
try {
|
||||
httpConnection.setRequestMethod(HttpMethod.GET);
|
||||
} catch (ProtocolException e) {
|
||||
String errorMsg =
|
||||
"Protocol specific error occurred when trying to set method to GET" +
|
||||
" for:" + urlString;
|
||||
log.error(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, e);
|
||||
}
|
||||
|
||||
responseMsg = readResponseFromGetRequest(httpConnection);
|
||||
|
||||
} else {
|
||||
CloseableHttpAsyncClient httpclient = null;
|
||||
try {
|
||||
|
||||
httpclient = HttpAsyncClients.createDefault();
|
||||
httpclient.start();
|
||||
HttpGet request = new HttpGet(urlString);
|
||||
final CountDownLatch latch = new CountDownLatch(1);
|
||||
Future<HttpResponse> future = httpclient.execute(
|
||||
request, new FutureCallback<HttpResponse>() {
|
||||
@Override
|
||||
public void completed(HttpResponse httpResponse) {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void failed(Exception e) {
|
||||
latch.countDown();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancelled() {
|
||||
latch.countDown();
|
||||
}
|
||||
});
|
||||
|
||||
latch.await();
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Sync Interrupted");
|
||||
}
|
||||
} finally {
|
||||
try {
|
||||
if (httpclient != null) {
|
||||
httpclient.close();
|
||||
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Failed on close");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return responseMsg;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------------------
|
||||
Utility methods relevant to creating and sending http requests
|
||||
--------------------------------------------------------------------------------------- */
|
||||
|
||||
/* This methods creates and returns a http connection object */
|
||||
|
||||
public static HttpURLConnection getHttpConnection(String urlString) throws
|
||||
DeviceManagementException {
|
||||
|
||||
URL connectionUrl = null;
|
||||
HttpURLConnection httpConnection;
|
||||
|
||||
try {
|
||||
connectionUrl = new URL(urlString);
|
||||
httpConnection = (HttpURLConnection) connectionUrl.openConnection();
|
||||
} catch (MalformedURLException e) {
|
||||
String errorMsg =
|
||||
"Error occured whilst trying to form HTTP-URL from string: " + urlString;
|
||||
log.error(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, e);
|
||||
} catch (IOException e) {
|
||||
String errorMsg = "Error occured whilst trying to open a connection to: " +
|
||||
connectionUrl.toString();
|
||||
log.error(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, e);
|
||||
}
|
||||
|
||||
return httpConnection;
|
||||
}
|
||||
|
||||
/* This methods reads and returns the response from the connection */
|
||||
|
||||
public static String readResponseFromGetRequest(HttpURLConnection httpConnection)
|
||||
throws DeviceManagementException {
|
||||
BufferedReader bufferedReader;
|
||||
try {
|
||||
bufferedReader = new BufferedReader(new InputStreamReader(
|
||||
httpConnection.getInputStream()));
|
||||
} catch (IOException e) {
|
||||
String errorMsg =
|
||||
"There is an issue with connecting the reader to the input stream at: " +
|
||||
httpConnection.getURL();
|
||||
log.error(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, e);
|
||||
}
|
||||
|
||||
String responseLine;
|
||||
StringBuilder completeResponse = new StringBuilder();
|
||||
|
||||
try {
|
||||
while ((responseLine = bufferedReader.readLine()) != null) {
|
||||
completeResponse.append(responseLine);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
String errorMsg =
|
||||
"Error occured whilst trying read from the connection stream at: " +
|
||||
httpConnection.getURL();
|
||||
log.error(errorMsg);
|
||||
throw new DeviceManagementException(errorMsg, e);
|
||||
}
|
||||
try {
|
||||
bufferedReader.close();
|
||||
} catch (IOException e) {
|
||||
log.error(
|
||||
"Could not succesfully close the bufferedReader to the connection at: " +
|
||||
httpConnection.getURL());
|
||||
}
|
||||
|
||||
return completeResponse.toString();
|
||||
}
|
||||
|
||||
public static boolean publishToDAS(String owner, String deviceId, float temperature) {
|
||||
PrivilegedCarbonContext.startTenantFlow();
|
||||
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
ctx.setTenantDomain(SUPER_TENANT, true);
|
||||
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
|
||||
DeviceAnalyticsService.class, null);
|
||||
Object metdaData[] = {owner, VirtualFireAlarmConstants.DEVICE_TYPE, deviceId,
|
||||
System.currentTimeMillis()};
|
||||
Object payloadData[] = {temperature};
|
||||
|
||||
try {
|
||||
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
|
||||
new Object[0], payloadData);
|
||||
} catch (DataPublisherConfigurationException e) {
|
||||
return false;
|
||||
} finally {
|
||||
PrivilegedCarbonContext.endTenantFlow();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String prepareSecurePayLoad(String message, Key encryptionKey, PrivateKey signatureKey)
|
||||
throws VirtualFireAlarmException {
|
||||
String encryptedMsg = VerificationManager.encryptMessage(message, encryptionKey);
|
||||
String signedPayload = VerificationManager.signMessage(encryptedMsg, signatureKey);
|
||||
|
||||
JSONObject jsonPayload = new JSONObject();
|
||||
jsonPayload.put(JSON_MESSAGE_KEY, encryptedMsg);
|
||||
jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload);
|
||||
|
||||
return jsonPayload.toString();
|
||||
}
|
||||
|
||||
|
||||
public static String extractMessageFromPayload(String message, Key decryptionKey, PublicKey verifySignatureKey)
|
||||
throws VirtualFireAlarmException {
|
||||
String actualMessage;
|
||||
|
||||
JSONObject jsonPayload = new JSONObject(message);
|
||||
Object encryptedMessage = jsonPayload.get(JSON_MESSAGE_KEY);
|
||||
Object signedPayload = jsonPayload.get(JSON_SIGNATURE_KEY);
|
||||
|
||||
if (encryptedMessage != null && signedPayload != null) {
|
||||
if (VerificationManager.verifySignature(
|
||||
encryptedMessage.toString(), signedPayload.toString(), verifySignatureKey)) {
|
||||
actualMessage = VerificationManager.decryptMessage(encryptedMessage.toString(), decryptionKey);
|
||||
} else {
|
||||
String errorMsg = "The message was not signed by a valid client. Could not verify signature on payload";
|
||||
throw new VirtualFireAlarmException(errorMsg);
|
||||
}
|
||||
} else {
|
||||
String errorMsg = "The received message is in an INVALID format. " +
|
||||
"Need to be JSON - {\"Msg\":\"<ENCRYPTED_MSG>\", \"Sig\":\"<SIGNED_MSG>\"}.";
|
||||
throw new VirtualFireAlarmException(errorMsg);
|
||||
}
|
||||
|
||||
return actualMessage;
|
||||
}
|
||||
|
||||
|
||||
public static PublicKey getDevicePublicKey(String deviceId) throws VirtualFireAlarmException {
|
||||
PublicKey clientPublicKey;
|
||||
String alias = "";
|
||||
|
||||
try {
|
||||
alias += deviceId.hashCode();
|
||||
|
||||
CertificateManagementService certificateManagementService =
|
||||
VirtualFireAlarmServiceUtils.getCertificateManagementService();
|
||||
X509Certificate clientCertificate = (X509Certificate) certificateManagementService.getCertificateByAlias(
|
||||
alias);
|
||||
clientPublicKey = clientCertificate.getPublicKey();
|
||||
|
||||
} catch (VirtualFireAlarmException e) {
|
||||
String errorMsg = "Could not retrieve CertificateManagementService from the runtime.";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
} catch (KeystoreException e) {
|
||||
String errorMsg = "An error occurred whilst trying to retrieve certificate for deviceId [" + deviceId +
|
||||
"] with alias: [" + alias + "]";
|
||||
log.error(errorMsg);
|
||||
throw new VirtualFireAlarmException(errorMsg, e);
|
||||
}
|
||||
return clientPublicKey;
|
||||
}
|
||||
|
||||
}
|
@ -1,26 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.scep;
|
||||
|
||||
public class ContentType {
|
||||
public static final String X_PKI_MESSAGE = "application/x-pki-message";
|
||||
public static final String X_X509_CA_CERT = "application/x-x509-ca-cert";
|
||||
public static final String X_X509_CA_RA_CERT = "application/x-x509-ca-ra-cert";
|
||||
}
|
||||
|
@ -1,39 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.util.scep;
|
||||
|
||||
public enum SCEPOperation {
|
||||
GET_CA_CERT("GetCACert"),
|
||||
GET_CA_CAPS("GetCACaps"),
|
||||
PKI_OPERATION("PKIOperation");
|
||||
|
||||
private String value;
|
||||
|
||||
private SCEPOperation(String value) {
|
||||
this.setValue(value);
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
}
|
Loading…
Reference in new issue