Adding plugins and samples to the distribution.

application-manager-new
sinthuja 8 years ago
parent f5378f61e9
commit d8bb6d6e3c

@ -619,6 +619,23 @@
<exclude>**/nimbus-jose-jwt_2.26.1.wso2v2.jar</exclude>
</excludes>
</fileSet>
<fileSet>
<directory>src/core/plugins</directory>
<outputDirectory>${pom.artifactId}-${pom.version}/plugins</outputDirectory>
<includes>
<include>*/**</include>
</includes>
</fileSet>
<fileSet>
<directory>src/core/samples</directory>
<outputDirectory>${pom.artifactId}-${pom.version}/samples</outputDirectory>
<includes>
<include>*/**</include>
</includes>
<fileMode>644</fileMode>
</fileSet>
<!-- ********************************* End of IoT Core Profile ********************************* -->
<!-- ********************************* Start of Analytics Profile ********************************* -->

@ -0,0 +1,212 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2</groupId>
<artifactId>wso2</artifactId>
<version>1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>org.wso2.iot.devicemgt-plugins</groupId>
<artifactId>iot-devicetype-feature-installation</artifactId>
<version>3.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Creating custom distribution</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<id>2-p2-repo-generation</id>
<phase>package</phase>
<goals>
<goal>p2-repo-gen</goal>
</goals>
<configuration>
<metadataRepository>file:${basedir}/target/p2-repo</metadataRepository>
<artifactRepository>file:${basedir}/target/p2-repo</artifactRepository>
<publishArtifacts>true</publishArtifacts>
<publishArtifactRepository>true</publishArtifactRepository>
<featureArtifacts>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.androidsense.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.arduino.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.raspberrypi.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature:${carbon.device.mgt.plugin.version}
</featureArtifactDef>
</featureArtifacts>
</configuration>
</execution>
<execution>
<id>default-feature-install</id>
<phase>package</phase>
<goals>
<goal>p2-profile-gen</goal>
</goals>
<configuration>
<profile>default</profile>
<metadataRepository>file:${basedir}/target/p2-repo</metadataRepository>
<artifactRepository>file:${basedir}/target/p2-repo</artifactRepository>
<destination>${basedir}/../wso2/components</destination>
<deleteOldProfileFiles>false</deleteOldProfileFiles>
<features>
<feature>
<id>org.wso2.carbon.device.mgt.iot.androidsense.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.arduino.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.raspberrypi.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature.group</id>
<version>${carbon.device.mgt.plugin.version}</version>
</feature>
</features>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<id>default-feature-install</id>
<phase>package</phase>
<configuration>
<tasks>
<copy todir="../wso2/analytics/repository/deployment/server/carbonapps">
<fileset dir="../repository/resources/devicetypes">
<include name="*.car"/>
</fileset>
</copy>
<copy todir="../wso2/analytics/repository/deployment/server/">
<fileset dir="resources/analytics">
<include name="**/*"/>
</fileset>
</copy>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
Ideally the Axis2 build should only use Maven central (which is available
by default) and nothing else. We had troubles with other repositories in
the past. Therefore configuring additional repositories here should be
considered very carefully. -->
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.snapshots</id>
<name>WSO2 Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<properties>
<carbon.device.mgt.plugin.version>3.0.13-SNAPSHOT</carbon.device.mgt.plugin.version>
</properties>
</project>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>activity_data.csv</file>
<streamID>org.wso2.iot.android.activity:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>audio_data.csv</file>
<streamID>org.wso2.iot.android.audio:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>battery_data.csv</file>
<streamID>org.wso2.iot.android.battery:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>call_data.csv</file>
<streamID>org.wso2.iot.android.call:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>location_data.csv</file>
<streamID>org.wso2.iot.android.location:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>network_data.csv</file>
<streamID>org.wso2.iot.android.data:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>screen_data.csv</file>
<streamID>org.wso2.iot.android.screen:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<streamConfiguration type="csv">
<file>sms_data.csv</file>
<streamID>org.wso2.iot.android.sms:1.0.0</streamID>
<separateChar>,</separateChar>
<delayBetweenEventsInMilies>1000</delayBetweenEventsInMilies>
</streamConfiguration>

@ -0,0 +1,155 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.coffeeking</groupId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.agent</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Agent Web app</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>connected-cup-agent</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<pluginRepositories>
<pluginRepository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
Ideally the Axis2 build should only use Maven central (which is available
by default) and nothing else. We had troubles with other repositories in
the past. Therefore configuring additional repositories here should be
considered very carefully. -->
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.snapshots</id>
<name>WSO2 Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
</project>

@ -0,0 +1,67 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.agent.datasense;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.agent.transport.TransportHandlerException;
import org.coffeeking.agent.transport.mqtt.ConnectedCupMQttTransportHandler;
import org.json.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StreamCorruptedException;
public class PushLevel extends HttpServlet {
private static final Log log = LogFactory.getLog(PushLevel.class);
private ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler;
public PushLevel() {
connectedCupMQttTransportHandler = ConnectedCupMQttTransportHandler.getInstance();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String deviceId = req.getParameter("deviceId");
String tenantDomain = req.getParameter("tenantDomain");
String deviceOwner = req.getParameter("deviceOwner");
String payload = req.getParameter("payload");
payload = " {\"event\": {\"metaData\": {\"owner\": \"" + deviceOwner +
"\", \"type\": \"coffeelevel\",\"deviceId\": " +
"\"" + deviceId + "\",\"timestamp\": " + System.currentTimeMillis() +
"},\"payloadData\": { \"coffeelevel\": " + Float.parseFloat(payload) + ", \"temperature\": 0} }}";
String token = (String) req.getSession().getAttribute("token");
if (!connectedCupMQttTransportHandler.isConnected()) {
connectedCupMQttTransportHandler.setToken(token);
connectedCupMQttTransportHandler.connect();
}
try {
if (connectedCupMQttTransportHandler.isConnected()) {
connectedCupMQttTransportHandler.publishToConnectedCup(deviceOwner, deviceId, payload, tenantDomain, 0,
true);
}
} catch (TransportHandlerException e) {
log.error(e);
resp.sendError(500);
}
}
}

@ -0,0 +1,66 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.agent.datasense;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.agent.transport.TransportHandlerException;
import org.coffeeking.agent.transport.mqtt.ConnectedCupMQttTransportHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class PushTemperature extends HttpServlet {
private static final Log log = LogFactory.getLog(PushTemperature.class);
private ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler;
public PushTemperature() {
connectedCupMQttTransportHandler = ConnectedCupMQttTransportHandler.getInstance();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String deviceId = req.getParameter("deviceId");
String tenantDomain = req.getParameter("tenantDomain");
String payload = req.getParameter("payload");
String deviceOwner = req.getParameter("deviceOwner");
payload = " {\"event\": {\"metaData\": {\"owner\": \"" + deviceOwner +
"\", \"type\": \"temperature\",\"deviceId\": " +
"\"" + deviceId + "\",\"timestamp\": " + System.currentTimeMillis() +
"},\"payloadData\": { \"temperature\": " + Float.parseFloat(payload) + ", \"coffeelevel\": 0} }}";
String token = (String) req.getSession().getAttribute("token");
if (!connectedCupMQttTransportHandler.isConnected()) {
connectedCupMQttTransportHandler.setToken(token);
connectedCupMQttTransportHandler.connect();
}
try {
if (connectedCupMQttTransportHandler.isConnected()) {
connectedCupMQttTransportHandler.publishToConnectedCup(deviceOwner, deviceId, payload, tenantDomain, 0,
true);
}
} catch (TransportHandlerException e) {
log.error(e);
resp.sendError(500);
}
}
}

@ -0,0 +1,50 @@
/*
* 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.coffeeking.agent.transport;
/**
* This interface consists of the core functionality related to the transport between any device and the server. The
* interface is an abstraction, regardless of the underlying protocol used for the transport. Implementation of this
* interface by any class that caters a specific protocol (ex: HTTP, XMPP, MQTT, CoAP) would ideally have methods
* specific to the protocol used for communication and thees methods that implement the logic related to the devices
* using the protocol.
*
* @param <T> a message type specific to the protocol implemented
*/
public interface TransportHandler<T> {
int DEFAULT_TIMEOUT_INTERVAL = 5000; // millis ~ 10 sec
void connect();
boolean isConnected();
void processIncomingMessage() throws TransportHandlerException;
void processIncomingMessage(T message) throws TransportHandlerException;
void processIncomingMessage(T message, String... messageParams) throws TransportHandlerException;
void publishDeviceData() throws TransportHandlerException;
void publishDeviceData(T publishData) throws TransportHandlerException;
void publishDeviceData(String... publishData) throws TransportHandlerException;
void disconnect();
}

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

