100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Forked CCS
Christian Bauer47bf07124d9e
diff --git a/beehive/ccs/Dockerfile b/beehive/ccs/Dockerfilenew file mode 100644index 000000000..d7897f071--- /dev/null+++ b/beehive/ccs/Dockerfile@@ -0,0 +1,5 @@+FROM openremote/tomcat:latest++ADD build/libs/ccs.war webapps/+ADD conf/keystore.jks ./+diff --git a/beehive/ccs/build.gradle b/beehive/ccs/build.gradlenew file mode 100644index 000000000..c18dca12b--- /dev/null+++ b/beehive/ccs/build.gradle@@ -0,0 +1,75 @@+apply plugin: "java"+apply plugin: "war"++dependencies {++ compile "org.openremote:or-commons:0.1.0"+ compile "org.openremote:or-object-model:0.2.1"++ compile "org.json:json:20090211"++ compile "net.sf.flexjson:flexjson:$flexjsonVersion"++ compile "org.slf4j:slf4j-api:$slf4jVersion"+ compile "ch.qos.logback:logback-classic:1.1.3"++ compile "org.glassfish.jersey.containers:jersey-container-servlet-core:$jerseyVersion"+ compile "javax.ws.rs:javax.ws.rs-api:$jaxrsVersion"++ compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:1.0.0.Final"++ compile "org.hibernate:hibernate-core:$hibernateVersion"+ compile "org.hibernate:hibernate-entitymanager:$hibernateVersion"+ compile "org.hibernate:hibernate-c3p0:$hibernateVersion"++ compile "mysql:mysql-connector-java:$mysqlConnectorVersion"++ compile "commons-lang:commons-lang:$commonsLangVersion"+ compile "commons-codec:commons-codec:$commonsCodecVersion"+ compile "commons-dbcp:commons-dbcp:$commonsDbcpVersion"++ compile "org.springframework.security:spring-security-core:$springVersion"++ providedCompile "javax.servlet:javax.servlet-api:$servletVersion"++ testCompile "junit:junit:$junitVersion"+}++war {+ archiveName = 'ccs.war'++ // TODO: Replace with proper config system+ if (project.hasProperty("targetEnv")) {+ def targetEnvFolder = 'environments/' + targetEnv;+ if (new File(targetEnvFolder).exists()) {+ from(targetEnvFolder) {+ include '*.properties'+ include '*.xml'+ exclude 'web.xml'+ into ('WEB-INF/classes')+ }+ from(targetEnvFolder) {+ include 'web.xml'+ into ('WEB-INF')+ }+ } else {+ println "*** No configuration exists for target environment"+ }+ } else {+ println "*** No target environment defined"+ }+}++import com.bmuschko.gradle.docker.tasks.image.*++task buildImage(type: DockerBuildImage) {+ dependsOn war+ inputDir = projectDir+ dockerFile = file("$projectDir/Dockerfile")+ tag = dockerImageName+}++task pushImage(type: DockerPushImage) {+ dependsOn buildImage+ imageName = dockerImageName+}diff --git a/beehive/ccs/conf/keystore.jks b/beehive/ccs/conf/keystore.jksnew file mode 100644index 000000000..1f8436961Binary files /dev/null and b/beehive/ccs/conf/keystore.jks differdiff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.javanew file mode 100644index 000000000..22d0a09e0--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.java@@ -0,0 +1,297 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand;++import org.glassfish.jersey.server.ResourceConfig;+import org.hibernate.Session;+import org.hibernate.jdbc.Work;+import org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor;+import org.openremote.beehive.EntityTransactionFilter;+import org.openremote.controllercommand.proxy.ProxyServer;+import org.openremote.controllercommand.resources.ControllerCommandResource;+import org.openremote.controllercommand.resources.ControllerCommandsResource;+import org.openremote.controllercommand.service.AccountService;+import org.openremote.controllercommand.service.ControllerCommandService;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import javax.annotation.PreDestroy;+import javax.persistence.EntityManager;+import javax.persistence.EntityManagerFactory;+import javax.persistence.EntityTransaction;+import javax.persistence.Persistence;+import javax.ws.rs.container.ContainerRequestContext;+import javax.ws.rs.container.ContainerRequestFilter;+import javax.ws.rs.container.ContainerResponseContext;+import javax.ws.rs.container.ContainerResponseFilter;+import java.io.BufferedReader;+import java.io.IOException;+import java.io.InputStreamReader;+import java.sql.*;+import java.util.Properties;++public class ControllerProxyAndCommandServiceApplication extends ResourceConfig {+ static private EntityManagerFactory entityManagerFactory;++ protected final static Logger persistenceLog = LoggerFactory.getLogger(ControllerProxyAndCommandServiceApplication.class);++ public ControllerProxyAndCommandServiceApplication() {++ Properties config = new Properties();+ try {+ config.load(getClassLoader().getResourceAsStream("config.properties"));+ } catch (IOException e) {+ // TODO: log+ e.printStackTrace();+ }++ entityManagerFactory = Persistence.createEntityManagerFactory(config.getProperty("persistenceUnitName", "CCS-MySQL"));+ // TODO THis is never called, no idea why....+ if (config.getProperty("persistenceCreateSchema", "false").equals("true")) {+ createSchema();+ }+ persistenceLog.info("EntityManagerFactory has been created");+ register(EntityPersistence.class);++ GenericDAO genericDAO = new GenericDAO();+ final AccountService accountService = new AccountService();+ accountService.setGenericDAO(genericDAO);+ final ControllerCommandService controllerCommandService = new ControllerCommandService();+ controllerCommandService.setGenericDAO(genericDAO);++ String proxyHostname = config.getProperty("proxy.hostname", "localhost");+ Integer proxyTimeout = getIntegerConfiguration(config, "proxy.timeout", 10000);+ Integer proxyPort = getIntegerConfiguration(config, "proxy.port", 10000);+ String proxyClientPortRange = config.getProperty("proxy.clientPortRange", "30000-30010");+ Boolean useSSL = getBooleanConfiguration(config, "proxy.useSSL", true);+ String keystore = config.getProperty("proxy.keystore", "keystore.ks");+ String keystorePassword = config.getProperty("proxy.keystorePassword", "storepass");+ ProxyServer ps = new ProxyServer(proxyHostname, proxyTimeout, proxyPort, proxyClientPortRange, useSSL, keystore, keystorePassword, controllerCommandService, accountService, this);+ ps.start();++ register(ControllerCommandResource.class);+ register(ControllerCommandsResource.class);++ register(new org.glassfish.hk2.utilities.binding.AbstractBinder() {+ @Override+ protected void configure() {+ bind(accountService);+ bind(controllerCommandService);+ }+ });+ }++ @PreDestroy+ private void testDestroy() {+ try {+ entityManagerFactory.close();+ persistenceLog.info("EntityManagerFactory has been closed");+ } catch (Exception e) {+ persistenceLog.warn("Could not close EntityManagerFactory");+ }+ }++ private Integer getIntegerConfiguration(Properties config, String propertyName, Integer defaultValue) {+ String stringValue = config.getProperty(propertyName);+ if (stringValue == null) {+ return defaultValue;+ }+ Integer integerValue = null;+ try {+ integerValue = Integer.parseInt(stringValue);+ } catch (NumberFormatException e) {+ integerValue = defaultValue;+ }+ return integerValue;+ }++ private Boolean getBooleanConfiguration(Properties config, String propertyName, Boolean defaultValue) {+ String stringValue = config.getProperty(propertyName);+ if (stringValue == null) {+ return defaultValue;+ }+ Boolean booleanValue = null;+ try {+ booleanValue = Boolean.parseBoolean(stringValue);+ } catch (NumberFormatException e) {+ booleanValue = defaultValue;+ }+ return booleanValue;+ }++ public EntityManager createEntityManager() {+ persistenceLog.trace(">>createEntityManager");+ EntityManager entityManager = null;+ try {+ persistenceLog.trace("Before createEntityManager");+ entityManager = entityManagerFactory.createEntityManager();+ persistenceLog.debug("Got entityManager " + entityManager);+ EntityTransaction tx = entityManager.getTransaction();+ persistenceLog.debug("Got transaction " + tx);+ tx.begin();+ persistenceLog.debug("Begun transaction");+ } catch (Exception e) {+ persistenceLog.error("Failed to create an EntityManager", e);+ }+ persistenceLog.trace("<<createEntityManager");+ return entityManager;+ }++ public void commitEntityManager(EntityManager entityManager) {+ persistenceLog.trace(">>commitEntityManager");+ if (entityManager.isOpen()) {+ persistenceLog.debug("entityManager opened, commit transaction");+ entityManager.getTransaction().commit();+ entityManager.close();+ }+ persistenceLog.trace("<<commitEntityManager");+ }++ public void rollbackEntityManager(EntityManager entityManager) {+ persistenceLog.trace(">>rollbackEntityManager");+ if (entityManager.isOpen()) {+ persistenceLog.debug("entityManager opened, rollback transaction");+ entityManager.getTransaction().rollback();+ entityManager.close();+ }+ persistenceLog.trace("<<rollbackEntityManager");+ }++ /**+ * This container filter implements a managed persistence context for JPA entities used+ * in JAX-RS resources.+ */+ private static class EntityPersistence implements ContainerRequestFilter, ContainerResponseFilter {+ // Class Members ------------------------------------------------------------------------------++ // ContainerRequestFilter Implementation ------------------------------------------------------++ /**+ * Passes the entity manager reference as a request property to the resource classes to use.+ * Also begins the transaction boundary for JPA entities here.+ */+ @Override+ public void filter(ContainerRequestContext request) {+ EntityManager entityManager = null;+ try {+ entityManager = entityManagerFactory.createEntityManager();+ request.setProperty(EntityTransactionFilter.PERSISTENCE_ENTITY_MANAGER_LOOKUP, entityManager);+ entityManager.getTransaction().begin();+ } catch (Throwable throwable) {++ persistenceLog.error("Failed to create EntityManager", throwable);++ if (entityManager != null) {+ EntityTransaction tx = entityManager.getTransaction();+ if (tx != null && tx.isActive()) {+ try {+ tx.rollback();+ } catch (Exception e) {+ persistenceLog.warn("Failed to rollback transaction ", e);+ }+ }+ }+ }+ }++ /**+ * Manages the entity transaction boundary on return request. If entity transaction has+ * been marked for rollback, or we are returning an HTTP error code 400 or above, roll back+ * the entity transaction.+ */+ @Override+ public void filter(ContainerRequestContext request, ContainerResponseContext response) {+ EntityManager entityManager = (EntityManager) request.getProperty(EntityTransactionFilter.PERSISTENCE_ENTITY_MANAGER_LOOKUP);+ if (entityManager == null) {+ return;+ }++ EntityTransaction tx = entityManager.getTransaction();++ persistenceLog.debug("Transaction is " + tx + " , active ? " + (tx.isActive() ? "yes" : "no"));++ if (tx != null && tx.isActive()) {+ if (tx.getRollbackOnly() || response.getStatus() >= 400) {+ persistenceLog.debug("Rolling back transaction");+ try {+ tx.rollback();+ } catch (Exception e) {+ persistenceLog.warn("Failed to rollback transaction ", e);+ }+ } else {+ persistenceLog.debug("Commit transaction");+ try {+ tx.commit();+ } catch (Exception e) {+ persistenceLog.error("Failed to commit transaction ", e);+ }+ }+ }+ if (entityManager.isOpen()) {+ try {+ entityManager.close();+ } catch (Exception e) {+ persistenceLog.warn("Failed to closed EntityManager", e);+ }+ }+ }+ }++ private void createSchema() {+ // Check if the CONTROLLER table exists+ entityManagerFactory.createEntityManager().unwrap(Session.class).doWork(new Work() {+ @Override+ public void execute(Connection connection) throws SQLException {+ DatabaseMetaData meta;+ ResultSet rs = null;+ try {+ meta = connection.getMetaData();+ rs = meta.getTables(null, null, "controller", new String[]{"TABLE"});+ if (!rs.next()) {+ rs.close();+ persistenceLog.warn("NO DATABASE SCHEMA FOUND, ATTEMPTING TO CREATE DATABASE SCHEMA...");+ MultipleLinesSqlCommandExtractor extractor = new MultipleLinesSqlCommandExtractor();+ String[] sqlCommands = extractor.extractCommands(+ new BufferedReader(new InputStreamReader(+ getClass().getClassLoader().getResourceAsStream("sql/CreateTables.sql"))+ )+ );+ for (String sqlCommand : sqlCommands) {+ Statement stmt = null;+ try {+ stmt = connection.createStatement();+ rs = stmt.executeQuery(sqlCommand);+ } finally {+ if (stmt != null) {+ stmt.close();+ }+ }+ }+ }+ } finally {+ if (rs != null)+ rs.close();+ }+ }+ });+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/GenericDAO.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/GenericDAO.javanew file mode 100644index 000000000..01bcca242--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/GenericDAO.java@@ -0,0 +1,52 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2010, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand;++import javax.persistence.EntityManager;+import javax.persistence.criteria.CriteriaBuilder;+import javax.persistence.criteria.CriteriaQuery;+import javax.persistence.criteria.Root;++/**+ * The general DAO for all the DAO. It provides basic CRUD operations using Hibernate.+ *+ * @author Dan 2009-2-6+ */+public class GenericDAO {++ /**+ * Return the persistent instance of the given entity class with the given non-identifier field.+ *+ * @param <T> a persistent generics+ * @param clazz a persistent class+ * @param fieldName field name+ * @param fieldValue field value+ * @return the persistent instance+ */+ public <T> T getByNonIdField(EntityManager entityManager, Class<T> clazz, String fieldName, String fieldValue) {+ CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();+ CriteriaQuery<T> query = criteriaBuilder.createQuery(clazz);+ Root<T> root = query.from(clazz);+ query.select(root);+ query.where(criteriaBuilder.equal(root.get(fieldName), fieldValue));+ return entityManager.createQuery(query).getSingleResult();+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/db/CustomMySQL5Dialect.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/db/CustomMySQL5Dialect.javanew file mode 100644index 000000000..296a4f53b--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/db/CustomMySQL5Dialect.java@@ -0,0 +1,47 @@+/* OpenRemote, the Home of the Digital Home.+* Copyright 2008-2010, OpenRemote Inc.+*+* See the contributors.txt file in the distribution for a+* full listing of individual contributors.+*+* This program is free software: you can redistribute it and/or modify+* it under the terms of the GNU Affero General Public License as+* published by the Free Software Foundation, either version 3 of the+* License, or (at your option) any later version.+*+* This program is distributed in the hope that it will be useful,+* but WITHOUT ANY WARRANTY; without even the implied warranty of+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+* GNU Affero General Public License for more details.+*+* You should have received a copy of the GNU Affero General Public License+* along with this program. If not, see <http://www.gnu.org/licenses/>.+*/+package org.openremote.controllercommand.db;++import java.sql.Types;++import org.hibernate.dialect.MySQL5Dialect;++/**+ * A customized SQL dialect for MySQL 5.x specific features.+ *+ * @author Dan 2009-2-6+ */+public class CustomMySQL5Dialect extends MySQL5Dialect {++ public CustomMySQL5Dialect() {+ super();+ // maps the boolean type to tinyint(1)+ registerColumnType(Types.BIT, "tinyint(1)");+ }++ /**+ * Sets the MySQL default charset to UTF-8+ */+ @Override+ public String getTableTypeString() {+ return " ENGINE=InnoDB DEFAULT CHARSET=utf8";+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.javanew file mode 100644index 000000000..126c97175--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.java@@ -0,0 +1,83 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2011, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.domain;++import java.util.List;++import javax.persistence.Entity;+import javax.persistence.OneToMany;+import javax.persistence.Table;++/**+ * The Class Account.+ *+ * @author Marcus+ */+@Entity+@Table(name = "account")+public class Account extends BusinessEntity {++ private static final long serialVersionUID = -5029444774173816237L;++ /**+ * The users.+ */+ private List<User> users;++ /**+ * The controllers this account is linked to+ */+ private List<Controller> controllers;++ @OneToMany(mappedBy = "account")+ public List<User> getUsers() {+ return users;+ }++ public void setUsers(List<User> users) {+ this.users = users;+ }++ @OneToMany(mappedBy = "account")+ public List<Controller> getControllers() {+ return controllers;+ }++ public void setControllers(List<Controller> controllers) {+ this.controllers = controllers;+ }++ @Override+ public int hashCode() {+ return (int) getOid();+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj)+ return true;+ if (obj == null)+ return false;+ if (getClass() != obj.getClass())+ return false;+ Account other = (Account) obj;+ return other.getOid() == getOid();+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/BusinessEntity.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/BusinessEntity.javanew file mode 100644index 000000000..34d835149--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/BusinessEntity.java@@ -0,0 +1,86 @@+/* OpenRemote, the Home of the Digital Home.+* Copyright 2008-2011, OpenRemote Inc.+*+* See the contributors.txt file in the distribution for a+* full listing of individual contributors.+*+* This program is free software: you can redistribute it and/or modify+* it under the terms of the GNU Affero General Public License as+* published by the Free Software Foundation, either version 3 of the+* License, or (at your option) any later version.+*+* This program is distributed in the hope that it will be useful,+* but WITHOUT ANY WARRANTY; without even the implied warranty of+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+* GNU Affero General Public License for more details.+*+* You should have received a copy of the GNU Affero General Public License+* along with this program. If not, see <http://www.gnu.org/licenses/>.+*/++package org.openremote.controllercommand.domain;++import java.io.Serializable;++import javax.persistence.GeneratedValue;+import javax.persistence.GenerationType;+import javax.persistence.Id;+import javax.persistence.MappedSuperclass;+++/**+ * Business entity class for all JPA entities with the common property oid.+ *+ * @author Marcus+ */+@MappedSuperclass+public abstract class BusinessEntity implements Serializable {++ /**+ * The Constant serialVersionUID.+ */+ private static final long serialVersionUID = 754736926051991600L;++ /**+ * The oid.+ */+ private long oid;++ /**+ * Instantiates a new business entity.+ */+ public BusinessEntity() {+ super();+ }++ /**+ * Instantiates a new business entity.+ *+ * @param oid the oid+ */+ public BusinessEntity(long oid) {+ super();+ this.oid = oid;+ }++ /**+ * Gets the oid.+ *+ * @return the oid+ */+ @Id+ @GeneratedValue(strategy = GenerationType.AUTO)+ public long getOid() {+ return oid;+ }++ /**+ * Sets the oid.+ *+ * @param oid the new oid+ */+ public void setOid(long oid) {+ this.oid = oid;+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.javanew file mode 100644index 000000000..3c74e4785--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.java@@ -0,0 +1,75 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2011, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.domain;++import javax.persistence.Entity;+import javax.persistence.ManyToOne;+import javax.persistence.Table;++/**+ * The Class Controller.+ *+ * @author Marcus+ */+@Entity+@Table(name = "controller")+public class Controller extends BusinessEntity {++ private static final long serialVersionUID = -8631606687130231794L;++ /**+ * The MAC address (can be a comma seperated list of multiple MAC address)+ */+ private String macAddress;++ /**+ * The linked Account+ */+ private Account account;++ private boolean linked;++ public String getMacAddress() {+ return macAddress;+ }++ public void setMacAddress(String macAddress) {+ this.macAddress = macAddress;+ }++ @ManyToOne+ public Account getAccount() {+ return account;+ }++ public void setAccount(Account account) {+ this.account = account;+ }++ public boolean isLinked() {+ return linked;+ }++ public void setLinked(boolean linked) {+ this.linked = linked;+ }+++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.javanew file mode 100644index 000000000..8ec025650--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.java@@ -0,0 +1,101 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2011, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.domain;++import java.util.Date;++import javax.persistence.Entity;+import javax.persistence.EnumType;+import javax.persistence.Enumerated;+import javax.persistence.Inheritance;+import javax.persistence.InheritanceType;+import javax.persistence.ManyToOne;+import javax.persistence.Table;++/**+ * Entity for commands sent from Beehive to the backend+ *+ * @author Stphane Epardaud <[email protected]>+ */+@SuppressWarnings("serial")+@Entity+@Table(name = "controller_command")+@Inheritance(strategy = InheritanceType.JOINED)+public class ControllerCommand extends BusinessEntity {++ private Account account;+ private Date creationDate;+ private State state;+ private ControllerCommandDTO.Type type;+++ /**+ * State of the command. They start as OPEN, then are marked as DONE when they have been treated by+ * the controller.+ */+ public enum State {+ OPEN, DONE;+ }++ public ControllerCommand() {+ }++ public ControllerCommand(Account account, ControllerCommandDTO.Type type) {+ this.account = account;+ this.creationDate = new Date();+ this.state = State.OPEN;+ this.type = type;+ }++ @ManyToOne+ public Account getAccount() {+ return account;+ }++ public void setAccount(Account account) {+ this.account = account;+ }++ public Date getCreationDate() {+ return creationDate;+ }++ public void setCreationDate(Date creationDate) {+ this.creationDate = creationDate;+ }++ @Enumerated(EnumType.STRING)+ public State getState() {+ return state;+ }++ public void setState(State state) {+ this.state = state;+ }++ @Enumerated(EnumType.STRING)+ public ControllerCommandDTO.Type getType() {+ return type;+ }++ public void setType(ControllerCommandDTO.Type type) {+ this.type = type;+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.javanew file mode 100644index 000000000..2fde48a60--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.java@@ -0,0 +1,61 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.domain;++import java.util.UUID;++import javax.persistence.Entity;+import javax.persistence.Table;++@SuppressWarnings("serial")+@Entity+@Table(name = "initiate_proxy_controller_command")+public class InitiateProxyControllerCommand extends ControllerCommand {+ private String url;+ private String token;++ public InitiateProxyControllerCommand() {+ super();+ }++ public InitiateProxyControllerCommand(Account account, ControllerCommandDTO.Type type, String url) {+ super(account, type);+ this.url = url;+ // TODO Should this be SecureRandom?+ this.token = UUID.randomUUID().toString();+ }++ public void setUrl(String url) {+ this.url = url;+ }++ public String getUrl() {+ return url;+ }++ public void setToken(String token) {+ this.token = token;+ }++ public String getToken() {+ return token;+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.javanew file mode 100644index 000000000..13f5c27f9--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.java@@ -0,0 +1,147 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2012, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.domain;++import javax.persistence.Column;+import javax.persistence.Entity;+import javax.persistence.ManyToOne;+import javax.persistence.Table;+import javax.persistence.Transient;+++/**+ * TODO+ *+ * @author Marcus+ */+@Entity+@Table(name = "user")+public class User extends BusinessEntity {++ private static final long serialVersionUID = 6064996041309363949L;++ private String username;++ private String password;++ private String rawPassword;++ /**+ * The account containing all business entities.+ */+ private Account account;++ /**+ * Instantiates a new user.+ */+ public User() {+ account = new Account();+ }++ public User(Account account) {+ this.account = account;+ }++ /**+ * Gets the username.+ *+ * @return the username+ */+ @Column(unique = true, nullable = false)+ public String getUsername() {+ return username;+ }++ /**+ * Sets the username.+ *+ * @param username the new username+ */+ public void setUsername(String username) {+ this.username = username;+ }++ /**+ * Gets the password.+ *+ * @return the password+ */+ @Column(nullable = false)+ public String getPassword() {+ return password;+ }++ /**+ * Sets the password.+ *+ * @param password the new password+ */+ public void setPassword(String password) {+ this.password = password;+ }++ /**+ * Gets the account.+ *+ * @return the account+ */+ @ManyToOne+ public Account getAccount() {+ return account;+ }++ /**+ * Sets the account.+ *+ * @param account the new account+ */+ public void setAccount(Account account) {+ this.account = account;+ }+++ @Transient+ public String getRawPassword() {+ return rawPassword;+ }++ public void setRawPassword(String rawPassword) {+ this.rawPassword = rawPassword;+ }++ @Override+ public int hashCode() {+ return (int) getOid();+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj)+ return true;+ if (obj == null)+ return false;+ if (getClass() != obj.getClass())+ return false;+ User other = (User) obj;+ return other.getOid() == getOid();+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/HTTPException.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/HTTPException.javanew file mode 100644index 000000000..031440b20--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/HTTPException.java@@ -0,0 +1,48 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.proxy;++@SuppressWarnings("serial")+public class HTTPException extends Exception {++ private int status;+ private boolean json;+ private boolean options;++ public HTTPException(int status, boolean json, boolean options) {+ super();+ this.status = status;+ this.json = json;+ this.options = options;+ }++ public int getStatus() {+ return status;+ }++ public boolean isJson() {+ return json;+ }++ public boolean isOptionsRequest() {+ return options;+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/Proxy.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/Proxy.javanew file mode 100644index 000000000..90971c7f3--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/Proxy.java@@ -0,0 +1,151 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.proxy;++import org.slf4j.LoggerFactory;++import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.net.Socket;++public abstract class Proxy extends Thread {++ protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(Proxy.class);++ protected Socket consoleSocket;+ protected boolean halted;+ protected int timeout;+ protected byte[] consoleBuffer;+ protected int consoleBytesRead;++ public Proxy(Socket clientSocket, int timeout) throws IOException {+ this.consoleSocket = clientSocket;+ this.timeout = timeout;+ }++ @Override+ public void run() {+ try {+ logger.info("Client running");+ // we first need to connect to the endpoint+ Socket controllerSocket;+ try {+ controllerSocket = openDestinationSocket();+ } catch (IOException e) {+ logger.error("Failed to connect to the destination", e);+ return;+ }+ try {+ logger.info("We got connection to the destination");+ final byte[] request = new byte[1024];+ byte[] reply = new byte[4096];++ // Get client streams. Make them final so they can+ // be used in the anonymous thread below.+ final InputStream from_client = consoleSocket.getInputStream();+ final OutputStream to_client = consoleSocket.getOutputStream();++ // Get server streams.+ final InputStream from_server = controllerSocket.getInputStream();+ final OutputStream to_server = controllerSocket.getOutputStream();++ //Write the HTTP request which was already read when checking the authentication header+ to_server.write(consoleBuffer, 0, consoleBytesRead);+ to_server.flush();++ // Make a thread to read the client's requests and pass them+ // to the server. We have to use a separate thread because+ // requests and responses may be asynchronous.+ Thread t = new Thread() {+ public void run() {+ int bytes_read;+ try {+ while ((bytes_read = from_client.read(request)) != -1) {+ to_server.write(request, 0, bytes_read);+ to_server.flush();+ }+ } catch (IOException e) {+ e.printStackTrace();+ }++ // the client closed the connection to us, so close our+ // connection to the server. This will also cause the+ // server-to-client loop in the main thread exit.+ try {+ to_server.close();+ } catch (IOException e) {++ }+ }+ };++ // Start the client-to-server request thread running+ t.start();++ // Meanwhile, in the main thread, read the server's responses+ // and pass them back to the client. This will be done in+ // parallel with the client-to-server request thread above.+ int bytes_read;+ try {+ while ((bytes_read = from_server.read(reply)) != -1) {+ to_client.write(reply, 0, bytes_read);+ to_client.flush();+ }+ } catch (IOException e) {+ }++ // The server closed its connection to us, so we close our+ // connection to our client.+ // This will make the other thread exit.+ to_client.close();++ logger.info("Done with proxying");+ } catch (Exception e) {+ logger.error("Proxy dead", e);+ } finally {+ // close the dst socket+ try {+ controllerSocket.close();+ } catch (IOException x) {+ }+ }+ } finally {+ // close the src socket+ try {+ consoleSocket.close();+ } catch (IOException x) {+ }+ onProxyExit();+ }+ }++ protected void onProxyExit() {+ }++ protected abstract Socket openDestinationSocket() throws IOException;+++ public void halt() {+ halted = true;+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.javanew file mode 100644index 000000000..917977d1c--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.java@@ -0,0 +1,338 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.proxy;++import org.openremote.controllercommand.ControllerProxyAndCommandServiceApplication;+import org.openremote.controllercommand.domain.InitiateProxyControllerCommand;+import org.openremote.controllercommand.domain.User;+import org.openremote.controllercommand.service.AccountService;+import org.openremote.controllercommand.service.ControllerCommandService;+import org.slf4j.LoggerFactory;++import javax.net.ssl.SSLServerSocketFactory;+import javax.persistence.EntityManager;+import java.io.IOException;+import java.io.OutputStream;+import java.net.HttpURLConnection;+import java.net.InetSocketAddress;+import java.net.ServerSocket;+import java.net.Socket;+import java.nio.charset.Charset;+import java.util.regex.Matcher;+import java.util.regex.Pattern;++public class ProxyClient extends Proxy {++ protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(ProxyServer.class);++ private ProxyServer server;+ private String hostName;+ private int minClientPort;+ private int maxClientPort;+ private AccountService accountService;+ private ControllerCommandService controllerCommandService;+ private SSLServerSocketFactory sslServerSocketFactory;+ private ControllerProxyAndCommandServiceApplication application;++ public ProxyClient(ProxyServer server, Socket clientSocket, int timeout, String hostName, int minClientPort, int maxClientPort,+ ControllerCommandService controllerCommandService, AccountService accountService, SSLServerSocketFactory sslServerSocketFactory, ControllerProxyAndCommandServiceApplication application) throws IOException {+ super(clientSocket, timeout);+ this.server = server;+ this.hostName = hostName;+ this.minClientPort = minClientPort;+ this.maxClientPort = maxClientPort;+ this.accountService = accountService;+ this.controllerCommandService = controllerCommandService;+ this.sslServerSocketFactory = sslServerSocketFactory;+ this.application = application;+ }++ protected void onProxyExit() {+ server.unregister(this);+ }++ protected Socket openDestinationSocket() throws IOException {+ // this either returns a good user, or throws+ User user = authenticateUser();+ ServerSocket serverSocket;+ if (sslServerSocketFactory != null) {+ serverSocket = sslServerSocketFactory.createServerSocket();+ } else {+ serverSocket = new ServerSocket();+ }+ int localPort;+ try {+ logger.info("Binding socket for client");+ for (localPort = minClientPort; localPort <= maxClientPort; localPort++) {+ try {+ serverSocket.bind(new InetSocketAddress(localPort));+ if (serverSocket.getLocalPort() != -1) {+ break;+ }+ } catch (IOException ignoreAndContinue) {+ }+ }++ localPort = serverSocket.getLocalPort();+ if (localPort == -1) {+ throw new IOException("Could not bind local socket between ports " + minClientPort + " and " + maxClientPort);+ }+ logger.info("Socket bound to port " + localPort);++ // now let's tell the client we want connection here+ InitiateProxyControllerCommand controllerCommand = contactController(user, localPort);+ try {+ serverSocket.setSoTimeout(timeout);+ // now wait for the client to connect+ while (true) {+ Socket clientSocket = serverSocket.accept();+ if (halted) {+ break;+ }+ // we have a socket, let's cancel the key and return the client socket+ logger.info("We have a client, now let's check the token");+ // this throws on error+ checkToken(clientSocket, controllerCommand);+ return clientSocket;+ }+ // we timed out+ } finally {+ // we got contacted, or not but let's drop this command since we're not listening anymore+ EntityManager entityManager = application.createEntityManager();+ try {+ ControllerCommandService controllerCommandService = getControllerCommandService();+ controllerCommandService.closeControllerCommand(controllerCommand);+ controllerCommandService.update(entityManager, controllerCommand);+ application.commitEntityManager(entityManager);+ entityManager = null;+ } finally {+ if (entityManager != null) {+ application.rollbackEntityManager(entityManager);+ }+ }+ }+ } finally {+ try {+ serverSocket.close();+ } catch (IOException x) {+ // ignore in finally+ }++ }+ logger.info("Halted");+ throw new IOException("We've been halted");+ }++ private void checkToken(Socket clientSocket, InitiateProxyControllerCommand controllerCommand) throws IOException {+ try {+ byte[] token = controllerCommand.getToken().getBytes("ASCII");+ byte[] readToken = new byte[token.length];+ clientSocket.getInputStream().read(readToken);+ logger.info("Checking token");+ // we have read it all, now compare+ for (int i = 0; i < token.length; i++) {+ if (token[i] != readToken[i]) {+ throw new IOException("Client connected with invalid token");+ }+ }+ logger.info("Token is good");+ return;+ } catch (IOException x) {+ clientSocket.close();+ throw x;+ }+ }++ private User authenticateUser() throws IOException {+ // we need to read data from the client until we get the Authentication header+ try {+ logger.info("Reading HTTP headers");+ if (halted) {+ throw new IOException("Halted");+ }+ consoleBuffer = new byte[4096];+ consoleBytesRead = consoleSocket.getInputStream().read(consoleBuffer);+ if (consoleBytesRead == -1) {+ // we've reached EOF, drop this client+ throw new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED, false, false);+ }++ /* We read some more if we only receive 1 byte+ * see here: http://stackoverflow.com/questions/9358424/java-ssl-chrome-firefox-sends-g-in-http-header-instead-of-get-http-1-1+ */+ if (consoleBytesRead == 1) {+ consoleBytesRead = consoleSocket.getInputStream().read(consoleBuffer, 1, 4096);+ consoleBytesRead += 1;+ }++ // we have new data, let's look at it+ User user = getAuthenticatedUser(consoleBuffer, consoleBytesRead);+ if (user != null) {+ return user;+ }+ // for a timeout or were halted we just close the connection upstream by throwing+ throw new IOException("Connection timed-out before we could read the authentication header");+ } catch (HTTPException x) {+ // we must reply with an error+ throw sendError(consoleSocket, x.getStatus(), x.isJson(), x.isOptionsRequest());+ }+ }++ private IOException sendError(Socket srcSocket, int status, boolean json, boolean optionsRequest) throws IOException {+ // Construct the message+ String reason;+ String maybeHeader = "";+ String body = "";++ maybeHeader = "Access-Control-Allow-Origin: *\r\n";+ maybeHeader = maybeHeader + "Access-Control-Allow-Methods: GET, POST\r\n";+ maybeHeader = maybeHeader + "Access-Control-Allow-Headers: origin, authorization, accept\r\n";+ maybeHeader = maybeHeader + "Access-Control-Max-Age: 99999\r\n";++ switch (status) {+ case HttpURLConnection.HTTP_BAD_REQUEST:+ reason = "Bad request";+ break;+ case HttpURLConnection.HTTP_UNAUTHORIZED:+ reason = "Unauthorized";+ if (json) {+ status = 200;+ reason = "OK";+ body = "{\"error\": {\"code\": 401,\"message\": \"Not Authorized\"}}";+ } else {+ if (!optionsRequest) {+ maybeHeader = maybeHeader + "WWW-Authenticate: Basic realm=\"OPENREMOTE_Beehive\"\r\n";+ }+ }+ break;+ case HttpURLConnection.HTTP_FORBIDDEN:+ reason = "Forbidden";+ break;+ default:+ reason = "Unknown error";+ }+ if (optionsRequest) {+ status = 200;+ reason = "OK";+ }+ String response = "HTTP/1.1 " + status + " " + reason + "\r\n" + maybeHeader;+ if (body.length() != 0) {+ response = response + "Content-Length: " + body.length() + "\r\n";+ } else {+ response = response + "\r\n";+ }+ response = response + "\r\n" + body;++ byte[] dataToSend = response.getBytes("ASCII");+ // now send it+ OutputStream out = srcSocket.getOutputStream();+ out.write(dataToSend);+ out.flush();+ // we're done, let bail+ return new IOException("Error message (most likely wrong authentication data) was sent to client.");+ }++ private User getAuthenticatedUser(byte[] bytes, int length) throws HTTPException {+ // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4 says we should look for \r\nAuthorization:(.*)\r\n([^ \t]) as long+ // as it's not preceded by "\r\n\r\n" which indicates the end of the header section+ // we cannot parse data after the headers, but the headers are always in ASCII, so find that limit first+ int limit = length;+ int headerEnd = limit;+ for (int i = 0; i < limit - 3; i++) {+ if (bytes[i] == '\r'+ && bytes[i + 1] == '\n'+ && bytes[i + 2] == '\r'+ && bytes[i + 3] == '\n') {+ headerEnd = i + 4;+ break;+ }+ }+ // in any case, non-ASCII is after the end of headers, or since we haven't reached that yet, after the whole limit+ // so we can parse as ASCII characters+ String headers = new String(bytes, 0, headerEnd, Charset.forName("ASCII"));+ boolean optionsRequest = false;+ if (headers.startsWith("OPTIONS")) {+ optionsRequest = true;+ }+ // so do we have an Authentication header in there?+ Pattern pattern = Pattern.compile("\r\nAuthorization: ([^\r\n]*)\r\n([^ \t])", Pattern.CASE_INSENSITIVE);+ Pattern pattern2 = Pattern.compile("\r\nAccept:([^\r\n]*)\r\n([^ \t])", Pattern.CASE_INSENSITIVE);+ Matcher matcher = pattern.matcher(headers);+ Matcher matcher2 = pattern2.matcher(headers);+ boolean json = false;+ if (matcher2.find()) {+ if (matcher2.group(1).toLowerCase().indexOf("json") != -1) {+ json = true;+ }+ }+ // nothing?+ if (!matcher.find()) {+ if (headerEnd <= limit) {+ // we have seen every header, and found no good one, let's quit+ throw new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED, json, optionsRequest);+ }+ // we haven't seen the end of headers yet, don't give up and read more+ return null;+ }+ // we have a value!+ String value = matcher.group(1);+ // now fold it+ value = value.replaceAll("\r\n[ \t]+", " ").trim();+ // and attempt to validate it+ User user = null;+ EntityManager entityManager = application.createEntityManager();+ try {+ user = getAccountService().loadByHTTPBasicCredentials(entityManager, value);+ } finally {+ application.rollbackEntityManager(entityManager);+ }+ if (user == null) {+ // authentication failed+ throw new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED, json, optionsRequest);+ }+ return user;+ }++ protected ControllerCommandService getControllerCommandService() {+ return this.controllerCommandService;+ }++ protected AccountService getAccountService() {+ return this.accountService;+ }++ private InitiateProxyControllerCommand contactController(User user, int port) {+ InitiateProxyControllerCommand command = null;+ EntityManager entityManager = application.createEntityManager();+ try {+ ControllerCommandService controllerCommandService = getControllerCommandService();+ command = controllerCommandService.saveProxyControllerCommand(entityManager, user, ((sslServerSocketFactory != null) ? "https://" : "http://") + hostName + ":" + port);+ application.commitEntityManager(entityManager);+ entityManager = null;+ } finally {+ if (entityManager != null) {+ application.rollbackEntityManager(entityManager);+ }+ }+ return command;+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.javanew file mode 100644index 000000000..affdfa890--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.java@@ -0,0 +1,234 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.proxy;++import org.apache.commons.lang.StringUtils;+import org.openremote.controllercommand.ControllerProxyAndCommandServiceApplication;+import org.openremote.controllercommand.resources.ControllerCommandsResource;+import org.openremote.controllercommand.service.AccountService;+import org.openremote.controllercommand.service.ControllerCommandService;+import org.slf4j.LoggerFactory;++import javax.net.ssl.KeyManagerFactory;+import javax.net.ssl.SSLContext;+import javax.net.ssl.SSLServerSocketFactory;+import javax.net.ssl.TrustManagerFactory;+import java.io.FileInputStream;+import java.io.IOException;+import java.io.InputStream;+import java.net.ServerSocket;+import java.net.Socket;+import java.security.KeyStore;+import java.util.HashSet;+import java.util.Set;++public class ProxyServer extends Thread {++ protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(ProxyServer.class);++ private boolean halted = false;+ private Set<ProxyClient> clients = new HashSet<ProxyClient>();+ private String hostName;+ private int timeout;+ private int port;+ private int minClientPort;+ private int maxClientPort;+ private boolean useSSL;+ private String keystore;+ private String keystorePassword;+ private AccountService accountService;+ private ControllerCommandService controllerCommandService;+ private SSLServerSocketFactory sslServerSocketfactory = null;+ private ControllerProxyAndCommandServiceApplication application;++ public ProxyServer(String proxyHostname, Integer proxyTimeout, Integer proxyPort, String proxyClientPortRange, Boolean useSSL, String keystore,+ String keystorePassword, ControllerCommandService controllerCommandService, AccountService accountService, ControllerProxyAndCommandServiceApplication application) {+ this.accountService = accountService;+ this.controllerCommandService = controllerCommandService;+ this.application = application;++ if (StringUtils.isEmpty(proxyHostname)) {+ hostName = "localhost";+ } else {+ hostName = proxyHostname;+ }++ if (proxyTimeout == null) {+ timeout = 5000;+ } else {+ timeout = proxyTimeout.intValue();+ }++ if (proxyPort == null) {+ port = 10000;+ } else {+ port = proxyPort.intValue();+ }++ if (StringUtils.isEmpty(proxyClientPortRange)) {+ minClientPort = 0;+ maxClientPort = 0;+ } else {+ minClientPort = Integer.parseInt(proxyClientPortRange.trim().substring(0, proxyClientPortRange.indexOf("-")));+ maxClientPort = Integer.parseInt(proxyClientPortRange.trim().substring(proxyClientPortRange.indexOf("-") + 1, proxyClientPortRange.length()));+ }++ if (useSSL == null) {+ this.useSSL = false;+ } else {+ this.useSSL = useSSL;+ }++ if (this.useSSL && StringUtils.isEmpty(keystore)) {+ throw new RuntimeException("A keystore has to be specified when using SSL");+ } else {+ this.keystore = keystore;+ }++ if (this.useSSL && StringUtils.isEmpty(keystorePassword)) {+ throw new RuntimeException("A keystore password has to be specified when using SSL");+ } else {+ this.keystorePassword = keystorePassword;+ }++ if (useSSL) {+ // Specifying the Keystore details+ logger.info("Load keystore: " + this.keystore);+ InputStream keystoreStream = null;+ try {+ TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());+ KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());+ KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());++ // Path to keystore starts with a /, consider an absolute path and load as a file instead of a resource+ if (this.keystore.startsWith("/")) {+ try {+ keystoreStream = new FileInputStream(this.keystore);+ } catch (IOException e) {+ logger.error("The specified keystore " + this.keystore + " can not be loaded");+ throw new RuntimeException("The specified keystore " + this.keystore + " can not be loaded");+ }+ } else {+ keystoreStream = this.getClass().getResourceAsStream(this.keystore);+ }+ if (keystoreStream == null) {+ logger.error("The specified keystore " + this.keystore + " can not be loaded");+ throw new RuntimeException("The specified keystore " + this.keystore + " can not be loaded");+ }++ ks.load(keystoreStream, this.keystorePassword.toCharArray());+ logger.info("Keystore loaded, it contains " + ks.size() + ((ks.size() > 1) ? " entries" : " entry"));++ trustManagerFactory.init(ks);+ keyManagerFactory.init(ks, this.keystorePassword.toCharArray());++ SSLContext sc = SSLContext.getInstance("SSL");+ sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);+ sslServerSocketfactory = sc.getServerSocketFactory();+ } catch (Exception e) {+ throw new RuntimeException(e);+ } finally {+ if (keystoreStream != null) {+ try {+ keystoreStream.close();+ } catch (IOException e) {+ logger.warn("Failed to close stream to keystore", e);+ }+ }+ }+ }++ }++ @Override+ public void run() {+ logger.info("Proxy server starting up");+ ServerSocket server = null;+ try {+ if (useSSL) {+ // Initialize the SSL Server Socket+ logger.info("Starting SSL proxy server on port: " + port);+ server = sslServerSocketfactory.createServerSocket(port);+ } else {+ // Create a ServerSocket to listen for incoming console connections+ logger.info("Starting proxy server on port: " + port);+ server = new ServerSocket(port);+ }++ logger.info("Entering loop");+ while (true) {+ // Wait for a connection on the local port+ Socket clientSocket = server.accept();+ logger.info("Accepting a client socket");+ synchronized (clients) {+ if (halted) {+ break;+ }+ acceptConnection(clientSocket);+ }+ }+ logger.info("Exited loop");+ } catch (Exception e) {+ logger.error("Server died", e);+ } finally {+ if (server != null)+ try {+ server.close();+ } catch (IOException e) {+ }+ }+ }++ private void acceptConnection(Socket clientSocket) {+ try {+ logger.info("Got a client socket");+ ProxyClient client = new ProxyClient(this, clientSocket, timeout, hostName, minClientPort, maxClientPort, controllerCommandService,+ accountService, sslServerSocketfactory, application);+ clients.add(client);+ logger.info("Starting client");+ client.start();+ logger.info("Client started");+ } catch (Exception x) {+ // make sure we close this one if needed+ try {+ clientSocket.close();+ } catch (IOException e) {+ // ignore+ }+ }+ }++ public void halt() {+ synchronized (clients) {+ halted = true;+ for (Proxy client : clients) {+ client.halt();+ }+ }+ }++ public void unregister(Proxy proxyClient) {+ synchronized (clients) {+ clients.remove(proxyClient);+ }+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandResource.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandResource.javanew file mode 100644index 000000000..ba8969162--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandResource.java@@ -0,0 +1,134 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.resources;++import flexjson.JSONSerializer;+import org.json.JSONException;+import org.json.JSONObject;+import org.openremote.beehive.EntityTransactionFilter;+import org.openremote.controllercommand.ControllerProxyAndCommandServiceApplication;+import org.openremote.controllercommand.domain.Account;+import org.openremote.controllercommand.domain.ControllerCommand;+import org.openremote.controllercommand.domain.ControllerCommandDTO;+import org.openremote.controllercommand.domain.ControllerCommandDTO.Type;+import org.openremote.controllercommand.domain.User;+import org.openremote.controllercommand.service.AccountService;+import org.openremote.controllercommand.service.ControllerCommandService;+import org.openremote.rest.GenericResourceResultWithErrorMessage;++import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import javax.inject.Inject;+import javax.persistence.EntityManager;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.BadRequestException;+import javax.ws.rs.Consumes;+import javax.ws.rs.DELETE;+import javax.ws.rs.POST;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++@Path("/")+public class ControllerCommandResource {+ @Inject+ private ControllerCommandService controllerCommandService;++ @Inject+ private AccountService accountService;++ protected final static Logger log = LoggerFactory.getLogger(ControllerCommandResource.class);++ /**+ * Mark the controllerCommand with the given id as DONE<p>+ * REST Url: /rest/command/{commandId}+ *+ * @return ResultObject with String "ok"+ */+ @DELETE+ @Path("command/{commandId}")+ @Produces(MediaType.APPLICATION_JSON)+ public Response ackControllerCommands(@Context HttpServletRequest request, @PathParam("commandId") String commandId) {+ GenericResourceResultWithErrorMessage result = null;+ try {+ if (commandId != null) {+ log.info("Asked to acknowledge command with id " + commandId);+ Long id = Long.valueOf(commandId);+ ControllerCommand controllerCommand = controllerCommandService.findControllerCommandById(getEntityManager(request), id);+ controllerCommandService.closeControllerCommand(controllerCommand);+ controllerCommandService.update(getEntityManager(request), controllerCommand);+ result = new GenericResourceResultWithErrorMessage(null, "ok");+ } else {+ result = new GenericResourceResultWithErrorMessage("command not found", null);+ }+ } catch (Exception e) {+ log.error("Error while acknowledging a ControllerCommand", e);+ result = new GenericResourceResultWithErrorMessage(e.getMessage(), null);+ }+ return Response.ok(new JSONSerializer().exclude("*.class").deepSerialize(result)).build();+ }++ @POST+ @Path("command")+ @Consumes(MediaType.APPLICATION_JSON)+ @Produces(MediaType.APPLICATION_JSON)+ public Response saveCommand(@Context HttpServletRequest request, String jsonString) {+ if (jsonString == null) {+ throw new BadRequestException("No data received");+ }++ String username = request.getUserPrincipal().getName();++ User user = accountService.loadByUsername(getEntityManager(request), username);+ Account account = user.getAccount();++ try {+ JSONObject jsonData = new JSONObject(jsonString);+ String typeAsString = jsonData.getString("type");+ if (typeAsString == null) {+ throw new BadRequestException("Type must be provided");+ }+ try {+ ControllerCommandDTO.Type type = Type.valueOf(typeAsString.trim().toUpperCase());+ if (Type.DOWNLOAD_DESIGN != type) {+ throw new BadRequestException("Unsupported command type");+ }+ ControllerCommand command = new ControllerCommand(account, Type.DOWNLOAD_DESIGN);+ controllerCommandService.save(getEntityManager(request), command);+ GenericResourceResultWithErrorMessage result = new GenericResourceResultWithErrorMessage(null, command);+ return Response.ok(new JSONSerializer().exclude("*.class").exclude("result.account").deepSerialize(result)).build();+ } catch (IllegalArgumentException e) {+ throw new BadRequestException("Unknown command type");+ }+ } catch (JSONException e) {+ throw new BadRequestException("Invalid JSON payload");+ }+ }++ private EntityManager getEntityManager(HttpServletRequest request) {+ return (EntityManager) request.getAttribute(EntityTransactionFilter.PERSISTENCE_ENTITY_MANAGER_LOOKUP);+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandsResource.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandsResource.javanew file mode 100644index 000000000..8e9a88bd4--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandsResource.java@@ -0,0 +1,91 @@+/*+ * OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2016, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.resources;++import flexjson.JSONSerializer;+import org.openremote.beehive.EntityTransactionFilter;+import org.openremote.controllercommand.domain.ControllerCommandDTO;+import org.openremote.controllercommand.service.ControllerCommandService;+import org.openremote.rest.GenericResourceResultWithErrorMessage;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import javax.inject.Inject;+import javax.persistence.EntityManager;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.GET;+import javax.ws.rs.Path;+import javax.ws.rs.PathParam;+import javax.ws.rs.Produces;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;+import java.util.ArrayList;+import java.util.List;++/**+ * @author <a href="mailto:[email protected]">Eric Bariaux</a>+ */+@Path("/")+public class ControllerCommandsResource {+ @Inject+ private ControllerCommandService controllerCommandService;++ protected final static Logger log = LoggerFactory.getLogger(ControllerCommandsResource.class);++ /**+ * Return a list of all not finished ControllerCommands<p>+ * REST Url: /rest/commands/{controllerOid} -> return all not finished controller commands for the given controllerOid+ *+ * @return a List of ControllerCommand+ */++ @GET+ @Path("commands/{controllerOid}")+ @Produces(MediaType.APPLICATION_JSON)+ public Response loadControllerCommands(@Context HttpServletRequest request, @PathParam("controllerOid") String controllerOid) {+ GenericResourceResultWithErrorMessage result = null;+ try {+ if (controllerOid != null) {+ log.info("Asked to get controller commands list for controller id " + controllerOid);+ Long id = Long.valueOf(controllerOid);++ String username = request.getUserPrincipal().getName();+ log.info("Query done by " + username);++ List<ControllerCommandDTO> commands = controllerCommandService.queryByControllerOidForUser(getEntityManager(request), id, username);+ result = new GenericResourceResultWithErrorMessage(null, commands);+ } else {+ log.info("No controller oid provided");+ result = new GenericResourceResultWithErrorMessage(null, new ArrayList<ControllerCommandDTO>());+ }+ } catch (Exception e) {+ log.error("Error getting controller commands", e);+ result = new GenericResourceResultWithErrorMessage(e.getMessage(), null);+ }+ return Response.ok(new JSONSerializer().exclude("*.class").deepSerialize(result)).build();+ }++ private EntityManager getEntityManager(HttpServletRequest request) {+ return (EntityManager) request.getAttribute(EntityTransactionFilter.PERSISTENCE_ENTITY_MANAGER_LOOKUP);+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/service/AccountService.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/service/AccountService.javanew file mode 100644index 000000000..a09a73539--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/service/AccountService.java@@ -0,0 +1,67 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2010, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.service;++import org.apache.commons.codec.binary.Base64;+import org.openremote.controllercommand.GenericDAO;+import org.openremote.controllercommand.domain.User;+import org.springframework.security.authentication.encoding.Md5PasswordEncoder;++import javax.persistence.EntityManager;+++/**+ * Account service implementation.+ *+ * @author Dan Cong+ */+public class AccountService {+ public static final String HTTP_AUTH_HEADER_NAME = "Authorization";+ public static final String HTTP_BASIC_AUTH_HEADER_VALUE_PREFIX = "Basic ";++ protected GenericDAO genericDAO;++ public void setGenericDAO(GenericDAO genericDAO) {+ this.genericDAO = genericDAO;+ }++ public User loadByUsername(EntityManager entityManager, String username) {+ return genericDAO.getByNonIdField(entityManager, User.class, "username", username);+ }++ public User loadByHTTPBasicCredentials(EntityManager entityManager, String credentials) {+ if (credentials.startsWith(HTTP_BASIC_AUTH_HEADER_VALUE_PREFIX)) {+ credentials = credentials.replaceAll(HTTP_BASIC_AUTH_HEADER_VALUE_PREFIX, "");+ credentials = new String(Base64.decodeBase64(credentials.getBytes()));+ String[] arr = credentials.split(":");+ if (arr.length == 2) {+ String username = arr[0];+ String password = arr[1];+ User user = loadByUsername(entityManager, username);+ String encodedPassword = new Md5PasswordEncoder().encodePassword(password, username);+ if (user != null && user.getPassword().equals(encodedPassword)) {+ return user;+ }+ }+ }+ // let's be lax and not throw a BAD_REQUEST to allow the user to retry+ return null;+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.javanew file mode 100644index 000000000..fdb319dfe--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.java@@ -0,0 +1,123 @@+/* OpenRemote, the Home of the Digital Home.+ * Copyright 2008-2011, OpenRemote Inc.+ *+ * See the contributors.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.controllercommand.service;++import org.openremote.controllercommand.GenericDAO;+import org.openremote.controllercommand.domain.Account;+import org.openremote.controllercommand.domain.Controller;+import org.openremote.controllercommand.domain.ControllerCommand;+import org.openremote.controllercommand.domain.ControllerCommand.State;+import org.openremote.controllercommand.domain.ControllerCommandDTO;+import org.openremote.controllercommand.domain.InitiateProxyControllerCommand;+import org.openremote.controllercommand.domain.User;++import javax.persistence.EntityManager;+import javax.persistence.NoResultException;+import javax.persistence.criteria.CriteriaBuilder;+import javax.persistence.criteria.CriteriaQuery;+import javax.persistence.criteria.Fetch;+import javax.persistence.criteria.Predicate;+import javax.persistence.criteria.Root;+import java.util.ArrayList;+import java.util.Collections;+import java.util.List;++/**+ * ControllerCommand service implementation.+ *+ * @author Stef Epardaud+ */+public class ControllerCommandService {++ protected GenericDAO genericDAO;++ public void setGenericDAO(GenericDAO genericDAO) {+ this.genericDAO = genericDAO;+ }++ public void save(EntityManager entityManager, ControllerCommand c) {+ entityManager.persist(c);+ }++ public List<ControllerCommandDTO> queryByControllerOidForUser(EntityManager entityManager, Long oid, String username) {+ User u = genericDAO.getByNonIdField(entityManager, User.class, "username", username);+++ CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();+ CriteriaQuery<Controller> controllerQuery = criteriaBuilder.createQuery(Controller.class);+ Root<Controller> controllerRoot = controllerQuery.from(Controller.class);+ Fetch<Controller, Account> accountJoin = controllerRoot.fetch("account");+ accountJoin.fetch("users");+ controllerQuery.select(controllerRoot);+ controllerQuery.where(criteriaBuilder.equal(controllerRoot.get("oid"), oid));+ Controller controller;+ try {+ controller = entityManager.createQuery(controllerQuery).getSingleResult();+ } catch (NoResultException e) {+ return Collections.emptyList();+ }++ // Only return commands if the user making the request has access to the account linked to the controller+ if (!controller.getAccount().getUsers().contains(u)) {+ return Collections.emptyList();+ }++ CriteriaQuery<ControllerCommand> controllerCommandQuery = criteriaBuilder.createQuery(ControllerCommand.class);+ Root<ControllerCommand> controllerCommandRoot = controllerCommandQuery.from(ControllerCommand.class);+ controllerCommandQuery.select(controllerCommandRoot);+ Predicate criteria = criteriaBuilder.equal(controllerCommandRoot.get("account"), controller.getAccount());+ criteria = criteriaBuilder.and(criteria, criteriaBuilder.equal(controllerCommandRoot.get("state"), State.OPEN));+ controllerCommandQuery.where(criteria);+ controllerCommandQuery.orderBy(criteriaBuilder.asc(controllerCommandRoot.get("creationDate")));++ List<ControllerCommand> list = entityManager.createQuery(controllerCommandQuery).getResultList();+ List<ControllerCommandDTO> result = new ArrayList<ControllerCommandDTO>(list.size());+ for (ControllerCommand cmd : list) {+ ControllerCommandDTO dto = new ControllerCommandDTO();+ dto.setOid(cmd.getOid());+ dto.setCommandType(cmd.getType().getLabel());+ if (cmd instanceof InitiateProxyControllerCommand) {+ dto.addParameter("token", ((InitiateProxyControllerCommand) cmd).getToken());+ dto.addParameter("url", ((InitiateProxyControllerCommand) cmd).getUrl());+ }+ result.add(dto);+ }+ return result;+ }++ public InitiateProxyControllerCommand saveProxyControllerCommand(EntityManager entityManager, User user, String url) {+ InitiateProxyControllerCommand command = new InitiateProxyControllerCommand(user.getAccount(), ControllerCommandDTO.Type.INITIATE_PROXY, url);+ save(entityManager, command);+ return command;+ }++ public void closeControllerCommand(ControllerCommand controllerCommand) {+ controllerCommand.setState(State.DONE);+ }++ public ControllerCommand findControllerCommandById(EntityManager entityManager, Long id) {+ return entityManager.find(ControllerCommand.class, id);+ }++ public void update(EntityManager entityManager, ControllerCommand controllerCommand) {+ entityManager.merge(controllerCommand);+ }++}diff --git a/beehive/ccs/src/main/resources/CreateTables.sql b/beehive/ccs/src/main/resources/CreateTables.sqlnew file mode 100644index 000000000..1cc108cc3--- /dev/null+++ b/beehive/ccs/src/main/resources/CreateTables.sql@@ -0,0 +1,38 @@+CREATE TABLE IF NOT EXISTS `controller` (+ `oid` BIGINT(20) NOT NULL AUTO_INCREMENT,+ `linked` TINYINT(1) NOT NULL,+ `macAddress` VARCHAR(255) NULL DEFAULT NULL,+ `account_oid` BIGINT(20) NULL DEFAULT NULL,+ PRIMARY KEY (`oid`) ,+ INDEX `IDX__CONTROLLER__ACCOUNT_OID` (`account_oid` ASC) ,+ CONSTRAINT `FK__CONTROLLER__ACCOUNT__ACCOUNT_OID`+ FOREIGN KEY (`account_oid`)+ REFERENCES `account` (`oid`))+ENGINE = InnoDB+DEFAULT CHARACTER SET = utf8;++CREATE TABLE IF NOT EXISTS `controller_command` (+ `oid` BIGINT(20) NOT NULL AUTO_INCREMENT,+ `creationDate` DATETIME NULL DEFAULT NULL,+ `state` VARCHAR(255) NULL DEFAULT NULL,+ `type` VARCHAR(255) NULL DEFAULT NULL,+ `account_oid` BIGINT(20) NULL DEFAULT NULL,+ PRIMARY KEY (`oid`) ,+ INDEX `IDX__CONTROLLER_COMMAND__ACCOUNT_OID` (`account_oid` ASC) ,+ CONSTRAINT `FK__CONTROLLER_COMMAND__ACCOUNT__ACCOUNT_OID`+ FOREIGN KEY (`account_oid`)+ REFERENCES `account` (`oid`))+ENGINE = InnoDB+DEFAULT CHARACTER SET = utf8;++CREATE TABLE IF NOT EXISTS `initiate_proxy_controller_command` (+ `oid` BIGINT(20) NOT NULL,+ `token` VARCHAR(255) NULL DEFAULT NULL,+ `url` VARCHAR(255) NULL DEFAULT NULL,+ PRIMARY KEY (`oid`) ,+ INDEX `IDX__INITIATE_PROXY_CONTROLLER_COMMAND__OID` (`oid` ASC) ,+ CONSTRAINT `FK__INITIATE_PROXY_CONTROLLER_COMMAND__CONTROLLER_COMMAND__OID`+ FOREIGN KEY (`oid`)+ REFERENCES `controller_command` (`oid`))+ENGINE = InnoDB+DEFAULT CHARACTER SET = utf8;\ No newline at end of filediff --git a/beehive/ccs/src/main/resources/META-INF/persistence.xml b/beehive/ccs/src/main/resources/META-INF/persistence.xmlnew file mode 100644index 000000000..be9d6c060--- /dev/null+++ b/beehive/ccs/src/main/resources/META-INF/persistence.xml@@ -0,0 +1,68 @@+<?xml version="1.0" encoding="UTF-8"?>++<!--+ OpenRemote, the Home of the Digital Home.+ Copyright 2008-2016, OpenRemote Inc.++ See the contributors.txt file in the distribution for a+ full listing of individual contributors.++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as+ published by the Free Software Foundation; either version 3 of the+ License, or (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program; if not, see <http://www.gnu.org/licenses/>.+-->++<persistence+ xmlns="http://java.sun.com/xml/ns/persistence"+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence+ http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"+ version="2.0">++ <persistence-unit name="CCS-MySQL">+ <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>++ <class>org.openremote.controllercommand.domain.Account</class>+ <class>org.openremote.controllercommand.domain.User</class>+ <class>org.openremote.controllercommand.domain.Controller</class>+ <class>org.openremote.controllercommand.domain.ControllerCommand</class>+ <class>org.openremote.controllercommand.domain.InitiateProxyControllerCommand</class>++ <properties>+ <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>+ <!-- TODO Should we use SSL to connect to database? -->+ <property name="javax.persistence.jdbc.url"+ value="jdbc:mysql://mysql:3306/openremote?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>++ <property name="javax.persistence.jdbc.user" value="openremote"/>+ <property name="javax.persistence.jdbc.password" value="CHANGE_ME_DB_USER_PASSWORD"/>++ <property name="hibernate.cache.provider_class" value="org.hibernate.cache.internal.NoCacheProvider"/>+ <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>+ <property name="hibernate.hbm2ddl.auto" value="validate"/>+ <property name="hibernate.current_session_context_class" value="managed"/>++ <property name="hibernate.connection.provider_class"+ value="org.hibernate.c3p0.internal.C3P0ConnectionProvider"/>+ <property name="hibernate.c3p0.min_size" value="5"/>+ <property name="hibernate.c3p0.max_size" value="20"/>+ <property name="hibernate.c3p0.acquire_increment" value="5"/>+ <property name="hibernate.c3p0.max_statements" value="50"/>+ <property name="hibernate.c3p0.timeout" value="1800"/>+ <property name="hibernate.c3p0.idle_test_period" value="10"/>+ <property name="hibernate.c3p0.testConnectionOnCheckin" value="true"/>+ <property name="hibernate.c3p0.preferredTestQuery" value="SELECT 1"/>+ </properties>++ </persistence-unit>++</persistence>\ No newline at end of filediff --git a/beehive/ccs/src/main/resources/config.properties b/beehive/ccs/src/main/resources/config.propertiesnew file mode 100644index 000000000..181eabe51--- /dev/null+++ b/beehive/ccs/src/main/resources/config.properties@@ -0,0 +1,10 @@+persistenceUnitName=CCS-MySQL+persistenceCreateSchema=true++proxy.hostname=localhost+proxy.timeout=10000+proxy.port=10000+proxy.clientPortRange=30000-30010+proxy.useSSL=true+proxy.keystore=/keystore.ks+proxy.keystorePassword=storepassdiff --git a/beehive/ccs/src/main/webapp/WEB-INF/web.xml b/beehive/ccs/src/main/webapp/WEB-INF/web.xmlnew file mode 100644index 000000000..a116cad08--- /dev/null+++ b/beehive/ccs/src/main/webapp/WEB-INF/web.xml@@ -0,0 +1,116 @@+<?xml version="1.0" encoding="UTF-8"?>+<web-app id="WebApp_ID" version="2.4"+ xmlns="http://java.sun.com/xml/ns/j2ee"+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"+ xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee+ http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">+ <display-name>DeviceDiscovery Service</display-name>++ <!--+ =================================================================================================++ Map servlet Java class implementations to URLs.++ This mapping links the JAX-RS 2.0 implementation to Glassfish Jersey based implementation+ of the API.++ =================================================================================================+ -->+++ <servlet>+ <servlet-name>Jersey Servlet Container for CCS</servlet-name>++ <!-- Jersey implementation -->++ <servlet-class>+ org.glassfish.jersey.servlet.ServletContainer+ </servlet-class>++ <!-- JAX-RS 2.0 configuration to link JAX-RS application -->++ <init-param>+ <param-name>javax.ws.rs.Application</param-name>+ <param-value>org.openremote.controllercommand.ControllerProxyAndCommandServiceApplication</param-value>+ </init-param>++ <load-on-startup>1</load-on-startup>+ </servlet>+++ <!--++ URL Mapping:++ As per the Beehive REST API design convention, all REST API calls start with '/rest' path.++ -->++ <servlet-mapping>+ <servlet-name>Jersey Servlet Container for CCS</servlet-name>+ <url-pattern>/rest/*</url-pattern>+ </servlet-mapping>++ <!--+ =================================================================================================++ Security Configuration++ This configuration section establishes role-based access to (by default) all of the CCS resources.+ Each resource access requires at minimum a basic authentication to access.++ =================================================================================================+ -->+++ <security-constraint>++ <display-name>Controller Proxy And Command Service Security</display-name>++ <!--+ Defines an URL pattern to include all resource access to CCS.+ The HTTP method elements are not included meaning all HTTP requests must conform+ to the configured security constraints...+ -->+ <web-resource-collection>++ <web-resource-name>All Service Access to CCS</web-resource-name>++ <description>+ This configuration constraints all HTTP method access to all of the CCS resources.+ </description>++ <url-pattern>/*</url-pattern>++ </web-resource-collection>+++ <!-- User roles required to access CCS resources... -->++ <auth-constraint>+ <role-name>ROLE_ADMIN</role-name>+ </auth-constraint>++ </security-constraint>+++ <!-- At minimum, require HTTP Basic authorization... -->++ <login-config>+ <auth-method>BASIC</auth-method>+ <realm-name>ControllerProxyAndCommandService</realm-name>+ </login-config>++ <!-- Define the security roles... -->++ <security-role>++ <description>+ ROLE_ADMIN is the administrator role for a specific account (it's the account owner).+ </description>++ <role-name>ROLE_ADMIN</role-name>++ </security-role>++</web-app>diff --git a/beehive/ccs/src/test/java/org/openremote/controllercommand/rest/ControllerCommandTests.java b/beehive/ccs/src/test/java/org/openremote/controllercommand/rest/ControllerCommandTests.javanew file mode 100644index 000000000..ca070a983--- /dev/null+++ b/beehive/ccs/src/test/java/org/openremote/controllercommand/rest/ControllerCommandTests.java@@ -0,0 +1,9 @@+package org.openremote.controllercommand.rest;++import org.junit.Ignore;++@Ignore+public class ControllerCommandTests+{++}diff --git a/build.gradle b/build.gradleindex f433894d1..365094aff 100644--- a/build.gradle+++ b/build.gradle@@ -19,6 +19,9 @@ allprojects {maven {url "https://oss.sonatype.org/content/repositories/snapshots/"}+ maven {+ url "http://m2repo.openremote.com/content/groups/public/"+ }}version = projectVersiondiff --git a/controller/Dockerfile b/controller/Dockerfileindex 7b0e69582..d75081631 100644--- a/controller/Dockerfile+++ b/controller/Dockerfile@@ -18,7 +18,6 @@ ADD conf/GVconfig.txt /opt/or-resources/data/GVconfig.txt# Fix some permissionsUSER root-RUN apt-get update && apt-get -y install netcatRUN chown -R openremote.openremote /opt/or-resourcesUSER openremotediff --git a/controller/build.gradle b/controller/build.gradleindex cefc6ccb5..507ce4509 100644--- a/controller/build.gradle+++ b/controller/build.gradle@@ -1,7 +1,5 @@import com.bmuschko.gradle.docker.tasks.image.*-ext.dockerImageName = "$dockerRepository/$project.name:$imageVersion".toString()-task buildImage(type: DockerBuildImage) {inputDir = projectDirdockerFile = file("$projectDir/Dockerfile")diff --git a/controller/conf/keystore.jks b/controller/conf/keystore.jksindex af98bdbae..1f8436961 100644Binary files a/controller/conf/keystore.jks and b/controller/conf/keystore.jks differdiff --git a/controller/conf/truststore.jks b/controller/conf/truststore.jksindex 9683ff9d3..8bca9b6e2 100644Binary files a/controller/conf/truststore.jks and b/controller/conf/truststore.jks differdiff --git a/gradle.properties b/gradle.propertiesindex 54190f1a7..2b48df711 100644--- a/gradle.properties+++ b/gradle.properties@@ -32,4 +32,13 @@ camelVersion = 2.16.2tyrusVersion = 1.10geojsonJacksonVersion = 1.6# Explicit dependency can be removed with Camel 2.18.x, then AHC 2.x is the default-ahcVersion = 1.9.39\ No newline at end of file+ahcVersion = 1.9.39+servletVersion = 3.1.0+flexjsonVersion = 2.1+springVersion = 3.1.1.RELEASE+commonsLangVersion = 2.4+commonsCodecVersion = 1.3+commonsDbcpVersion = 1.2.1+mysqlConnectorVersion = 5.1.17+jaxrsVersion = 2.0.1+jerseyVersion = 2.22diff --git a/profile/README.md b/profile/README.mdindex 3ca0a77d8..864ed56a5 100644--- a/profile/README.md+++ b/profile/README.md@@ -34,8 +34,10 @@ keytool -list -v \-keystore /tmp/or-keystore.jks \-storepass CHANGE_ME_SSL_KEY_STORE_PASSWORD-cp /tmp/or-keystore.jks demo-controller/conf/keystore.jks-cp /tmp/or-truststore.jks demo-controller/conf/truststore.jks+cp /tmp/or-keystore.jks controller/conf/keystore.jks+cp /tmp/or-truststore.jks controller/conf/truststore.jks++cp /tmp/or-keystore.jks beehive/ccs/conf/keystore.jks```@@ -50,11 +52,7 @@ TODO: Old Tomcat can't have separate key and store passwords...## Deploying profiles```-docker-compose -p <my_project_name> -f profile/mysql.yml -f profile/ccs.yml up-```+./gradlew -p beehive/ccs clean war-For example, to run a Controller and CCS:--```-dc -p my_project -f profile/dependencies/mysql.yml -f profile/ccs.yml+docker-compose -p <my_project_name> -f profile/mysql.yml -f profile/ccs.yml up```diff --git a/profile/ccs.yml b/profile/ccs.ymlindex 4557a7f7a..51fed732a 100644--- a/profile/ccs.yml+++ b/profile/ccs.yml@@ -5,24 +5,34 @@## - mysql#+# Create a RUN CONFIGURATION in your IDE:+#+# -version: '2'services:controller:- image: openremote/controller:latest+ build:+ context: ../../controllerenvironment:TZ: "Europe/Zurich"- JAVA_OPTS: -Djavax.net.ssl.trustStore=\/opt\/or-resources\/truststore.jks+ JAVA_OPTS: -Djavax.net.ssl.trustStore=\/opt\/OpenRemote-Controller\/truststore.jks -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=nSSL_KEY_STORE_PASSWORD: "CHANGE_ME_SSL_KEY_STORE_PASSWORD"- BEEHIVE_REMOTE_SERVICE_URI: "https://css:8443/css/rest"+ SSL_DISABLE_HOSTNAME_VERIFICATION: "true"+ BEEHIVE_REMOTE_SERVICE_URI: "https://ccs:8443/ccs/rest"CONTROLLER_CONSOLE_THRESHOLD: "INFO"links:- ccsports:- "8688:8688"+ - "8000:8000"ccs:- image: openremote/ccs:latest+ build:+ context: ../../beehive/ccs+ ports:+ - "8443:8443"+ - "5005:5005"# TODO Why is this necessary? Is CCS connecting with itself?extra_hosts:- "ccs:127.0.0.1"@@ -31,8 +41,9 @@ services:BEEHIVE_DB_PASSWORD: "CHANGE_ME_DB_USER_PASSWORD"BEEHIVE_DB_DRIVER: "com.mysql.jdbc.Driver"BEEHIVE_DB_URL: "jdbc:mysql://mysql:3306/openremote"- SSL_KEYSTORE_PASSWORD: "CHANGE_ME_SSL_KEY_STORE_PASSWORD"+ SSL_KEY_STORE_PASSWORD: "CHANGE_ME_SSL_KEY_STORE_PASSWORD"+ TOMCAT_DEBUG: "true"+ JPDA_ADDRESS: "5005"+ JPDA_SUSPEND: "n"links:- mysql- ports:- - "8443:8443"diff --git a/profile/ccs_dev.yml b/profile/ccs_dev.ymldeleted file mode 100644index 9a2b1d616..000000000--- a/profile/ccs_dev.yml+++ /dev/null@@ -1,43 +0,0 @@-#-# Controller Commmand Service (Remote Proxy)-#-# This profile requires dependencies:-#-# - mysql-#-version: '2'-services:-- controller:- build:- context: ../demo-controller- dockerfile: Dockerfile- environment:- TZ: "Europe/Zurich"- JAVA_OPTS: -Djavax.net.ssl.trustStore=\/opt\/or-resources\/truststore -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n- SSL_KEY_STORE_PASSWORD: "CHANGE_ME_SSL_KEY_STORE_PASSWORD"- BEEHIVE_REMOTE_SERVICE_URI: "https://css:8443/css/rest"- CONTROLLER_CONSOLE_THRESHOLD: "INFO"- ports:- - "8688:8688"- - "8000:8000"-- ccs:- image: openremote/ccs:latest- ports:- - "8443:8443"- - "5005:5005"- # TODO Why is this necessary? Is CCS connecting with itself?- extra_hosts:- - "ccs:127.0.0.1"- environment:- BEEHIVE_DB_USERNAME: "openremote"- BEEHIVE_DB_PASSWORD: "CHANGE_ME_DB_USER_PASSWORD"- BEEHIVE_DB_DRIVER: "com.mysql.jdbc.Driver"- BEEHIVE_DB_URL: "jdbc:mysql://mysql:3306/openremote"- SSL_KEY_STORE_PASSWORD: "CHANGE_ME_SSL_KEY_STORE_PASSWORD"- TOMCAT_DEBUG: "true"- JPDA_ADDRESS: "5005"- JPDA_SUSPEND: "n"- links:- - mysqldiff --git a/profile/dependencies/mysql.yml b/profile/dependencies/mysql.ymlindex eb5cd512c..d1f645d02 100644--- a/profile/dependencies/mysql.yml+++ b/profile/dependencies/mysql.yml@@ -5,7 +5,8 @@ version: '2'services:mysql:- image: openremote/mysql:latest+ build:+ context: ../../base/mysqlenvironment:TZ: "Europe/Zurich"# This is the database superuser@@ -15,4 +16,4 @@ services:MYSQL_USER: openremoteMYSQL_PASSWORD: "CHANGE_ME_DB_USER_PASSWORD"ports:- - "3306:3306"+ - "3306:3306"\ No newline at end of filediff --git a/profile/dependencies/mysql_dev.yml b/profile/dependencies/mysql_dev.ymldeleted file mode 100644index 505a30c71..000000000--- a/profile/dependencies/mysql_dev.yml+++ /dev/null@@ -1,22 +0,0 @@-#-# DEVELOPER VERSION-#-# MySQL database service(s)-#-version: '2'-services:-- mysql:- build:- context: ../../base/mysql- dockerfile: Dockerfile- environment:- TZ: "Europe/Zurich"- # This is the database superuser- MYSQL_ROOT_PASSWORD: "CHANGE_ME_DB_ROOT_PASSWORD"- # Create default database when started (see scripts)- MYSQL_DATABASE: openremote- MYSQL_USER: openremote- MYSQL_PASSWORD: "CHANGE_ME_DB_USER_PASSWORD"- ports:- - "3306:3306"diff --git a/settings.gradle b/settings.gradleindex 2d094b609..ad6ac7373 100644--- a/settings.gradle+++ b/settings.gradle@@ -6,6 +6,7 @@ include "base:postgres","base:keycloak","container","controller",+ "beehive:ccs","manager:shared","manager:server","manager:client",