@ -0,0 +1,160 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.agent.transport.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.agent.transport.TransportHandlerException;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.ScheduledFuture;
public class ConnectedCupMQttTransportHandler extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(ConnectedCupMQttTransportHandler.class);
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private static final String DEVICE_TYPE = "connectedcup";
private static ConnectedCupMQttTransportHandler connectedCupMQttTransportHandler;
private static String publishTopic = "%s/" + DEVICE_TYPE + "/%s";
protected ConnectedCupMQttTransportHandler() {
super(iotServerSubscriber, DEVICE_TYPE, "tcp://localhost:1886", "");
}
private ScheduledFuture<?> dataPushServiceHandler;
public ScheduledFuture<?> getDataPushServiceHandler() {
return dataPushServiceHandler;
}
public void setToken(String token) {
setUsernameAndPassword(token, "");
}
@Override
public void connect() {
Runnable connect = new Runnable() {
@Override
public void run() {
log.info("Trying to connect..");
while (!isConnected()) {
try {
connectToQueue();
} catch (TransportHandlerException e) {
log.warn("Connection to MQTT Broker at: " +
mqttBrokerEndPoint + " failed");
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Subscriber: Thread Sleep Interrupt Exception");
}
}
}
log.info("Connected..");
}
};
Thread connectorThread = new Thread(connect);
connectorThread.start();
}
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
}
public void publishToConnectedCup(String deviceOwner , String deviceId, String payLoad, String tenantDomain, int qos, boolean retained)
throws TransportHandlerException{
String topic = String.format(publishTopic, tenantDomain, deviceId);
publishToQueue(topic, payLoad, qos, retained);
}
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
try {
dataPushServiceHandler.cancel(true);
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " +
mqttBrokerEndPoint);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception");
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.start();
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
@Override
public void processIncomingMessage() {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
public static ConnectedCupMQttTransportHandler getInstance(){
if(connectedCupMQttTransportHandler == null){
connectedCupMQttTransportHandler = new ConnectedCupMQttTransportHandler();
}
return connectedCupMQttTransportHandler;
}
}

@ -0,0 +1,372 @@
/*
* 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.coffeeking.agent.transport.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.agent.transport.TransportHandler;
import org.coffeeking.agent.transport.TransportHandlerException;
import org.eclipse.paho.client.mqttv3.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
/**
* This is an abstract class that implements the "TransportHandler" interface. The interface is an abstraction for
* the core functionality with regards to device-server communication regardless of the Transport protocol. This
* specific class contains the HTTP-Transport specific implementations. The class implements utility methods for the
* case of a HTTP communication. However, this "abstract class", even-though it implements the "TransportHandler"
* interface, does not contain the logic relevant to the interface methods. The specific functionality of the
* interface methods are intended to be implemented by the concrete class that extends this abstract class and
* utilizes the HTTP specific functionality (ideally a device API writer who would like to communicate to the device
* via HTTP Protocol).
* <p/>
* This class contains the Device-Management 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.
*/
public abstract class MQTTTransportHandler
implements MqttCallback, TransportHandler<MqttMessage> {
private static final Log log = LogFactory.getLog(MQTTTransportHandler.class);
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
private MqttClient client;
private String clientId;
private MqttConnectOptions options;
private String clientWillTopic;
protected String mqttBrokerEndPoint;
protected int timeoutInterval;
protected String subscribeTopic;
/**
* Constructor for the MQTTTransportHandler which takes in the owner, type of the device
* and the MQTT Broker URL and the topic to subscribe.
*
* @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
*/
protected MQTTTransportHandler(String deviceOwner, String deviceType,
String mqttBrokerEndPoint,
String subscribeTopic) {
this.clientId = deviceOwner + ":" + deviceType;
this.subscribeTopic = subscribeTopic;
this.clientWillTopic = deviceType + File.separator + "disconnection";
this.mqttBrokerEndPoint = mqttBrokerEndPoint;
this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL;
this.initSubscriber();
}
/**
* Constructor for the MQTTTransportHandler 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 intervalInMillis the time interval in MILLI-SECONDS between successive
* attempts to connect to the broker.
*/
protected MQTTTransportHandler(String deviceOwner, String deviceType,
String mqttBrokerEndPoint, String subscribeTopic,
int intervalInMillis) {
this.clientId = deviceOwner + ":" + deviceType;
this.subscribeTopic = subscribeTopic;
//TODO:: Use constant strings
this.clientWillTopic = deviceType + File.separator + "disconnection";
this.mqttBrokerEndPoint = mqttBrokerEndPoint;
this.timeoutInterval = intervalInMillis;
this.initSubscriber();
}
public void setUsernameAndPassword (String username, String password) {
options.setUserName(username);
options.setPassword(password.toCharArray());
}
public void setTimeoutInterval(int timeoutInterval) {
this.timeoutInterval = timeoutInterval;
}
/**
* 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() {
try {
client = new MqttClient(this.mqttBrokerEndPoint, clientId, null);
//TODO:: Need to check for debug
log.info("MQTT subscriber was created with ClientID : " + clientId);
} catch (MqttException ex) {
//TODO:: Remove unnecessary formatting and print exception
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);
//TODO:: Throw the error out
}
options = new MqttConnectOptions();
options.setCleanSession(true);
//TODO:: Use constant strings
options.setWill(clientWillTopic, "Connection-Lost".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.
*/
@Override
public boolean isConnected() {
return client.isConnected();
}
/**
* Connects to the MQTT-Broker and if successfully established connection.
*
* @throws TransportHandlerException in the event of 'Connecting to' the MQTT broker fails.
*/
protected void connectToQueue() throws TransportHandlerException {
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;
//TODO:: Compulsory log of errors and remove formatted error
if (log.isDebugEnabled()) {
log.debug(errorMsg);
}
throw new TransportHandlerException(errorMsg, ex);
} catch (MqttException ex) {
//TODO:: Compulsory log of errors and remove formatted error
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;
if (log.isDebugEnabled()) {
log.debug(errorMsg);
}
throw new TransportHandlerException(errorMsg, ex);
}
}
/**
* Subscribes to the MQTT-Topic specific to this MQTT Client. (The MQTT-Topic specific to the
* device is taken in as a constructor parameter of this class) .
*
* @throws TransportHandlerException in the event of 'Subscribing to' the MQTT broker
* fails.
*/
protected void subscribeToQueue() throws TransportHandlerException {
try {
//TODO:: QoS Level take it from a variable
client.subscribe(subscribeTopic, 0);
if (log.isDebugEnabled()) {
log.debug("Subscriber '" + clientId + "' subscribed to topic: " + subscribeTopic);
}
} catch (MqttException ex) {
//TODO:: Compulsory log of errors and remove formatted error
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 TransportHandlerException(errorMsg, ex);
}
}
/**
* This method is used to publish reply-messages for the control signals received.
* Invocation of this method calls its overloaded-method with a QoS equal to that of the
* default value.
*
* @param topic the topic to which the reply message is to be published.
* @param payLoad the reply-message (payload) of the MQTT publish action.
*/
protected void publishToQueue(String topic, String payLoad)
throws TransportHandlerException {
publishToQueue(topic, payLoad, DEFAULT_MQTT_QUALITY_OF_SERVICE, false);
}
/**
* This is an overloaded method that publishes MQTT reply-messages for control signals
* received form the IoT-Server.
*
* @param topic the topic to which the reply message is to be published
* @param payLoad the reply-message (payload) of the MQTT publish action.
* @param qos the Quality-of-Service of the current publish action.
* Could be 0(At-most once), 1(At-least once) or 2(Exactly once)
*/
protected void publishToQueue(String topic, String payLoad, int qos, boolean retained)
throws TransportHandlerException {
try {
client.publish(topic, payLoad.getBytes(StandardCharsets.UTF_8), qos, retained);
if (log.isDebugEnabled()) {
log.debug("Message: " + payLoad + " to MQTT topic [" + topic +
"] published successfully");
}
} 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.info(errorMsg);
throw new TransportHandlerException(errorMsg, ex);
}
}
protected void publishToQueue(String topic, MqttMessage message)
throws TransportHandlerException {
try {
client.publish(topic, message);
if (log.isDebugEnabled()) {
log.debug("Message: " + message.toString() + " to MQTT topic [" + topic +
"] published successfully");
}
} catch (MqttException ex) {
//TODO:: Compulsory log of errors and remove formatted error
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.info(errorMsg);
throw new TransportHandlerException(errorMsg, ex);
}
}
/**
* Callback method which is triggered once the MQTT client losers its connection to the broker.
* Spawns a new thread that executes necessary actions to try and reconnect to the endpoint.
*
* @param throwable a Throwable Object containing the details as to why the failure occurred.
*/
@Override
public void connectionLost(Throwable throwable) {
if (log.isDebugEnabled()) {
log.warn("Lost Connection for client: " + this.clientId + " to " + this.mqttBrokerEndPoint + "." +
"\nThis was due to - " + throwable.getMessage());
}
Thread reconnectThread = new Thread() {
public void run() {
connect();
}
};
reconnectThread.setDaemon(true);
reconnectThread.start();
}
/**
* 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) {
if (log.isDebugEnabled()) {
log.debug("Got an MQTT message '" + mqttMessage.toString() + "' for topic '" + topic + "'.");
}
Thread messageProcessorThread = new Thread() {
public void run() {
try {
processIncomingMessage(mqttMessage, topic);
} catch (TransportHandlerException e) {
log.error("An error occurred when trying to process received MQTT message [" + mqttMessage + "] " +
"for topic [" + topic + "].", e);
}
}
};
messageProcessorThread.setDaemon(true);
messageProcessorThread.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.
*/
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
String topic = iMqttDeliveryToken.getTopics()[0];
String client = iMqttDeliveryToken.getClient().getClientId();
try {
if (iMqttDeliveryToken.isComplete()) {
if (log.isDebugEnabled()) {
if (iMqttDeliveryToken.getMessage() != null) {
String message = iMqttDeliveryToken.getMessage().toString();
log.debug("Message to client [" + client + "] under topic (" + topic +
") was delivered successfully with the delivery message: '" + message + "'");
} else {
log.debug("Message to client [" + client + "] under topic (" + topic +
") was delivered successfully.");
}
}
} else {
log.warn("FAILED: Delivery of MQTT message to [" + client + "] under topic [" + topic + "] failed.");
}
} catch (MqttException e) {
//TODO:: Throw errors
log.error("Error occurred whilst trying to read the message from the MQTT delivery token.");
}
}
/**
* Closes the connection to the MQTT Broker.
*/
public void closeConnection() throws MqttException {
if (client != null && isConnected()) {
client.disconnect();
}
}
}

@ -0,0 +1,27 @@
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>ConnectedCup-Webapp</display-name>
<servlet>
<servlet-name>PushTemperature</servlet-name>
<servlet-class>org.coffeeking.agent.datasense.PushTemperature</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>PushTemperature</servlet-name>
<url-pattern>/push_temperature</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>PushLevel</servlet-name>
<servlet-class>org.coffeeking.agent.datasense.PushLevel</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>PushLevel</servlet-name>
<url-pattern>/push_level</url-pattern>
</servlet-mapping>
</web-app>

@ -0,0 +1,299 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
input[type=range][orient=vertical]
{
writing-mode: bt-lr; /* IE */
-webkit-appearance: slider-vertical; /* WebKit */
width: 8px;
height: 175px;
padding: 0 5px;
}
h1 {
padding-top: 10px;
text-align: center;
}
.left-pane{
float: left;
width: 30%;
text-align: center;
min-width: 325px;
}
.right-pane{
float: right;
background-color: rgba(204, 204, 204, 0.61);
width: 70%;
}
.coffee-wrapper{
margin: 10% 0 5% 10%;
text-align: center;
}
.coffee-top{
position: absolute;
bottom: 10px;
height: 30px;
width: 100%;
z-index: 99;
background-color: aquamarine;
}
.coffee-bottom{
position: absolute;
bottom: 0px;
height: 10px;
width: 100%;
z-index: 98;
background-color: aqua;
}
.handle {
position: absolute;
height: 200px;
width: 97px;
top: 39px;
left: -111px;
border-top-left-radius: 75px 100px;
border-bottom-left-radius: 75px 100px;
border-top-right-radius: 50% 20px;
border-bottom-right-radius: 50% 20px;
background: linear-gradient(to left, rgba(0, 0, 0, 0.01) 0%, rgba(0, 0, 0, 0.01) 100%);
background-color: rgba(255, 255, 255, 0.28);
border: 1px solid rgba(255, 255, 255, 0.25);
}
.handle:after {
content: "";
position: absolute;
height: 167px;
width: 76px;
top: 15px;
right: 0;
border-top-left-radius: 45px 70px;
border-bottom-left-radius: 45px 70px;
border-top-right-radius: 45px 35px;
border-bottom-right-radius: 45px 35px;
background: rgba(204, 204, 204, 0.3);
}
:before, :after {
content: '';
display: block;
position: absolute;
}
html, body {
height: 100%;
}
.coffee {
display: inline-block;
position: relative;
width: 300px;
margin: 0 20px 50px 0;
}
.coffee:after {
height: 14px;
width: 300px;
border-radius: 46px/10px;
box-shadow: 0px 1px 4px -2px rgba(0, 0, 0, 0.2), 0px 2px 10px -3px rgba(0, 0, 0, 0.1);
bottom: -7.6px;
z-index: 0;
}
.coffee:before {
height: 14px;
width: 300px;
border-radius: 46px/10px;
box-shadow: 0px 2px 10px -2px rgba(0, 204, 255, 0.3), 0px 2px 15px -2px rgba(0, 204, 255, 0.4);
bottom: -7.6px;
z-index: 0;
}
.coffee_main {
height: 300px;
position: relative;
width: 298px;
background: none;
border: 1px solid rgba(255, 255, 255, 0.5);
border-top: none;
border-bottom: none;
}
.coffee_main:after, .coffee_main:before {
height: 12px;
width: 296px;
border-radius: 46px/10px;
border: 2px solid rgba(255, 255, 255, 0.5);
border-bottom: 2px solid rgba(255, 255, 255, 0.7);
border-top: 1px solid rgba(255, 255, 255, 0.3);
left: -1px;
}
.coffee_main:after {
top: -7px;
box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.6) inset, 0px 3px 3px -1px rgba(255, 255, 255, 0.4), 0px 0px 3px rgba(0, 0, 0, 0.05) inset, 0px 0px 6px rgba(255, 255, 255, 0.7) inset, 0px 0px 3px rgba(0, 0, 0, 0.15) inset;
}
.coffee_main:before {
top: 294px;
box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.7) inset, 0px 0px 3px rgba(0, 0, 0, 0.15) inset;
}
.coffee_mouth {
height: 52px;
width: 44px;
margin: 0px auto;
position: relative;
background: none;
border: 1px solid rgba(0, 0, 0, 0.04);
border-top: none;
border-bottom: none;
background: linear-gradient(to right, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 5%, rgba(255, 255, 255, 0) 95%, rgba(255, 255, 255, 0.3));
box-shadow: 0px 0px 6px rgba(255, 255, 255, 0.3);
}
.coffee_mouth:after {
height: 6px;
width: 44px;
border-radius: 25px/6px;
border: 1px solid rgba(255, 255, 255, 0.4);
left: -1px;
top: -4px;
z-index: 1;
box-shadow: 0px 0px 3px rgba(255, 255, 255, 0.3);
}
.coffee_inner {
height: 295px;
width: 92%;
margin: 0px auto;
border-radius: 10px 10px 20px 20px/10px;
border: 1px solid rgba(0, 0, 0, 0.01);
border-top: 1px solid rgba(255, 255, 255, 0.3);
border-bottom-width: 0.5px;
position: relative;
box-shadow: 0px 0px 2px rgba(255, 255, 255, 0.5) inset, 0px 0px 8px rgba(255, 255, 255, 0.6) inset, 0px 0px 5px rgba(255, 255, 255, 0.5);
position: relative;
top: 1px;
}
.coffee_inner:before {
border-radius: 40px/4px;
top: 140px;
width: 90%;
left: 3px;
height: 9px;
}
.coffee_top .highlight {
display: block;
height: 30px;
width: 20px;
position: absolute;
left: 5px;
top: 5px;
transform: skew(0deg, 5deg);
background: linear-gradient(to right, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.6) 4%, rgba(255, 255, 255, 0.2) 98%, rgba(255, 255, 255, 0));
}
.coffee_top .highlight:after {
height: 30px;
width: 2px;
left: -3px;
top: -1px;
transform: skew(0deg, 5deg);
background: rgba(255, 255, 255, 0.3);
}
.coffee_main .highlight {
display: block;
height: 301px;
width: 25px;
position: absolute;
left: 10px;
top: 6px;
transform: skew(0deg, 6deg);
background: linear-gradient(to right, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.5) 4%, rgba(255, 255, 255, 0.2) 98%, rgba(255, 255, 255, 0));
z-index: 2;
}
.coffee_main .highlight:after {
height: 150px;
width: 4px;
left: -6px;
top: 0px;
transform: skew(0deg, 3deg);
background: linear-gradient(to bottom, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 80%);
}
.coffee_neck .highlight {
display: block;
height: 20px;
width: 25px;
position: absolute;
left: 2px;
top: 6px;
transform: skew(0deg, 6deg);
background: linear-gradient(to right, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.3) 4%, rgba(255, 255, 255, 0.1) 98%, rgba(255, 255, 255, 0));
}
.water {
background: linear-gradient(-85deg, rgba(167, 92, 24, 0.35), rgba(169, 108, 52, 0.55) 70%, rgba(185, 128, 76, 0.4));
width: 99%;
height: 80px;
position: absolute;
left: 1px;
bottom: 1px;
border-radius: 50px 50px 20px 20px/8px 8px 10px 10px;
box-shadow: 0px 0px 6px rgba(165, 117, 73, 0.5) inset, 0px 0.2px 3px -1px rgba(0, 0, 0, 0.3) inset, 0px 2px 6px -1px rgba(0, 0, 0, 0.1) inset, 0px 2px 5px rgba(190,155,123,0.3), 0px 1px 3px rgba(190,155,123,0.2);
}
.water:after {
height: 10px;
width: 100%;
left: -1px;
top: 0px;
background: linear-gradient(to right, rgba(255, 255, 255, 0.4), rgba(255, 127, 0, 0.05) 50%, rgba(251, 148, 0, 0.1) 80%, rgba(255, 255, 255, 0.3));
border-radius: 50px/8px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-bottom-color: rgba(255, 255, 255, 0.4);
box-shadow: 0px 1px 2px -1px rgba(165, 90, 26, 0.35);
}
.water:before {
height: 10px;
width: 100%;
left: 2px;
bottom: -1px;
background: linear-gradient(to right, rgba(190,155,123,0.2), rgba(190,155,123,0.1) 50%, rgba(190,155,123,0.2) 80%, rgba(190,155,123,0.3));
border-radius: 50px/10px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-bottom: none;
box-shadow: 0px -2px 3px -1px rgba(190,155,123,0.25);
}
.water {
height: 0px;
-webkit-transition: all 3s ease-out;
-moz-transition: all 3s ease-out;
-o-transition: all 3s ease-out;
transition: all 3s ease-out;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}

@ -0,0 +1,134 @@
<%--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
--%>
<html>
<head>
<title>Connected Coffee Cup</title>
<link rel="stylesheet" href="css/coffee.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<%
String deviceId = request.getParameter("deviceId");
if (deviceId != null) {
request.getSession().setAttribute("deviceId", deviceId);
}
String deviceOwner = request.getParameter("deviceOwner");
if (deviceOwner != null) {
request.getSession().setAttribute("deviceOwner", deviceOwner);
}
String tenantDomain = request.getParameter("tenantDomain");
if (tenantDomain != null) {
request.getSession().setAttribute("tenantDomain", tenantDomain);
}
String token = request.getParameter("token");
if (token != null) {
request.getSession().setAttribute("token", token);
}
%>
<div class="container">
<h1>Coffee Cup - Demo</h1>
<div class="left-pane">
<table style="width:100%">
<tr>
<td align="right" style="width: 140px">Temperature:</td>
<td id="temperature_level" align="left" style="width: 60px">0 C</td>
<td align="right" style="width: 140px">Coffee Level:</td>
<td id="coffee_level" align="left" style="width: 60px">0%</td>
</tr>
<tr>
<td colspan="2" align="center">
<input id="amount_temp" type="range" orient="vertical" min="0" max="100"
value="0"
onchange="updateTemperature(this.value)"><br/>
</td>
<td colspan="2" align="center">
<input id="amount_coffee" type="range" orient="vertical" min="0" max="100"
value="0"
onchange="updateCoffee(this.value)">
</td>
</tr>
<tr>
<td colspan="4" align="center">
<button id="order-cup">Order Coffee Cup</button>
</td>
</tr>
</table>
</div>
<div class="right-pane">
<div class="coffee-wrapper">
<div class="coffee">
<div class="coffee_main">
<div class="coffee_inner">
<div class="handle"></div>
<div class="water" id="water"></div>
</div>
<div class="highlight"></div>
</div>
</div>
</div>
</div>
</div>
<script src="js/libs/jquery.min.js"></script>
<script src="js/coffee.js"></script>
<script src="js/libs/htmlpreview.min.js"></script>
<script>HTMLPreview.replaceAssets();</script>
<script>
$('#order-cup').click(function () {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var token = '<%=request.getSession().getAttribute("token")%>';
var url = '/connectedcup/controller/ordercoffee?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner;
$.ajax({
type: 'POST',
url: url,
headers: {
'Authorization': 'Bearer ' + token
}
});
});
function sendData() {
var deviceId = '<%=request.getSession().getAttribute("deviceId")%>';
var deviceOwner = '<%=request.getSession().getAttribute("deviceOwner")%>';
var tenantDomain = '<%=request.getSession().getAttribute("tenantDomain")%>';
if (tenantDomain == null) {
tenantDomain = 'carbon.super';
}
var tempPayload = temperature;
var levelPayload = coffee_amount;
$.post('/connected-cup-agent/push_temperature?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner +
'&payload=' + tempPayload + '&tenantDomain=' + tenantDomain);
$.post('/connected-cup-agent/push_level?deviceId=' + deviceId + '&deviceOwner=' + deviceOwner +
'&payload=' + levelPayload + '&tenantDomain=' + tenantDomain);
setTimeout(sendData, 5000);
}
sendData();
</script>
</body>
</html>

@ -0,0 +1,39 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var temperature = 0;
var coffee_amount = 0;
function updateCoffee(newValue) {
var coffee_level = document.getElementById('coffee_level');
coffee_level.innerHTML = newValue + '%';
coffee_amount = newValue;
var coffee = document.getElementById('water');
if (newValue == 0) {
coffee.style.height = (newValue * 3) + 'px';
} else {
coffee.style.height = (newValue * 3) - 3 + 'px';
}
}
function updateTemperature(newValue) {
temperature = newValue;
var temperature_level = document.getElementById('temperature_level');
temperature_level.innerHTML = newValue + ' C';
}

@ -0,0 +1,19 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var HTMLPreview={content:"",previewform:document.getElementById("previewform"),file:function(){return location.search.substring(1)},raw:function(){return HTMLPreview.file().replace(/\/\/github\.com/,"//raw.githubusercontent.com").replace(/\/blob\//,"/")},replaceAssets:function(){var a,b,c;a=document.querySelectorAll("iframe[src],frame[src]");for(b=0;b<a.length;++b)if(c=a[b].src,0<c.indexOf("//raw.githubusercontent.com")||0<c.indexOf("//bitbucket.org"))a[b].src="//"+location.hostname+location.pathname+"?"+c;a=document.querySelectorAll("a[href]");for(b=0;b<a.length;++b)if(c=a[b].href,0<c.indexOf("#"))a[b].href="//"+location.hostname+location.pathname+location.search+"#"+a[b].hash.substring(1);else if((0<c.indexOf("//raw.githubusercontent.com")||0<c.indexOf("//bitbucket.org"))&&(0<c.indexOf(".html")||0<c.indexOf(".htm")))a[b].href="//"+location.hostname+location.pathname+"?"+c;if(!document.querySelectorAll("frameset").length){a=document.querySelectorAll("link[rel=stylesheet]");for(b=0;b<a.length;++b)c=a[b].href,(0<c.indexOf("//raw.githubusercontent.com")||0<c.indexOf("//bitbucket.org"))&&HTMLPreview.send(c,"loadCSS");a=document.querySelectorAll("script");for(b=0;b<a.length;++b)c=a[b].src,0<c.indexOf("//raw.githubusercontent.com")||0<c.indexOf("//bitbucket.org")?HTMLPreview.send(c,"loadJS"):!c&&0>a[b].innerHTML.indexOf("HTMLPreview")&&document.write(a[b].outerHTML)}},loadHTML:function(a){a&&a.query&&a.query.diagnostics&&a.query.diagnostics.redirect?HTMLPreview.send(a.query.diagnostics.redirect.content,"loadHTML"):a&&a.query&&a.query.results&&a.query.results.resources&&a.query.results.resources.content&&200==a.query.results.resources.status?(HTMLPreview.content=a.query.results.resources.content.replace(/<head>/i,'<head><base href="'+HTMLPreview.raw()+'">').replace(/<\/body>/i,'<script src="//'+location.hostname+'/htmlpreview.min.js">\x3c/script><script>HTMLPreview.replaceAssets();\x3c/script></body>').replace(/<\/head>\s*<frameset/gi,'<script src="//'+location.hostname+'/htmlpreview.min.js">\x3c/script><script>document.addEventListener("DOMContentLoaded",HTMLPreview.replaceAssets,false);\x3c/script></head><frameset'),setTimeout(function(){document.open();document.write(HTMLPreview.content);document.close()},50)):HTMLPreview.previewform.innerHTML=a&&a.error&&a.error.description?a.error.description:"Error: Cannot load file "+HTMLPreview.raw()},loadCSS:function(a){a&&a.query&&a.query.diagnostics&&a.query.diagnostics.redirect?HTMLPreview.send(a.query.diagnostics.redirect.content,"loadCSS"):a&&a.query&&a.query.results&&a.query.results.resources&&a.query.results.resources.content&&200==a.query.results.resources.status&&document.write("<style>"+a.query.results.resources.content.replace(/url\((?:'|")?([^\/][^:'"\)]+)(?:'|")?\)/gi,"url("+a.query.results.resources.url.replace(/[^\/]+\.css.*$/gi,"")+"$1)")+"</style>")},loadJS:function(a){a&&a.query&&a.query.diagnostics&&a.query.diagnostics.redirect?HTMLPreview.send(a.query.diagnostics.redirect.content,"loadJS"):a&&a.query&&a.query.results&&a.query.results.resources&&a.query.results.resources.content&&200==a.query.results.resources.status&&document.write("<script>"+a.query.results.resources.content+"\x3c/script>")},send:function(a,b){document.write('<script src="//query.yahooapis.com/v1/public/yql?q=select%20*%20from%20data.headers%20where%20url%3D%22'+encodeURIComponent(a)+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=HTMLPreview."+b+'">\x3c/script>')},submitform:function(){location.href="/?"+document.getElementById("file").value;return!1},init:function(){HTMLPreview.previewform.onsubmit=HTMLPreview.submitform;HTMLPreview.file()&&(HTMLPreview.previewform.innerHTML="<p>Loading...</p>",HTMLPreview.send(HTMLPreview.raw(),"loadHTML"))}};

@ -0,0 +1,43 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project name="create-connectedcup-capps" default="zip" basedir=".">
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/carbonapps"/>
<property name="src-dir" value="src/main/resources/carbonapps"/>
<property name="ConnectedCup_dir" value="connected_cup"/>
<property name="CoffeeLevel_Sensor_dir" value="coffee_level"/>
<target name="clean">
<delete dir="${target-dir}" />
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${ConnectedCup_dir}.car">
<zipfileset dir="${src-dir}/${ConnectedCup_dir}"/>
</zip>
<zip destfile="${target-dir}/${CoffeeLevel_Sensor_dir}.car">
<zipfileset dir="${src-dir}/${CoffeeLevel_Sensor_dir}"/>
</zip>
</target>
</project>

@ -0,0 +1,93 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.coffeeking</groupId>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.analytics</artifactId>
<version>1.0.0</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Analytics capp</name>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<id>auto-clean</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<target>
<ant antfile="build.xml" target="zip"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>${project.artifactId}-${carbon.device.mgt.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,36 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/target/carbonapps</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifacts>
<artifact name="coffee_level" version="1.0.0" type="carbon/application">
<dependency artifact="coffee_level_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="coffee_level_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="coffee_level_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="coffee_level_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="coffee_level_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>coffee_level_receiver.xml</file>
</artifact>

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<eventReceiver name="coffee_level_receiver" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.coffeelevel" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="coffee_level_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>coffee_level_script.xml</file>
</artifact>

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<Analytics>
<Name>coffee_level_script</Name>
<Script>
CREATE TEMPORARY TABLE DeviceCoffeeLevelData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_COFFEELEVEL");
CREATE TEMPORARY TABLE DeviceCoffeeLevelSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_COFFEELEVEL_SUMMARY", schema "coffeelevel FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert into table DeviceCoffeeLevelSummaryData select coffeelevel, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceCoffeeLevelData group by coffeelevel, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="coffee_level_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_coffeelevel.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.coffeelevel:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>coffeelevel</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="coffee_level_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.coffeelevel_1.0.0.json</file>
</artifact>

@ -0,0 +1,17 @@
{
"name": "org.wso2.iot.devices.coffeelevel",
"version": "1.0.0",
"nickName": "CoffeeLevel",
"description": "Coffee Level data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "coffeelevel","type": "FLOAT"
}
]
}

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifacts>
<artifact name="connected_cup" version="1.0.0" type="carbon/application">
<dependency artifact="connected_cup_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="connected_cup_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="connected_cup_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="connected_cup_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="connected_cup_execution" version="1.0.0" type="event/execution-plan" serverRole="DataAnalyticsServer">
<file>connected_cup_execution.siddhiql</file>
</artifact>

@ -0,0 +1,24 @@
/* Enter a unique ExecutionPlan */
@Plan:name('connected_cup_execution')
/* Enter a unique description for ExecutionPlan */
-- @Plan:description('connected_cup_execution')
/* define streams/tables and write queries here ... */
@Export('org.wso2.iot.devices.temperature:1.0.0')
define stream temperature (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, temperature float);
@Export('org.wso2.iot.devices.coffeelevel:1.0.0')
define stream coffeelevel (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, coffeelevel float);
@Import('org.wso2.iot.connectedcup:1.0.0')
define stream connectedcup (meta_owner string, meta_deviceId string, meta_type string, meta_timestamp long, temperature float, coffeelevel float);
from connectedcup[meta_type == 'coffeelevel']
select meta_owner, 'connectedcup' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, coffeelevel
insert into coffeelevel;
from connectedcup[meta_type == 'temperature']
select meta_owner, 'connectedcup' as meta_deviceType, meta_deviceId, meta_timestamp as meta_time, temperature
insert into temperature;

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="connected_cup_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>connected_cup_publisher.xml</file>
</artifact>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<eventPublisher name="connected_cup_publisher" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.connectedcup" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="secured-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="connected_cup_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>connected_cup_receiver.xml</file>
</artifact>

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<eventReceiver name="connected_cup_receiver" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/connectedcup/#</property>
<property name="contentValidator">iot-mqtt</property>
<property name="contentTransformer">default</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.connectedcup" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<artifact name="connected_cup_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.connectedcup_1.0.0.json</file>
</artifact>

@ -0,0 +1,16 @@
{
"name": "org.wso2.iot.connectedcup",
"version": "1.0.0",
"nickName": "connectedcup",
"description": "This hold the device type stream of connectedcup",
"metaData": [
{"name": "owner", "type": "STRING"},
{"name": "deviceId", "type": "STRING"},
{"name": "type", "type": "STRING"},
{"name": "timestamp", "type": "LONG"}
],
"payloadData": [
{"name": "temperature", "type": "FLOAT"},
{"name": "coffeelevel", "type": "FLOAT"}
]
}

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.coffeeking</groupId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup API</name>
<description>WSO2 IoTS(Device Types) - Connected Cup API</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>connectedcup</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,127 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Extension;
import io.swagger.annotations.ExtensionProperty;
import io.swagger.annotations.Info;
import io.swagger.annotations.SwaggerDefinition;
import io.swagger.annotations.Tag;
import org.wso2.carbon.apimgt.annotations.api.Scope;
import org.wso2.carbon.apimgt.annotations.api.Scopes;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@SwaggerDefinition(
info = @Info(
version = "1.0.0",
title = "",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = "name", value = "connectedcup"),
@ExtensionProperty(name = "context", value = "/connectedcup"),
})
}
),
tags = {
@Tag(name = "connectedcup", description = "")
}
)
@Scopes(
scopes = {
@Scope(
name = "Enroll device",
description = "",
key = "perm:connectedcup:enroll",
permissions = {"/device-mgt/devices/enroll/connectedcup"}
)
}
)
public interface ConnectedCupService {
String SCOPE = "scope";
@Path("device/ordercoffee")
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Order Coffee",
notes = "",
response = Response.class,
tags = "connectedcup",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll")
})
}
)
Response orderCoffee(@QueryParam("deviceId") String deviceId);
/**
* Retrieve Sensor data for the device type
*/
@Path("stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "GET",
value = "Retrieve Sensor data for the device type",
notes = "",
response = Response.class,
tags = "connectedcup",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll")
})
}
)
Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to);
@Path("device/register")
@POST
@ApiOperation(
consumes = MediaType.APPLICATION_JSON,
httpMethod = "POST",
value = "Enroll Cup",
notes = "",
response = Response.class,
tags = "connectedcup",
extensions = {
@Extension(properties = {
@ExtensionProperty(name = SCOPE, value = "perm:connectedcup:enroll")
})
}
)
boolean register(@QueryParam("name") String name);
}

@ -0,0 +1,162 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.api.util.APIUtil;
import org.coffeeking.api.util.SensorRecord;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.commons.SortType;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
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.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class ConnectedCupServiceImpl implements ConnectedCupService {
private static Log log = LogFactory.getLog(ConnectedCupServiceImpl.class);
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
@Path("device/ordercoffee")
@POST
public Response orderCoffee(@QueryParam("deviceId") String deviceId) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
return Response.ok().entity("Coffee ordered.").build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = " deviceId:" + deviceId + " AND deviceType:" +
ConnectedCupConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = getSensorEventTableName(sensor);
try {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
List<SensorRecord> sensorDatas;
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SortType.ASC);
sortByFields.add(sortByField);
sensorDatas = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.ok().entity(sensorDatas).build();
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* get the event table from the sensor name.
*/
private String getSensorEventTableName(String sensorName) {
String sensorEventTableName;
switch (sensorName) {
case "temperature":
sensorEventTableName = "DEVICE_TEMPERATURE_SUMMARY";
break;
case "coffeelevel":
sensorEventTableName = "DEVICE_COFFEELEVEL_SUMMARY";
break;
default:
sensorEventTableName = "";
}
return sensorEventTableName;
}
@Path("device/register")
@POST
public boolean register(@QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
String deviceId = shortUUID();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
return APIUtil.getDeviceManagementService().enrollDevice(device);
} catch (DeviceManagementException e) {
log.error("Failed to enroll device with device name :" + name, e);
return false;
}
}
}

@ -0,0 +1,33 @@
/*
* 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.coffeeking.api.exception;
public class ConnectedCupException extends Exception {
private static final long serialVersionUID = 118512086957330189L;
public ConnectedCupException(String errorMessage) {
super(errorMessage);
}
public ConnectedCupException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

@ -0,0 +1,150 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
throw new IllegalStateException("Device Management service has not initialized");
}
return deviceManagementProviderService;
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
throw new IllegalStateException("Device Authorization service has not initialized");
}
return deviceAccessAuthorizationService;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
throw new IllegalStateException("Analytics api service has not initialized");
}
return analyticsDataAPI;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataAPIUtil.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
/**
* Creates the SensorDatas from records.
*
* @param records the records
* @return the Map of SensorRecord <id, SensorRecord>
*/
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
/**
* Create a SensorRecord object out of a Record object
*
* @param record the record object
* @return SensorRecord object
*/
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
}

@ -0,0 +1,89 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.api.util;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@XmlRootElement
/**
* This stores sensor event data for android sense.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class SensorRecord {
@XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values;
@XmlElement(required = false, name = "id")
private String id;
/**
* Gets the values.
*
* @return the values
*/
public Map<String, Object> getValues() {
return values;
}
/**
* Sets the values.
*
* @param values the values
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
List<String> valueList = new ArrayList<String>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());
}
return valueList.toString();
}
}

@ -0,0 +1,53 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Register a device</name>
<path>/device-mgt/user/devices</path>
<url>/device/register</url>
<method>POST</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>Order coffee cup</name>
<path>/device-mgt/user/operation</path>
<url>/device/ordercoffee</url>
<method>POST</method>
<scope>connectedcup_user</scope>
</Permission>
<Permission>
<name>get device stats</name>
<path>/device-mgt/user/stats</path>
<url>/stats/*/sensors/*</url>
<method>GET</method>
<scope>connectedcup_user</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ 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.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ConnectedCup" address="/">
<jaxrs:serviceBeans>
<bean id="ConnectedCupService"
class="org.coffeeking.api.ConnectedCupServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>ConnectedCup-Webapp</display-name>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app>

@ -0,0 +1,116 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.coffeeking</groupId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin</name>
<description>WSO2 IoTS(Device Types) - Connected Cup CDMF Plugin</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>1.4.0</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Bundle-Version>${carbon.device.mgt.plugin.version}</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.coffeeking.connectedcup.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.xml.bind.*;resolution:=optional,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
javax.xml.bind.annotation.*;resolution:=optional,
javax.net;resolution:=optional,
javax.net.ssl;resolution:=optional,
org.w3c.dom;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.context.*,
org.wso2.carbon.ndatasource.core,
javax.xml.parsers.*;resolution:=optional
</Import-Package>
<Export-Package>
!org.coffeeking.connectedcup.plugin.internal,
org.coffeeking.connectedcup.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,36 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.connectedcup.plugin.constants;
public class ConnectedCupConstants {
public final static String DEVICE_TYPE = "connectedcup";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID";
public final static String ORDER_ON = "YES";
public final static String ORDER_OFF = "NO";
public static final String URL_PREFIX = "http://";
public static final String LEVEL_CONTEXT = "/LEVEL/";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
public static final String SENSOR_TEMPERATURE = "temperature";
public static final String SENSOR_LEVEL = "level";
public static final String DATA_SOURCE_NAME = "jdbc/ConnectedCupDM_DB";
}

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

@ -0,0 +1,100 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.connectedcup.plugin.impl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This hold the feature manager implementation for Connected CUp.
*/
public class ConnectedCupFeatureManager implements FeatureManager{
private static Feature feature = new Feature();
private static final String METHOD = "method";
private static final String URI = "uri";
private static final String CONTENT_TYPE = "contentType";
private static final String PATH_PARAMS = "pathParams";
private static final String QUERY_PARAMS = "queryParams";
private static final String FORM_PARAMS = "formParams";
public ConnectedCupFeatureManager() {
feature.setCode("ordercoffee");
feature.setName("Order Coffee");
feature.setDescription("Order coffee cup");
Map<String, Object> apiParams = new HashMap<>();
apiParams.put(METHOD, "POST");
apiParams.put(URI, "/connectedcup/device/ordercoffee");
List<String> pathParams = new ArrayList<>();
List<String> queryParams = new ArrayList<>();
List<String> formParams = new ArrayList<>();
apiParams.put(PATH_PARAMS, pathParams);
queryParams.add("deviceId");
apiParams.put(QUERY_PARAMS, queryParams);
apiParams.put(FORM_PARAMS, formParams);
List<Feature.MetadataEntry> metadataEntries = new ArrayList<>();
Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry();
metadataEntry.setId(-1);
metadataEntry.setValue(apiParams);
metadataEntries.add(metadataEntry);
feature.setMetadataEntries(metadataEntries);
}
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> list) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String code) throws DeviceManagementException {
if (code.equals(feature.getCode())) {
return feature;
}
return null;
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
List<Feature> features = new ArrayList<>();
features.add(feature);
return features;
}
@Override
public boolean removeFeature(String s) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

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

@ -0,0 +1,81 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.coffeeking.connectedcup.plugin.impl;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class ConnectedCupManagerService implements DeviceManagementService{
private DeviceManager deviceManager;
@Override
public String getType() {
return ConnectedCupConstants.DEVICE_TYPE;
}
@Override
public OperationMonitoringTaskConfig getOperationMonitoringConfig() {
return null;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager=new ConnectedCupManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, false);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
@Override
public PolicyMonitoringManager getPolicyMonitoringManager() {
return null;
}
}

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

@ -0,0 +1,132 @@
/*
* 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.coffeeking.connectedcup.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectedCupDAOUtil {
private static final Log log = LogFactory.getLog(ConnectedCupDAOUtil.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public ConnectedCupDAOUtil() {
initConnectedCupDAO();
}
public static void initConnectedCupDAO() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(ConnectedCupConstants.DATA_SOURCE_NAME);
} catch (NamingException e) {
log.error("Error while looking up the data source: " +
ConnectedCupConstants.DATA_SOURCE_NAME);
}
}
public ConnectedCupDAO getConnectedCupDeviceDAO() {
return new ConnectedCupDAO();
}
public static void beginTransaction() throws ConnectedCupDeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new ConnectedCupDeviceMgtPluginException(
"Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws ConnectedCupDeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new ConnectedCupDeviceMgtPluginException(
"Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws ConnectedCupDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, " +
"hence commit has not been attempted");
}
}
} catch (SQLException e) {
throw new ConnectedCupDeviceMgtPluginException(
"Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws ConnectedCupDeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws ConnectedCupDeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug(
"Datasource connection associated with the current thread is null, " +
"hence rollback has not been attempted");
}
}
} catch (SQLException e) {
throw new ConnectedCupDeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

@ -0,0 +1,88 @@
/*
* 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.coffeeking.connectedcup.plugin.impl.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
/**
* Contains utility methods used by FireAlarm plugin.
*/
public class ConnectedCupUtils {
private static Log log = LogFactory.getLog(ConnectedCupUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for (Device.Property property : deviceProperties) {
if (propertyKey.equals(property.getName())) {
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
}

@ -0,0 +1,74 @@
/*
* 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.coffeeking.connectedcup.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.impl.ConnectedCupManagerService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
/**
* @scr.component name="org.coffeeking.connectedcup.plugin.internal
* .ConnectedCupServiceComponent"
* immediate="true"
*/
public class ConnectedCupServiceComponent {
private static final Log log = LogFactory.getLog(ConnectedCupServiceComponent.class);
private ServiceRegistration connectedCupServiceRegRef;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Connected Cup Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
connectedCupServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new ConnectedCupManagerService(), null);
if (log.isDebugEnabled()) {
log.debug("Connected Cup Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Connected Cup Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Connected Cup Service Component");
}
try {
if (connectedCupServiceRegRef != null) {
connectedCupServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Connected Cup Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Connected Cup Service Component", e);
}
}
}

@ -0,0 +1,67 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.coffeeking</groupId>
<artifactId>device.mgt.iot.connectedcup-parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Component</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Component</description>
<url>http://wso2.org</url>
<modules>
<module>analytics</module>
<module>plugin</module>
<module>api</module>
<module>agent</module>
<module>ui</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -0,0 +1,63 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.coffeeking</groupId>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.ui</artifactId>
<version>1.0.0</version>
<name>WSO2 IoTS(Device Types) - Connected Cup UI</name>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<finalName>${project.artifactId}-${carbon.device.mgt.version}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,36 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -0,0 +1,48 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
<span id="connectedcup-details" data-devices="{{devices}}" data-devicename="{{device.name}}"
data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="connectedcup-div-chart" data-backend-api-url= {{backendApiUri}}>
<div class="chartWrapper" id="chartWrapper">
<h3 id="span-title">Temperature</h3>
<div id="y_axis-temperature" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-temperature" title="Smoothing"></div>
<div id="legend-temperature"></div>
</div>
<div id="chart-temperature" class="custom_rickshaw_graph"></div>
<div id="x_axis-temperature" class="custom_x_axis"></div>
<div id="slider-temperature" class="custom_slider"></div>
</div>
<div class="chartWrapper" id="chartWrapper">
<h3 id="span-title">Coffee Level</h3>
<div id="y_axis-coffeelevel" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-coffeelevel" title="Smoothing"></div>
<div id="legend-coffeelevel"></div>
</div>
<div id="chart-coffeelevel" class="custom_rickshaw_graph"></div>
<div id="x_axis-coffeelevel" class="custom_x_axis"></div>
<div id="slider-coffeelevel" class="custom_slider"></div>
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/connectedcup.js"}}
{{/zone}}

@ -0,0 +1,42 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId");
if (devices) {
return {
"devices": stringify(devices),
"backendApiUri": "/connectedcup/stats/"
};
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
return {
"device": device.content,
"backendApiUri": "/connectedcup/stats/" + deviceId
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}

@ -0,0 +1,316 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var palette = new Rickshaw.Color.Palette({scheme: 'classic9'});
function drawGraph_connectedcup(from, to) {
$('#y_axis-temperature').html('');
$('#smoother-temperature').html('');
$('#legend-temperature').html('');
$('#chart-temperature').html('');
$('#x_axis-temperature').html('');
$('#slider-temperature').html('');
$('#y_axis-coffeelevel').html('');
$('#smoother-coffeelevel').html('');
$('#legend-coffeelevel').html('');
$('#chart-coffeelevel').html('');
$('#x_axis-coffeelevel').html('');
$('#slider-coffeelevel').html('');
var devices = $('#connectedcup-details').data('devices');
var tzOffset = new Date().getTimezoneOffset() * 60;
var chartWrapperElmId = '#connectedcup-div-chart';
var graphWidth = $(chartWrapperElmId).width() - 50;
var temperatureGraphConfig = {
element: document.getElementById('chart-temperature'),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: 'linear',
unstack: true,
stack: false,
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
series: []
};
var coffeelevelGraphConfig = {
element: document.getElementById('chart-coffeelevel'),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: 'linear',
unstack: true,
stack: false,
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
series: []
};
if (devices) {
for (var i = 0; i < devices.length; i++) {
temperatureGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
});
coffeelevelGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
});
}
} else {
temperatureGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $('#connectedcup-details').data('devicename')
});
coffeelevelGraphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $('#connectedcup-details').data('devicename')
});
}
var temperatureGraph = new Rickshaw.Graph(temperatureGraphConfig);
var coffeelevelGraph = new Rickshaw.Graph(coffeelevelGraphConfig);
temperatureGraph.render();
coffeelevelGraph.render
var xAxisTemepature = new Rickshaw.Graph.Axis.Time({
graph: temperatureGraph
});
xAxisTemepature.render();
var xAxisCoffeelevel = new Rickshaw.Graph.Axis.Time({
graph: coffeelevelGraph
});
xAxisCoffeelevel.render();
var yAxisTemperature = new Rickshaw.Graph.Axis.Y({
graph: temperatureGraph,
orientation: 'left',
element: document.getElementById('y_axis-temperature'),
width: 40,
height: 410
});
yAxisTemperature.render();
var yAxisCoffeelevel = new Rickshaw.Graph.Axis.Y({
graph: coffeelevelGraph,
orientation: 'left',
element: document.getElementById('y_axis-coffeelevel'),
width: 40,
height: 410
});
yAxisCoffeelevel.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: temperatureGraph,
element: document.getElementById('slider-temperature')
});
var legend = new Rickshaw.Graph.Legend({
graph: temperatureGraph,
element: document.getElementById('legend-temperature')
});
var sliderCoffee = new Rickshaw.Graph.RangeSlider.Preview({
graph: coffeelevelGraph,
element: document.getElementById('slider-coffeelevel')
});
var legendCoffee = new Rickshaw.Graph.Legend({
graph: coffeelevelGraph,
element: document.getElementById('legend-coffeelevel')
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({
graph: temperatureGraph,
formatter: function (series, x, y) {
var date = '<span class="date">' +
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
}
});
var hoverDetailCoffeelevel = new Rickshaw.Graph.HoverDetail({
graph: coffeelevelGraph,
formatter: function (series, x, y) {
var date = '<span class="date">' +
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ': ' + parseInt(y) + '<br>' + date;
}
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: temperatureGraph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: temperatureGraph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: temperatureGraph,
legend: legend
});
var shelvingCoffee = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: coffeelevelGraph,
legend: legendCoffee
});
var orderCoffee = new Rickshaw.Graph.Behavior.Series.Order({
graph: coffeelevelGraph,
legend: legendCoffee
});
var highlighterCoffee = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: coffeelevelGraph,
legend: legendCoffee
});
var deviceIndex = 0;
if (devices) {
getData();
} else {
var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/temperature'
+ '?from=' + from + '&to=' + to;
var successCallback = function (data) {
if (data) {
drawTemperatureLineGraph(JSON.parse(data));
}
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {});
var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + '/sensors/coffeelevel'
+ '?from=' + from + '&to=' + to;
var successCallbackCoffeeLevel = function (data) {
if (data) {
drawCoffeeLevelLineGraph(JSON.parse(data));
}
};
invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
console.log(message);
});
}
function getData() {
if (deviceIndex >= devices.length) {
return;
}
var backendApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier
+ '/sensors/temperature?from=' + from + '&to=' + to;
var successCallback = function (data) {
if (data) {
drawTemperatureLineGraph(JSON.parse(data));
}
deviceIndex++;
getData();
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
deviceIndex++;
getData();
});
var coffeeLevelApiUrl = $('#connectedcup-div-chart').data('backend-api-url') + devices[deviceIndex].deviceIdentifier
+ '/sensors/coffeelevel?from=' + from + '&to=' + to;
var successCallbackCoffeeLevel = function (data) {
if (data) {
drawCoffeeLevelLineGraph(JSON.parse(data));
}
};
invokerUtil.get(coffeeLevelApiUrl, successCallbackCoffeeLevel, function (message) {
console.log(message);
});
}
function drawTemperatureLineGraph(data) {
if (data.length === 0 || data.length === undefined) {
return;
}
var chartData = [];
for (var i = 0; i < data.length; i++) {
chartData.push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(data[i].values.temperature)
}
);
}
temperatureGraphConfig.series[deviceIndex].data = chartData;
temperatureGraph.update();
}
function drawCoffeeLevelLineGraph(data) {
if (data.length === 0 || data.length === undefined) {
return;
}
var chartData = [];
for (var i = 0; i < data.length; i++) {
chartData.push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(data[i].values.coffeelevel)
}
);
}
coffeelevelGraphConfig.series[deviceIndex].data = chartData;
coffeelevelGraph.update();
}
}

@ -0,0 +1,67 @@
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/thumb.png"/>
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
<div class="add-margin-top-4x">
<div class="buttons">
<a class="btn-operations" target="_blank" href="{{../device.ip}}/connected-cup-agent/index.jsp?deviceOwner={{@user.username}}&tenantDomain={{@user.domain}}&deviceId={{../device.deviceIdentifier}}&token={{../device.accessToken}}" >Go To Device</a>
</div>
</div>
</div>
{{/zone}}
{{#zone "device-view-tabs"}}
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li>
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
{{/zone}}
{{#zone "device-view-tab-contents"}}
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div class="panel-heading">Device Statistics</div>
{{unit "cdmf.unit.device.type.connectedcup.realtime.analytics-view" device=device}}
</div>
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
<i class="fw fw-settings fw-spin fw-2x"></i>
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
{{/zone}}

@ -0,0 +1,40 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter('id');
if (deviceType && deviceId) {
var deviceModule = require("/app/modules/business-controllers/device.js").deviceModule;
var deviceData = deviceModule.viewDevice(deviceType, deviceId);
if (deviceData && deviceData.status != 'error') {
var device = deviceData.content;
var constants = require('/app/modules/constants.js');
var tokenPair = JSON.parse(session.get(constants.TOKEN_PAIR));
if (tokenPair) {
device.accessToken = tokenPair.accessToken;
}
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
device.ip = devicemgtProps['httpsWebURL'];
return {'device': deviceData.content};
}
}
}

@ -0,0 +1,43 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
{{unit "cdmf.unit.lib.rickshaw-graph"}}
<div id="div-chart" data-websocketurl="{{websocketEndpoint}}">
<div class="chartWrapper" id="chartWrapper">
<div id="y_axis" class="custom_y_axis" style="margin-top: -20px;">Temperature</div>
<div class="legend_container">
<div id="smoother" title="Smoothing"></div>
<div id="legend"></div>
</div>
<div id="chart" class="custom_rickshaw_graph"></div>
<div class="custom_x_axis">Time</div>
</div>
</div>
<a class="padding-left"
href="{{@app.context}}/device/{{device.type}}/analytics?deviceId={{device.deviceIdentifier}}&deviceName={{device.name}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-statistics fw-stack-1x"></i>
</span> View Device Analytics
</a>
<!-- /statistics -->
{{#zone "bottomJs"}}
{{js "js/moment.min.js"}}
{{js "js/socket.io.min.js"}}
{{js "js/device-stats.js"}}
{{/zone}}

@ -0,0 +1,44 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var log = new Log("stats.js");
var carbonServer = require("carbon").server;
var device = context.unit.params.device;
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
var constants = require("/app/modules/constants.js");
var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
var jwtService = carbonServer.osgiService(
'org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
var jwtClient = jwtService.getJWTClient();
var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
var token = "";
if (encodedClientKeys) {
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
var resp = tokenUtil.decode(encodedClientKeys).split(":");
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.temperature/1.0.0?"
+ "deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
var websocketToken= {'name':'websocket-token','value': token, 'path':'/', "maxAge":18000};
response.addCookie(websocketToken);
}
return {"device": device, "websocketEndpoint": websocketEndpoint};
}

@ -0,0 +1,108 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var ws;
var graph;
var chartData = [];
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
$(window).load(function () {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
chartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
graph = new Rickshaw.Graph({
element: document.getElementById("chart"),
width: $("#div-chart").width() - 50,
height: 300,
renderer: "line",
interpolation: "linear",
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(),
series: [{
'color': palette.color(),
'data': chartData,
'name': "Temperature"
}]
});
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
height: 300,
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis')
});
new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
var date = '<span class="date">' + moment(x * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
var websocketUrl = $("#div-chart").data("websocketurl");
connect(websocketUrl)
});
$(window).unload(function () {
disconnect();
});
//websocket connection
function connect(target) {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
console.log('WebSocket is not supported by this browser.');
}
if (ws) {
ws.onmessage = function (event) {
var dataPoint = JSON.parse(event.data);
chartData.push({
x: parseInt(dataPoint[4]) / 1000,
y: parseFloat(dataPoint[5])
});
chartData.shift();
graph.update();
};
}
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
}

@ -0,0 +1,66 @@
/*
* Copyright (c) 2017, 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.
*/
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
padding: 0;
opacity: 0.2;
}
.light-grey {
color: #7c7c7c;
}
.uppercase {
text-transform: uppercase;
}
.grey-bg {
background-color: #f6f4f4;
}
.doc-link{
background: none;
color: #000;
padding: 10px 0px;
}
.doc-link a {
color: #006eff;
}

@ -0,0 +1,153 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var modalPopup = ".modal";
var modalPopupContainer = modalPopup + " .modal-content";
var modalPopupContent = modalPopup + " .modal-content";
var body = "body";
/*
* Set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).modal('show');
setPopupMaxHeight();
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != '') {
deviceType = this.value;
}
});
}
/*
* hide popup function.
*/
function hidePopup() {
$('label[for=deviceName]').remove();
$('.control-group').removeClass('success').removeClass('error');
$(modalPopupContent).html('');
$(modalPopup).modal('hide');
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
});
}
function downloadAgent() {
//$('#downloadForm').submit();
var $inputs = $('#downloadForm :input');
var values = {};
$inputs.each(function () {
values[this.name] = $(this).val();
});
var deviceName = $inputs[0].value;
$('.new-device-name').each(function () {
if (this.value != '') {
deviceName = this.value;
}
});
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceName.length < 4) {
$("#invalid-username-error-msg span").text("Device name should be more than 3 letters!");
$("#invalid-username-error-msg").removeClass("hidden");
} else if (deviceName && deviceNameFormat.test(deviceName)) {
var payload = {};
payload.name = $inputs[0].value;
payload.owner = $inputs[1].value;
var connectedCupRegisterURL = '/connectedcup/device/register?name=' + encodeURI(payload.name);
invokerUtil.post(
connectedCupRegisterURL,
payload,
function (data, textStatus, jqxhr) {
$(modalPopupContent).html($('#device-created-content').html());
$('#device-created-link').click(function () {
hidePopup();
});
setTimeout(function () {
hidePopup();
}, 1000);
},
function (data) {
doAction(data)
}
);
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
}
}
function doAction(data) {
//if it is saml redirection response
if (data.status == null) {
document.write(data);
}
if (data.status == 200) {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$('input#download-device-url').val(data.responseText);
$('input#download-device-url').focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == 401) {
$(modalPopupContent).html($('#device-401-content').html());
$('#device-401-link').click(function () {
window.location = '/devicemgt/login';
});
showPopup();
} else if (data == 403) {
$(modalPopupContent).html($('#device-403-content').html());
$('#device-403-link').click(function () {
window.location = '/devicemgt/login';
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$('a#device-unexpected-error-link').click(function () {
hidePopup();
});
}
}

@ -0,0 +1,216 @@
{{!
Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you under the Apache License,
Version 2.0 (the "License"); you may not use this file except
in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
}}
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Connected Cup</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-3 col-lg-3 padding-top">
<img src="{{@unit.publicUri}}/images/coffeecup.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-9 col-lg-9 padding-top">
<h3 class="uppercase">What it Does</h3>
<hr>
<p class="grey margin-top">Connected cup is a virtual simulation of a smart coffee cup from the IOT Hardware
manufacturer "Coffee King". Once an instance of the virtual Connected-Cup, Users can play
around with the temperature and Coffee level. And the information will be relayed back to
the IoTServer and summarized.
</p>
<p>The device supports communication via HTTPS only.</p>
<br>
<h3 class="uppercase">What You Need</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="badge">STEP 01</span>
Go ahead and [Download] the Device.
</li>
<li>
<span class="badge">STEP 02</span>
Proceed to [Prepare] section.
</li>
<li>
<span class="badge">STEP 03</span>
Read [Try Out] section to further experiment with the device.
</li>
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations"
target="_blank"><i class="fw fw-api"></i> View API</i>
</a>
<a href="#" class="download-link btn-operations">
<i class="fw fw-download"></i>Create an instance</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered">
<h3>Name your Connected cup instance.</h3>
<br/>
<form id="downloadForm">
<div class="control-group">
<div class="controls">
<input class="connectedCupName" style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. Office_CoffeeCup"
name="name" size="60" required>
<br/>
<input type="hidden" class="owner" name="owner" value={{@user.username}} />
</div>
</div>
<br/>
<div class="buttons">
<a class="btn-operations" onclick="downloadAgent()">Create an Instance</a>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="device-created-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Connected cup device created. </h3>
<p> Select instance of the Connected Cup you created from the "Devices" section. </p>
<div class="buttons">
<a href="#" id="device-created-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
&nbsp;&nbsp;&nbsp;&nbsp;Goto Login Page&nbsp;&nbsp;&nbsp;&nbsp;
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Cancel&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h3 class="uppercase">Try Out</h3><hr>
<p class="grey margin-top">Access your Device</p>
<br/>
<ul>
<p class="padding-top-double"><span class="circle">01</span> Select instance of the Connected Cup you created from the "Devices" section.</p>
<p class="padding-top-double"><span class="circle">02</span> Click the [Go to Device] button from the "Operations" section and you will be able to view and experiment with the device.</p>
</ul>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Connected Cup Agent</h3><hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/coffee_stats.png" target="_blank">
<img src="{{@unit.publicUri}}/images/coffee_stats.png" class="img-responsive">
</a>
</center>
<br/>
</div>
{{#zone "topCss"}}
{{css "css/styles.css"}}
{{/zone}}
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -0,0 +1,238 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.coffeeking</groupId>
<artifactId>connected-cup-feature-parent</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.feature</artifactId>
<packaging>pom</packaging>
<version>1.0.0</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Feature</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Feature</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<version>${org.coffeeking.version}</version>
</dependency>
<dependency>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<version>${org.coffeeking.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.agent</artifactId>
<version>${org.coffeeking.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<version>1.2.140.wso2v3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.analytics
</artifactId>
<version>${org.coffeeking.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.ui
</artifactId>
<version>${org.coffeeking.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>connectedcup.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.coffeeking</groupId>
<artifactId>org.coffeeking.connectedcup.agent</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>connected-cup-agent.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Connected Cup Plugin Management schema -->
<id>create-connected-cup-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo
message="########### Create Connected Cup plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/ConnectedCupDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.coffeeking.connectedcup</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.coffeeking:org.coffeeking.connectedcup.plugin:${org.coffeeking.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,29 @@
#
# 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.
#
#
#[Device-Configurations]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/digital_display/controller
mqtt-ep=${MQTT_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

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

Loading…
Cancel
Save