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
Started migration of CCS to v3 container
Christian Bauer35677e443b45
diff --git a/README.md b/README.mdindex 256552171..a7d3ee441 100644--- a/README.md+++ b/README.md@@ -33,4 +33,11 @@ This is the platform project of OpenRemote, where we integrate services and codeTODO: Document other projects+```+docker-compose -p myproject -f profile/dependencies/postgresql.yml -f profile/dependencies/keycloak.yml up+org.openremote.ccs.Server#main()++GET localhost:8080/master/command/controller/123+(Should result in 403 NOT ALLOWED)+```diff --git a/base/tomcat/Dockerfile b/base/tomcat/Dockerfiledeleted file mode 100644index d1a5aceec..000000000--- a/base/tomcat/Dockerfile+++ /dev/null@@ -1,15 +0,0 @@-FROM tomcat:7.0.73-jre8--# Remove default webapps-RUN rm -rf /usr/local/tomcat/webapps/*--ADD conf/server_tpl.xml conf/-ADD lib/* lib/-ADD run.sh ./--# Reduce startup time-ENV JAVA_OPTS -Djava.security.egd=file:/dev/urandom--EXPOSE 8443--CMD /usr/local/tomcat/run.sh\ No newline at end of filediff --git a/base/tomcat/build.gradle b/base/tomcat/build.gradledeleted file mode 100644index ab5008a88..000000000--- a/base/tomcat/build.gradle+++ /dev/null@@ -1,12 +0,0 @@-import com.bmuschko.gradle.docker.tasks.image.*--task buildBaseImage(type: DockerBuildImage) {- inputDir = projectDir- dockerFile = file("$projectDir/Dockerfile")- tag = dockerImageName-}--task pushImage(type: DockerPushImage) {- dependsOn buildBaseImage- imageName = dockerImageName-}\ No newline at end of filediff --git a/base/tomcat/conf/server_tpl.xml b/base/tomcat/conf/server_tpl.xmldeleted file mode 100644index 6fbd23ca7..000000000--- a/base/tomcat/conf/server_tpl.xml+++ /dev/null@@ -1,160 +0,0 @@-<?xml version='1.0' encoding='utf-8'?>-<!--- Licensed to the Apache Software Foundation (ASF) under one or more- contributor license agreements. See the NOTICE file distributed with- this work for additional information regarding copyright ownership.- The ASF licenses this file to You under the Apache License, Version 2.0- (the "License"); you may not use this file except in compliance with- the License. You may obtain a copy of the License at-- http://www.apache.org/licenses/LICENSE-2.0-- Unless required by applicable law or agreed to in writing, software- distributed under the License is distributed on an "AS IS" BASIS,- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.- See the License for the specific language governing permissions and- limitations under the License.--->-<!-- Note: A "Server" is not itself a "Container", so you may not- define subcomponents such as "Valves" at this level.- Documentation at /docs/config/server.html- -->-<Server port="8005" shutdown="SHUTDOWN">- <Listener className="org.apache.catalina.startup.VersionLoggerListener"/>- <!-- Security listener. Documentation at /docs/config/listeners.html- <Listener className="org.apache.catalina.security.SecurityListener" />- -->- <!--APR library loader. Documentation at /docs/apr.html -->- <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on"/>- <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->- <Listener className="org.apache.catalina.core.JasperListener"/>- <!-- Prevent memory leaks due to use of particular java/javax APIs-->- <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>- <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>- <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>-- <!-- Global JNDI resources- Documentation at /docs/jndi-resources-howto.html- -->- <GlobalNamingResources>- <!-- Editable user database that can also be used by- UserDatabaseRealm to authenticate users- -->- <Resource name="UserDatabase" auth="Container"- type="org.apache.catalina.UserDatabase"- description="User database that can be updated and saved"- factory="org.apache.catalina.users.MemoryUserDatabaseFactory"- pathname="conf/tomcat-users.xml"/>-- <Resource name="jdbc/AuthDB" auth="Container" type="javax.sql.DataSource"- maxActive="100" maxIdle="30" maxWait="10000"- username="${BEEHIVE_DB_USERNAME}" password="${BEEHIVE_DB_PASSWORD}"- driverClassName="${BEEHIVE_DB_DRIVER}"- url="${BEEHIVE_DB_URL}"- validationQuery="/* ping */ SELECT 1" testWhileIdle="true"/>- </GlobalNamingResources>-- <!-- A "Service" is a collection of one or more "Connectors" that share- a single "Container" Note: A "Service" is not itself a "Container",- so you may not define subcomponents such as "Valves" at this level.- Documentation at /docs/config/service.html- -->- <Service name="Catalina">-- <!--The connectors can use a shared executor, you can define one or more named thread pools-->- <!--- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"- maxThreads="150" minSpareThreads="4"/>- -->--- <!-- A "Connector" represents an endpoint by which requests are received- and responses are returned. Documentation at :- Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)- Java AJP Connector: /docs/config/ajp.html- APR (HTTP/AJP) Connector: /docs/apr.html- Define a non-SSL HTTP/1.1 Connector on port 8080- -->- <!--- <Connector port="8080" protocol="HTTP/1.1"- connectionTimeout="20000"- redirectPort="8443" /> -->- <!-- A "Connector" using the shared thread pool-->- <!--- <Connector executor="tomcatThreadPool"- port="8080" protocol="HTTP/1.1"- connectionTimeout="20000"- redirectPort="8443" />- -->- <!-- Define a SSL HTTP/1.1 Connector on port 8443- This connector uses the BIO implementation that requires the JSSE- style configuration. When using the APR/native implementation, the- OpenSSL style configuration is required as described in the APR/native- documentation -->- <!--<Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"- maxThreads="150" SSLEnabled="true" scheme="https" secure="true"- clientAuth="false" sslProtocol="TLS" /> -->- <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"- connectionTimeout="-1"- maxThreads="150" SSLEnabled="true" scheme="https" secure="true"- keystoreFile="keystore.jks" keystorePass="${SSL_KEY_STORE_PASSWORD}"- clientAuth="false" sslProtocol="TLS"/>-- <!-- Define an AJP 1.3 Connector on port 8009 -->- <Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>--- <!-- An Engine represents the entry point (within Catalina) that processes- every request. The Engine implementation for Tomcat stand alone- analyzes the HTTP headers included with the request, and passes them- on to the appropriate Host (virtual host).- Documentation at /docs/config/engine.html -->-- <!-- You should set jvmRoute to support load-balancing via AJP ie :- <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">- -->- <Engine name="Catalina" defaultHost="localhost">-- <!--For clustering, please take a look at documentation at:- /docs/cluster-howto.html (simple how to)- /docs/config/cluster.html (reference documentation) -->- <!--- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>- -->-- <!-- Use the LockOutRealm to prevent attempts to guess user passwords- via a brute-force attack -->- <Realm className="org.apache.catalina.realm.LockOutRealm">- <!-- This Realm uses the UserDatabase configured in the global JNDI- resources under the key "UserDatabase". Any edits- that are performed against this UserDatabase are immediately- available for use by the Realm. -->- <Realm className="org.apache.catalina.realm.UserDatabaseRealm"- resourceName="UserDatabase"/>- <Realm className="org.openremote.tomcat.realm.LegacyBeehiveDataSourceRealm"- dataSourceName="jdbc/AuthDB" digest="md5" debug="99"- userTable="user" userNameCol="username" userCredCol="password"- userRoleTable="tomcat_user_role" roleNameCol="rolename"/>- </Realm>-- <Host name="localhost" appBase="webapps"- unpackWARs="true" autoDeploy="true">-- <!-- SingleSignOn valve, share authentication between web applications- Documentation at: /docs/config/valve.html -->- <!--- <Valve className="org.apache.catalina.authenticator.SingleSignOn" />- -->-- <!-- Access log processes all example.- Documentation at: /docs/config/valve.html- Note: The pattern used is equivalent to using pattern="common" -->- <!--- <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"- prefix="localhost_access_log." suffix=".txt"- pattern="%h %l %u %t "%r" %s %b" />- -->- </Host>- </Engine>- </Service>-</Server>diff --git a/base/tomcat/lib/mysql-connector-java-5.1.39-bin.jar b/base/tomcat/lib/mysql-connector-java-5.1.39-bin.jardeleted file mode 100644index dac6e1498..000000000Binary files a/base/tomcat/lib/mysql-connector-java-5.1.39-bin.jar and /dev/null differdiff --git a/base/tomcat/lib/or-tomcat-extensions-1.0.0.jar b/base/tomcat/lib/or-tomcat-extensions-1.0.0.jardeleted file mode 100644index 8b012cdb5..000000000Binary files a/base/tomcat/lib/or-tomcat-extensions-1.0.0.jar and /dev/null differdiff --git a/base/tomcat/run.sh b/base/tomcat/run.shdeleted file mode 100755index dfecf2bc9..000000000--- a/base/tomcat/run.sh+++ /dev/null@@ -1,3 +0,0 @@-#!/usr/bin/env bash-perl -p -i -e 's/\$\{([^}]+)\}/defined $ENV{$1} ? $ENV{$1} : $&/eg' < conf/server_tpl.xml > conf/server.xml-exec ${CATALINA_HOME}/bin/catalina.sh rundiff --git a/beehive/ccs/build.gradle b/beehive/ccs/build.gradleindex 40cb9264b..0630faa87 100644--- a/beehive/ccs/build.gradle+++ b/beehive/ccs/build.gradle@@ -1,73 +1,52 @@apply plugin: "java"-apply plugin: "war"+apply plugin: "application"++mainClassName = "org.openremote.ccs.Server"dependencies {+ compile project(":container")+compile "org.openremote:or-commons:0.1.0"compile "org.openremote:or-object-model:0.2.1"+ // TODO Replace with Jacksoncompile "org.json:json:20090211"-compile "net.sf.flexjson:flexjson:$flexjsonVersion"- compile "org.slf4j:slf4j-api:$slf4jVersion"- compile "org.slf4j:slf4j-jdk14:$slf4jVersion"- compile "org.slf4j:jcl-over-slf4j:$slf4jVersion"- compile "org.slf4j:log4j-over-slf4j:$slf4jVersion"-- 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')+distributions {+ main {+ contents {+ from("conf") {+ into "conf"}- } else {- println "*** No configuration exists for target environment"}- } else {- println "*** No target environment defined"}}+installDist {+ into "${buildDir}/install/$distributions.main.baseName"+}+import com.bmuschko.gradle.docker.tasks.image.*+task createDockerfile(type: Dockerfile) {+ destFile = project.file("$project.buildDir/install/Dockerfile")+ from "java:8"+ environmentVariable "WEBSERVER_DOCROOT", "webapp"+ environmentVariable "LOGGING_CONFIG_FILE", "conf/logging.properties"+ addFile project(':beehive:ccs').distributions.main.baseName, "/opt/app"+ exposePort 8080+ workingDir "/opt/app"+ entryPoint "/opt/app/bin/${project(":beehive:ccs").name}"+}+task buildImage(type: DockerBuildImage) {- dependsOn war+ dependsOn ":beehive:ccs:installDist", createDockerfileinputDir = projectDir- dockerFile = file("$projectDir/Dockerfile")tag = dockerImageName}diff --git a/beehive/ccs/conf/logging.properties b/beehive/ccs/conf/logging.propertiesindex 4e2634e70..e9ff67d51 100644--- a/beehive/ccs/conf/logging.properties+++ b/beehive/ccs/conf/logging.properties@@ -1,10 +1,28 @@-handlers = java.util.logging.ConsoleHandler+# This configuration file is used in the Manager's Docker image, it's the default+# configuration we ship to users.-.level = INFO-org.openremote.level = INFO-org.hibernate.level = INFO+handlers=java.util.logging.ConsoleHandler-org.apache.catalina.realm.level = ALL-org.apache.catalina.realm.useParentHandlers = true-org.apache.catalina.authenticator.level = ALL-org.apache.catalina.authenticator.useParentHandlers = true+java.util.logging.ConsoleHandler.formatter=org.openremote.container.util.LogFormatter+java.util.logging.ConsoleHandler.level=FINEST++.level=WARNING++org.openremote.level=INFO+org.openremote.container.message.level=WARNING++# Low-level debugging+org.hibernate.level=WARNING+com.zaxxer.hikari.level=WARNING+javax.management.level=WARNING+org.xnio.level=WARNING+org.apache.camel.management.level=WARNING+org.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING++# Set this to FINEST to log outgoing HTTP traffic+org.apache.http.level=WARNING+org.apache.http.impl.conn.DefaultClientConnection.level=WARNING++# Set this to FINEST to log SQL execution+#org.hibernate.SQL.level=FINEST+#org.hibernate.type.descriptor.sql.BasicBinder.level=FINESTdiff --git a/beehive/ccs/src/main/java/org/openremote/ccs/CCSIdentityService.java b/beehive/ccs/src/main/java/org/openremote/ccs/CCSIdentityService.javanew file mode 100644index 000000000..7d68a4c29--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/CCSIdentityService.java@@ -0,0 +1,40 @@+package org.openremote.ccs;++import org.keycloak.admin.client.resource.ClientResource;+import org.keycloak.admin.client.resource.ClientsResource;+import org.keycloak.admin.client.resource.RolesResource;+import org.keycloak.representations.idm.ClientRepresentation;+import org.keycloak.representations.idm.RoleRepresentation;+import org.openremote.container.Container;++import static org.openremote.ccs.Constants.APP_CLIENT_ID;+import static org.openremote.ccs.Constants.APP_NAME;++public class CCSIdentityService extends org.openremote.container.security.IdentityService {++ protected Container container;++ @Override+ public void init(Container container) throws Exception {+ this.container = container;+ setClientId(APP_CLIENT_ID);+ super.init(container);+ }++ public void createClientApplication(String bearerAuth, String realm) {+ ClientsResource clientsResource = getRealms(bearerAuth, false).realm(realm).clients();+ ClientRepresentation client = createClientApplication(+ realm, getClientId(), APP_NAME, container.isDevMode()+ );+ clientsResource.create(client);+ client = clientsResource.findByClientId(client.getClientId()).get(0);+ ClientResource clientResource = clientsResource.get(client.getId());+ addDefaultRoles(clientResource.roles());+ }++ public void addDefaultRoles(RolesResource rolesResource) {+ rolesResource.create(new RoleRepresentation("account-owner", "Account owner", false));+ rolesResource.create(new RoleRepresentation("service-admin", "Service administrator", false));+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.java b/beehive/ccs/src/main/java/org/openremote/ccs/CCSPersistenceService.javasimilarity index 54%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.javarename to beehive/ccs/src/main/java/org/openremote/ccs/CCSPersistenceService.javaindex fdb319dfe..0c6988a37 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/service/ControllerCommandService.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/CCSPersistenceService.java@@ -1,55 +1,49 @@-/* 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;+package org.openremote.ccs;-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.apache.commons.codec.binary.Base64;+import org.openremote.ccs.model.*;+import org.openremote.container.persistence.PersistenceService;import org.openremote.controllercommand.domain.ControllerCommandDTO;-import org.openremote.controllercommand.domain.InitiateProxyControllerCommand;-import org.openremote.controllercommand.domain.User;+import org.springframework.security.authentication.encoding.Md5PasswordEncoder;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 javax.persistence.criteria.*;import java.util.ArrayList;import java.util.Collections;import java.util.List;-/**- * ControllerCommand service implementation.- *- * @author Stef Epardaud- */-public class ControllerCommandService {+public class CCSPersistenceService extends PersistenceService {- protected GenericDAO genericDAO;+ public static final String HTTP_AUTH_HEADER_NAME = "Authorization";+ public static final String HTTP_BASIC_AUTH_HEADER_VALUE_PREFIX = "Basic ";- public void setGenericDAO(GenericDAO genericDAO) {- this.genericDAO = genericDAO;+ public User loadByUsername(EntityManager entityManager, String username) {+ CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();+ CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);+ Root<User> root = query.from(User.class);+ query.select(root);+ query.where(criteriaBuilder.equal(root.get("username"), username));+ return entityManager.createQuery(query).getSingleResult();+ }++ 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;}public void save(EntityManager entityManager, ControllerCommand c) {@@ -57,10 +51,14 @@ public class ControllerCommandService {}public List<ControllerCommandDTO> queryByControllerOidForUser(EntityManager entityManager, Long oid, String username) {- User u = genericDAO.getByNonIdField(entityManager, User.class, "username", username);-CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();+ CriteriaQuery<User> query = criteriaBuilder.createQuery(User.class);+ Root<User> root = query.from(User.class);+ query.select(root);+ query.where(criteriaBuilder.equal(root.get("username"), username));+ User u = entityManager.createQuery(query).getSingleResult();+CriteriaQuery<Controller> controllerQuery = criteriaBuilder.createQuery(Controller.class);Root<Controller> controllerRoot = controllerQuery.from(Controller.class);Fetch<Controller, Account> accountJoin = controllerRoot.fetch("account");@@ -83,15 +81,15 @@ public class ControllerCommandService {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));+ criteria = criteriaBuilder.and(criteria, criteriaBuilder.equal(controllerCommandRoot.get("state"), ControllerCommand.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());+ List<ControllerCommandDTO> result = new ArrayList<>(list.size());for (ControllerCommand cmd : list) {ControllerCommandDTO dto = new ControllerCommandDTO();- dto.setOid(cmd.getOid());+ dto.setOid(cmd.getId());dto.setCommandType(cmd.getType().getLabel());if (cmd instanceof InitiateProxyControllerCommand) {dto.addParameter("token", ((InitiateProxyControllerCommand) cmd).getToken());@@ -107,17 +105,4 @@ public class ControllerCommandService {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/java/org/openremote/ccs/CCSWebService.java b/beehive/ccs/src/main/java/org/openremote/ccs/CCSWebService.javanew file mode 100644index 000000000..aab852182--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/CCSWebService.java@@ -0,0 +1,23 @@+package org.openremote.ccs;++import org.openremote.container.Container;+import org.openremote.container.web.WebService;++public class CCSWebService extends WebService {++ @Override+ public void init(Container container) throws Exception {+ super.init(container);+ setDefaultRealm(Constants.MASTER_REALM);+ }++ @Override+ public void configure(Container container) throws Exception {++ container.getService(WebService.class).getApiSingletons().add(+ new ControllerCommandResourceImpl(container.getService(CCSPersistenceService.class))+ );++ super.configure(container);+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/Constants.java b/beehive/ccs/src/main/java/org/openremote/ccs/Constants.javanew file mode 100644index 000000000..e07a3b654--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/Constants.java@@ -0,0 +1,29 @@+/*+ * Copyright 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.ccs;++public interface Constants {++ String APP_NAME = "OpenRemote Controller Command Service";+ String APP_CLIENT_ID = "or-ccs";+ String MASTER_REALM = "master";+ String MASTER_REALM_ADMIN_USER = "admin";+ String PERSISTENCE_SEQUENCE_ID_GENERATOR = "SEQUENCE_ID_GENERATOR";+}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResource.java b/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResource.javanew file mode 100644index 000000000..9965de3cd--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResource.java@@ -0,0 +1,46 @@+package org.openremote.ccs;++import jsinterop.annotations.JsType;++import javax.annotation.security.RolesAllowed;+import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.*;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;++@Path("command")+@JsType(isNative = true)+public interface ControllerCommandResource {++ @POST+ @Consumes(MediaType.APPLICATION_JSON)+ @Produces(MediaType.APPLICATION_JSON)+ @RolesAllowed({"account-owner", "service-admin"})+ Response saveCommand(@Context HttpServletRequest request, String jsonString);++ /**+ * Mark the controllerCommand with the given id as DONE<p>+ * REST Url: /rest/command/{commandId}+ *+ * @return ResultObject with String "ok"+ */+ @DELETE+ @Path("{commandId}")+ @Produces(MediaType.APPLICATION_JSON)+ @RolesAllowed({"account-owner", "service-admin"})+ Response ackControllerCommands(@Context HttpServletRequest request, @PathParam("commandId") String commandId);++ /**+ * 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("controller/{controllerId}")+ @Produces(MediaType.APPLICATION_JSON)+ @RolesAllowed({"account-owner", "service-admin"})+ Response loadControllerCommands(@Context HttpServletRequest request, @PathParam("controllerId") String controllerId);++}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResourceImpl.java b/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResourceImpl.javanew file mode 100644index 000000000..0370cdf80--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/ControllerCommandResourceImpl.java@@ -0,0 +1,138 @@+/*+ * 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.ccs;++import flexjson.JSONSerializer;+import org.json.JSONException;+import org.json.JSONObject;+import org.openremote.ccs.model.Account;+import org.openremote.ccs.model.ControllerCommand;+import org.openremote.ccs.model.User;+import org.openremote.container.web.WebResource;+import org.openremote.controllercommand.domain.ControllerCommandDTO;+import org.openremote.controllercommand.domain.ControllerCommandDTO.Type;+import org.openremote.rest.GenericResourceResultWithErrorMessage;++import javax.servlet.http.HttpServletRequest;+import javax.ws.rs.BadRequestException;+import javax.ws.rs.core.Context;+import javax.ws.rs.core.Response;+import java.util.ArrayList;+import java.util.List;+import java.util.logging.Level;+import java.util.logging.Logger;++public class ControllerCommandResourceImpl extends WebResource implements ControllerCommandResource {++ private static final Logger LOG = Logger.getLogger(ControllerCommandResourceImpl.class.getName());++ final protected CCSPersistenceService persistenceService;++ public ControllerCommandResourceImpl(CCSPersistenceService persistenceService) {+ this.persistenceService = persistenceService;+ }++ @Override+ public Response saveCommand(@Context HttpServletRequest request, String jsonString) {+ if (jsonString == null) {+ throw new BadRequestException("No data received");+ }++ String username = request.getUserPrincipal().getName();++ return persistenceService.doReturningTransaction(entityManager -> {+ try {+ User user = persistenceService.loadByUsername(entityManager, username);+ Account account = user.getAccount();++ 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);+ persistenceService.save(entityManager, 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");+ }+ });+ }++ @Override+ public Response ackControllerCommands(@Context HttpServletRequest request, String commandId) {+ GenericResourceResultWithErrorMessage result = null;+ try {+ if (commandId != null) {+ LOG.info("Asked to acknowledge command with id " + commandId);+ Long id = Long.valueOf(commandId);+ persistenceService.doTransaction(entityManager -> {+ ControllerCommand controllerCommand = entityManager.find(ControllerCommand.class, id);+ controllerCommand.setState(ControllerCommand.State.DONE);+ controllerCommand = entityManager.merge(controllerCommand);+ });+ result = new GenericResourceResultWithErrorMessage(null, "ok");+ } else {+ result = new GenericResourceResultWithErrorMessage("command not found", null);+ }+ } catch (Exception ex) {+ LOG.log(Level.SEVERE, "Error while acknowledging a ControllerCommand", ex);+ result = new GenericResourceResultWithErrorMessage(ex.getMessage(), null);+ }+ return Response.ok(new JSONSerializer().exclude("*.class").deepSerialize(result)).build();+ }++ @Override+ public Response loadControllerCommands(@Context HttpServletRequest request, String controllerId) {+ GenericResourceResultWithErrorMessage result = null;+ try {+ if (controllerId != null) {+ LOG.info("Asked to get controller commands list for controller id " + controllerId);+ Long id = Long.valueOf(controllerId);++ String username = request.getUserPrincipal().getName();+ LOG.info("Query done by " + username);++ result = persistenceService.doReturningTransaction(entityManager -> {+ List<ControllerCommandDTO> commands = persistenceService.queryByControllerOidForUser(entityManager, id, username);+ return new GenericResourceResultWithErrorMessage(null, commands);+ });+ } else {+ LOG.info("No controller oid provided");+ result = new GenericResourceResultWithErrorMessage(null, new ArrayList<ControllerCommandDTO>());+ }+ } catch (Exception ex) {+ LOG.log(Level.SEVERE, "Error getting controller commands", ex);+ result = new GenericResourceResultWithErrorMessage(ex.getMessage(), null);+ }+ return Response.ok(new JSONSerializer().exclude("*.class").deepSerialize(result)).build();+ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/DemoDataService.java b/beehive/ccs/src/main/java/org/openremote/ccs/DemoDataService.javanew file mode 100644index 000000000..00ba1b037--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/DemoDataService.java@@ -0,0 +1,122 @@+/*+ * Copyright 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.ccs;++import org.apache.log4j.Logger;+import org.keycloak.admin.client.resource.*;+import org.keycloak.representations.idm.ClientRepresentation;+import org.keycloak.representations.idm.RealmRepresentation;+import org.openremote.container.Container;+import org.openremote.container.ContainerService;+import org.openremote.container.persistence.PersistenceService;+import org.openremote.container.security.AuthForm;+import rx.Observable;++import static org.openremote.ccs.Constants.*;+import static rx.Observable.fromCallable;++public class DemoDataService implements ContainerService {++ private static final Logger LOG = Logger.getLogger(DemoDataService.class.getName());++ public static final String IMPORT_DEMO_DATA = "IMPORT_DEMO_DATA";+ public static final boolean IMPORT_DEMO_DATA_DEFAULT = false;++ public static final String ADMIN_CLI_CLIENT_ID = "admin-cli";+ public static final String ADMIN_PASSWORD = "admin";++ protected Container container;+ protected PersistenceService persistenceService;+ protected CCSIdentityService identityService;++ @Override+ public void init(Container container) throws Exception {+ this.container = container;+ persistenceService = container.getService(PersistenceService.class);+ identityService = container.getService(CCSIdentityService.class);+ }++ @Override+ public void configure(Container container) throws Exception {++ }++ @Override+ public void start(Container container) {+ if (!container.isDevMode() && !container.getConfigBoolean(IMPORT_DEMO_DATA, IMPORT_DEMO_DATA_DEFAULT)) {+ return;+ }++ LOG.info("--- IMPORTING DEMO DATA ---");++ // Use a non-proxy client to get the access token+ String accessToken = identityService.getKeycloak().getAccessToken(+ MASTER_REALM, new AuthForm(ADMIN_CLI_CLIENT_ID, MASTER_REALM_ADMIN_USER, ADMIN_PASSWORD)+ ).getToken();++ try {+ configureMasterRealm(accessToken);++ LOG.info("--- DEMO DATA IMPORT COMPLETE ---");+ } catch (Exception ex) {+ throw new RuntimeException(ex);+ }+ }++ @Override+ public void stop(Container container) {+ }++ protected void configureMasterRealm(String accessToken) {+ RealmResource realmResource = identityService.getRealms(accessToken, false).realm(MASTER_REALM);+ ClientsResource clientsResource = identityService.getRealms(accessToken, false).realm(MASTER_REALM).clients();+ UsersResource usersResource = identityService.getRealms(accessToken, false).realm(MASTER_REALM).users();++ RealmRepresentation masterRealm = realmResource.toRepresentation();++ masterRealm.setDisplayName("Master");++ identityService.configureRealm(masterRealm, 300);++ realmResource.update(masterRealm);++ // Find out if there is a client already present for this application, if so, delete it+ fromCallable(clientsResource::findAll)+ .flatMap(Observable::from)+ .filter(clientRepresentation -> clientRepresentation.getClientId().equals(APP_CLIENT_ID))+ .map(ClientRepresentation::getId)+ .subscribe(clientObjectId -> {+ clientsResource.get(clientObjectId).remove();+ });++ identityService.createClientApplication(accessToken, masterRealm.getRealm());++ String clientObjectId = fromCallable(() -> clientsResource.findByClientId(APP_CLIENT_ID))+ .flatMap(Observable::from)+ .map(ClientRepresentation::getId)+ .toBlocking().singleOrDefault(null);++ ClientResource clientResource = clientsResource.get(clientObjectId);+ RolesResource rolesResource = clientResource.roles();++ // TODO User and role mappings+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/Server.java b/beehive/ccs/src/main/java/org/openremote/ccs/Server.javanew file mode 100644index 000000000..e689d0668--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/Server.java@@ -0,0 +1,20 @@+package org.openremote.ccs;++import org.openremote.ccs.proxy.ProxyService;+import org.openremote.container.Container;+import org.openremote.container.message.MessageBrokerService;++public class Server {++ public static void main(String[] args) throws Exception {+ new Container(+ new MessageBrokerService(),+ new CCSWebService(),+ new CCSIdentityService(),+ new CCSPersistenceService(),+ new ProxyService(),+ new DemoDataService()+ ).startBackground();+ }++}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.java b/beehive/ccs/src/main/java/org/openremote/ccs/model/Account.javasimilarity index 72%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/Account.javaindex 126c97175..a3678b0e3 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Account.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/Account.java@@ -17,13 +17,12 @@* 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;+package org.openremote.ccs.model;import javax.persistence.Entity;import javax.persistence.OneToMany;import javax.persistence.Table;+import java.util.List;/*** The Class Account.@@ -34,16 +33,7 @@ import javax.persistence.Table;@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")@@ -63,21 +53,4 @@ public class Account extends BusinessEntity {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/ccs/model/BusinessEntity.javasimilarity index 57%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/BusinessEntity.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/BusinessEntity.javaindex 34d835149..eaf95ec7b 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/BusinessEntity.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/BusinessEntity.java@@ -18,69 +18,37 @@* along with this program. If not, see <http://www.gnu.org/licenses/>.*/-package org.openremote.controllercommand.domain;+package org.openremote.ccs.model;-import java.io.Serializable;+import org.openremote.ccs.Constants;import javax.persistence.GeneratedValue;-import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.MappedSuperclass;+import java.io.Serializable;--/**- * Business entity class for all JPA entities with the common property oid.- *- * @author Marcus- */@MappedSuperclasspublic abstract class BusinessEntity implements Serializable {- /**- * The Constant serialVersionUID.- */- private static final long serialVersionUID = 754736926051991600L;-- /**- * The oid.- */- private long oid;+ private Long id;- /**- * Instantiates a new business entity.- */public BusinessEntity() {super();}- /**- * Instantiates a new business entity.- *- * @param oid the oid- */- public BusinessEntity(long oid) {+ public BusinessEntity(long id) {super();- this.oid = oid;+ this.id = id;}- /**- * Gets the oid.- *- * @return the oid- */@Id- @GeneratedValue(strategy = GenerationType.AUTO)- public long getOid() {- return oid;+ @GeneratedValue(generator = Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR)+ public Long getId() {+ return id;}- /**- * Sets the oid.- *- * @param oid the new oid- */- public void setOid(long oid) {- this.oid = oid;+ public void setId(long id) {+ this.id = id;}}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.java b/beehive/ccs/src/main/java/org/openremote/ccs/model/Controller.javasimilarity index 93%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/Controller.javaindex 3c74e4785..ff5ddcc71 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/Controller.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/Controller.java@@ -17,7 +17,10 @@* 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;+package org.openremote.ccs.model;++import org.openremote.ccs.model.Account;+import org.openremote.ccs.model.BusinessEntity;import javax.persistence.Entity;import javax.persistence.ManyToOne;diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.java b/beehive/ccs/src/main/java/org/openremote/ccs/model/ControllerCommand.javasimilarity index 96%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/ControllerCommand.javaindex 8ec025650..dd26350f8 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/ControllerCommand.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/ControllerCommand.java@@ -17,7 +17,9 @@* 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;+package org.openremote.ccs.model;++import org.openremote.controllercommand.domain.ControllerCommandDTO;import java.util.Date;@@ -45,7 +47,6 @@ public class ControllerCommand extends BusinessEntity {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.diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.java b/beehive/ccs/src/main/java/org/openremote/ccs/model/InitiateProxyControllerCommand.javasimilarity index 94%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/InitiateProxyControllerCommand.javaindex 2fde48a60..7c2a10695 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/InitiateProxyControllerCommand.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/InitiateProxyControllerCommand.java@@ -18,7 +18,9 @@* 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;+package org.openremote.ccs.model;++import org.openremote.controllercommand.domain.ControllerCommandDTO;import java.util.UUID;diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.java b/beehive/ccs/src/main/java/org/openremote/ccs/model/User.javasimilarity index 63%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.javarename to beehive/ccs/src/main/java/org/openremote/ccs/model/User.javaindex 13f5c27f9..b6ae755e2 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/domain/User.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/model/User.java@@ -18,7 +18,7 @@* 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;+package org.openremote.ccs.model;import javax.persistence.Column;import javax.persistence.Entity;@@ -26,32 +26,15 @@ import javax.persistence.ManyToOne;import javax.persistence.Table;import javax.persistence.Transient;--/**- * TODO- *- * @author Marcus- */@Entity-@Table(name = "user")+@Table(name = "users")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();}@@ -60,64 +43,33 @@ public class User extends BusinessEntity {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- */@ManyToOnepublic Account getAccount() {return account;}- /**- * Sets the account.- *- * @param account the new account- */public void setAccount(Account account) {this.account = account;}-@Transientpublic String getRawPassword() {return rawPassword;@@ -127,21 +79,4 @@ public class User extends BusinessEntity {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/ccs/proxy/HTTPException.javasimilarity index 96%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/HTTPException.javarename to beehive/ccs/src/main/java/org/openremote/ccs/proxy/HTTPException.javaindex 031440b20..6e5679146 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/HTTPException.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/HTTPException.java@@ -18,7 +18,7 @@* 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;+package org.openremote.ccs.proxy;@SuppressWarnings("serial")public class HTTPException extends Exception {diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.java b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyClient.javasimilarity index 65%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.javarename to beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyClient.javaindex 917977d1c..3c6aab604 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyClient.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyClient.java@@ -18,51 +18,154 @@* 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;+package org.openremote.ccs.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 org.openremote.ccs.CCSPersistenceService;+import org.openremote.ccs.model.ControllerCommand;+import org.openremote.ccs.model.InitiateProxyControllerCommand;+import org.openremote.ccs.model.User;import javax.net.ssl.SSLServerSocketFactory;-import javax.persistence.EntityManager;import java.io.IOException;+import java.io.InputStream;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.logging.Level;+import java.util.logging.Logger;import java.util.regex.Matcher;import java.util.regex.Pattern;-public class ProxyClient extends Proxy {+public class ProxyClient extends Thread {- protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(ProxyServer.class);+ private static final Logger LOG = Logger.getLogger(ProxyClient.class.getName());++ protected Socket consoleSocket;+ protected boolean halted;+ protected int timeout;+ protected byte[] consoleBuffer;+ protected int consoleBytesRead;private ProxyServer server;private String hostName;private int minClientPort;private int maxClientPort;- private AccountService accountService;- private ControllerCommandService controllerCommandService;+ private CCSPersistenceService persistenceService;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);+ CCSPersistenceService persistenceService, SSLServerSocketFactory sslServerSocketFactory) throws IOException {+ this.consoleSocket = clientSocket;+ this.timeout = timeout;this.server = server;this.hostName = hostName;this.minClientPort = minClientPort;this.maxClientPort = maxClientPort;- this.accountService = accountService;- this.controllerCommandService = controllerCommandService;+ this.persistenceService = persistenceService;this.sslServerSocketFactory = sslServerSocketFactory;- this.application = application;+ }++ @Override+ public void run() {+ try {+ LOG.info("Client running");+ // we first need to connect to the endpoint+ Socket controllerSocket;+ try {+ controllerSocket = openDestinationSocket();+ } catch (IOException e) {+ LOG.log(Level.SEVERE, "Failed to connect to the destination", e);+ return;+ }+ try {+ LOG.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();++ LOG.info("Done with proxying");+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "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();+ }+ }++ public void halt() {+ halted = true;}protected void onProxyExit() {@@ -80,7 +183,7 @@ public class ProxyClient extends Proxy {}int localPort;try {- logger.info("Binding socket for client");+ LOG.info("Binding socket for client");for (localPort = minClientPort; localPort <= maxClientPort; localPort++) {try {serverSocket.bind(new InetSocketAddress(localPort));@@ -95,7 +198,7 @@ public class ProxyClient extends Proxy {if (localPort == -1) {throw new IOException("Could not bind local socket between ports " + minClientPort + " and " + maxClientPort);}- logger.info("Socket bound to port " + localPort);+ LOG.info("Socket bound to port " + localPort);// now let's tell the client we want connection hereInitiateProxyControllerCommand controllerCommand = contactController(user, localPort);@@ -108,7 +211,7 @@ public class ProxyClient extends Proxy {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");+ LOG.info("We have a client, now let's check the token");// this throws on errorcheckToken(clientSocket, controllerCommand);return clientSocket;@@ -116,18 +219,10 @@ public class ProxyClient extends Proxy {// 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);- }- }+ persistenceService.doTransaction(entityManager -> {+ controllerCommand.setState(ControllerCommand.State.DONE);+ entityManager.merge(controllerCommand);+ });}} finally {try {@@ -137,7 +232,7 @@ public class ProxyClient extends Proxy {}}- logger.info("Halted");+ LOG.info("Halted");throw new IOException("We've been halted");}@@ -146,14 +241,14 @@ public class ProxyClient extends Proxy {byte[] token = controllerCommand.getToken().getBytes("ASCII");byte[] readToken = new byte[token.length];clientSocket.getInputStream().read(readToken);- logger.info("Checking token");+ LOG.info("Checking token");// we have read it all, now comparefor (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");+ LOG.info("Token is good");return;} catch (IOException x) {clientSocket.close();@@ -164,7 +259,7 @@ public class ProxyClient extends Proxy {private User authenticateUser() throws IOException {// we need to read data from the client until we get the Authentication headertry {- logger.info("Reading HTTP headers");+ LOG.info("Reading HTTP headers");if (halted) {throw new IOException("Halted");}@@ -293,17 +388,11 @@ public class ProxyClient extends Proxy {return null;}// we have a value!- String value = matcher.group(1);- // now fold it- value = value.replaceAll("\r\n[ \t]+", " ").trim();+ String credentials = matcher.group(1).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);- }+ User user = persistenceService.doReturningTransaction(+ entityManager -> persistenceService.loadByHTTPBasicCredentials(entityManager, credentials)+ );if (user == null) {// authentication failedthrow new HTTPException(HttpURLConnection.HTTP_UNAUTHORIZED, json, optionsRequest);@@ -311,28 +400,13 @@ public class ProxyClient extends Proxy {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;+ return persistenceService.doReturningTransaction(+ entityManager -> persistenceService.saveProxyControllerCommand(+ entityManager,+ user,+ ((sslServerSocketFactory != null) ? "https://" : "http://") + hostName + ":" + port+ )+ );}-}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.java b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyServer.javasimilarity index 69%rename from beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.javarename to beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyServer.javaindex affdfa890..d92056fc7 100644--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/ProxyServer.java+++ b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyServer.java@@ -18,14 +18,9 @@* 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;+package org.openremote.ccs.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 org.openremote.ccs.CCSPersistenceService;import javax.net.ssl.KeyManagerFactory;import javax.net.ssl.SSLContext;@@ -39,13 +34,15 @@ import java.net.Socket;import java.security.KeyStore;import java.util.HashSet;import java.util.Set;+import java.util.logging.Level;+import java.util.logging.Logger;public class ProxyServer extends Thread {- protected final static org.slf4j.Logger logger = LoggerFactory.getLogger(ProxyServer.class);+ private static final Logger LOG = Logger.getLogger(ProxyServer.class.getName());private boolean halted = false;- private Set<ProxyClient> clients = new HashSet<ProxyClient>();+ final private Set<ProxyClient> clients = new HashSet<>();private String hostName;private int timeout;private int port;@@ -54,18 +51,13 @@ public class ProxyServer extends Thread {private boolean useSSL;private String keystore;private String keystorePassword;- private AccountService accountService;- private ControllerCommandService controllerCommandService;+ private CCSPersistenceService persistenceService;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;+ String keystorePassword, CCSPersistenceService persistenceService) {- if (StringUtils.isEmpty(proxyHostname)) {+ if (proxyHostname == null || proxyHostname.length() == 0) {hostName = "localhost";} else {hostName = proxyHostname;@@ -74,16 +66,16 @@ public class ProxyServer extends Thread {if (proxyTimeout == null) {timeout = 5000;} else {- timeout = proxyTimeout.intValue();+ timeout = proxyTimeout;}if (proxyPort == null) {port = 10000;} else {- port = proxyPort.intValue();+ port = proxyPort;}- if (StringUtils.isEmpty(proxyClientPortRange)) {+ if (proxyClientPortRange == null || proxyClientPortRange.length() == 0) {minClientPort = 0;maxClientPort = 0;} else {@@ -91,19 +83,15 @@ public class ProxyServer extends Thread {maxClientPort = Integer.parseInt(proxyClientPortRange.trim().substring(proxyClientPortRange.indexOf("-") + 1, proxyClientPortRange.length()));}- if (useSSL == null) {- this.useSSL = false;- } else {- this.useSSL = useSSL;- }+ this.useSSL = useSSL != null ? useSSL : false;- if (this.useSSL && StringUtils.isEmpty(keystore)) {+ if (this.useSSL && (keystore == null || keystore.length() == 0)) {throw new RuntimeException("A keystore has to be specified when using SSL");} else {this.keystore = keystore;}- if (this.useSSL && StringUtils.isEmpty(keystorePassword)) {+ if (this.useSSL && (keystorePassword == null || keystorePassword.length() == 0)) {throw new RuntimeException("A keystore password has to be specified when using SSL");} else {this.keystorePassword = keystorePassword;@@ -111,7 +99,7 @@ public class ProxyServer extends Thread {if (useSSL) {// Specifying the Keystore details- logger.info("Load keystore: " + this.keystore);+ LOG.info("Load keystore: " + this.keystore);InputStream keystoreStream = null;try {TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());@@ -123,19 +111,19 @@ public class ProxyServer extends Thread {try {keystoreStream = new FileInputStream(this.keystore);} catch (IOException e) {- logger.error("The specified keystore " + this.keystore + " can not be loaded");+ LOG.severe("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");+ LOG.severe("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"));+ LOG.info("Keystore loaded, it contains " + ks.size() + ((ks.size() > 1) ? " entries" : " entry"));trustManagerFactory.init(ks);keyManagerFactory.init(ks, this.keystorePassword.toCharArray());@@ -150,7 +138,7 @@ public class ProxyServer extends Thread {try {keystoreStream.close();} catch (IOException e) {- logger.warn("Failed to close stream to keystore", e);+ LOG.log(Level.WARNING, "Failed to close stream to keystore", e);}}}@@ -160,24 +148,24 @@ public class ProxyServer extends Thread {@Overridepublic void run() {- logger.info("Proxy server starting up");+ LOG.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);+ LOG.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);+ LOG.info("Starting proxy server on port: " + port);server = new ServerSocket(port);}- logger.info("Entering loop");+ LOG.info("Entering loop");while (true) {// Wait for a connection on the local portSocket clientSocket = server.accept();- logger.info("Accepting a client socket");+ LOG.info("Accepting a client socket");synchronized (clients) {if (halted) {break;@@ -185,9 +173,9 @@ public class ProxyServer extends Thread {acceptConnection(clientSocket);}}- logger.info("Exited loop");+ LOG.info("Exited loop");} catch (Exception e) {- logger.error("Server died", e);+ LOG.log(Level.SEVERE, "Server died", e);} finally {if (server != null)try {@@ -199,13 +187,17 @@ public class ProxyServer extends Thread {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);+ LOG.info("Got a client socket");+ ProxyClient client = new ProxyClient(+ this, clientSocket, timeout, hostName,+ minClientPort, maxClientPort,+ persistenceService,+ sslServerSocketfactory+ );clients.add(client);- logger.info("Starting client");+ LOG.info("Starting client");client.start();- logger.info("Client started");+ LOG.info("Client started");} catch (Exception x) {// make sure we close this one if neededtry {@@ -219,13 +211,13 @@ public class ProxyServer extends Thread {public void halt() {synchronized (clients) {halted = true;- for (Proxy client : clients) {+ for (ProxyClient client : clients) {client.halt();}}}- public void unregister(Proxy proxyClient) {+ public void unregister(ProxyClient proxyClient) {synchronized (clients) {clients.remove(proxyClient);}diff --git a/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyService.java b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyService.javanew file mode 100644index 000000000..50f84c69d--- /dev/null+++ b/beehive/ccs/src/main/java/org/openremote/ccs/proxy/ProxyService.java@@ -0,0 +1,40 @@+package org.openremote.ccs.proxy;++import org.openremote.container.Container;+import org.openremote.container.ContainerService;++public class ProxyService implements ContainerService {++ @Override+ public void init(Container container) throws Exception {++ }++ @Override+ public void configure(Container container) throws Exception {+/*++ 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.jks");+ String keystorePassword = config.getProperty("proxy.keystorePassword", "storepass");+*/+ }++ @Override+ public void start(Container container) throws Exception {+/*+ ProxyServer ps = new ProxyServer(proxyHostname, proxyTimeout, proxyPort, proxyClientPortRange, useSSL, keystore, keystorePassword, controllerCommandService, accountService, this);+ ps.start();+*/++ }++ @Override+ public void stop(Container container) throws Exception {++ }+}diff --git a/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.javadeleted file mode 100644index 1c926e38f..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/ControllerProxyAndCommandServiceApplication.java+++ /dev/null@@ -1,303 +0,0 @@-/*- * 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 LOG = 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")) {- LOG.info("### Creating database schema");- createSchema();- } else {- LOG.info("### Not creating database schema");- }-- LOG.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.jks");- 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();- LOG.info("EntityManagerFactory has been closed");- } catch (Exception e) {- LOG.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() {- LOG.trace(">>createEntityManager");- EntityManager entityManager = null;- try {- LOG.trace("Before createEntityManager");- entityManager = entityManagerFactory.createEntityManager();- LOG.debug("Got entityManager " + entityManager);- EntityTransaction tx = entityManager.getTransaction();- LOG.debug("Got transaction " + tx);- tx.begin();- LOG.debug("Begun transaction");- } catch (Exception e) {- LOG.error("Failed to create an EntityManager", e);- }- LOG.trace("<<createEntityManager");- return entityManager;- }-- public void commitEntityManager(EntityManager entityManager) {- LOG.trace(">>commitEntityManager");- if (entityManager.isOpen()) {- LOG.debug("entityManager opened, commit transaction");- entityManager.getTransaction().commit();- entityManager.close();- }- LOG.trace("<<commitEntityManager");- }-- public void rollbackEntityManager(EntityManager entityManager) {- LOG.trace(">>rollbackEntityManager");- if (entityManager.isOpen()) {- LOG.debug("entityManager opened, rollback transaction");- entityManager.getTransaction().rollback();- entityManager.close();- }- LOG.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) {-- LOG.error("Failed to create EntityManager", throwable);-- if (entityManager != null) {- EntityTransaction tx = entityManager.getTransaction();- if (tx != null && tx.isActive()) {- try {- tx.rollback();- } catch (Exception e) {- LOG.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();-- LOG.debug("Transaction is " + tx + " , active ? " + (tx.isActive() ? "yes" : "no"));-- if (tx != null && tx.isActive()) {- if (tx.getRollbackOnly() || response.getStatus() >= 400) {- LOG.debug("Rolling back transaction");- try {- tx.rollback();- } catch (Exception e) {- LOG.warn("Failed to rollback transaction ", e);- }- } else {- LOG.debug("Commit transaction");- try {- tx.commit();- } catch (Exception e) {- LOG.error("Failed to commit transaction ", e);- }- }- }- if (entityManager.isOpen()) {- try {- entityManager.close();- } catch (Exception e) {- LOG.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();- LOG.info("Table CONTROLLER not found, attempting to create database schema");- MultipleLinesSqlCommandExtractor extractor = new MultipleLinesSqlCommandExtractor();- String[] sqlCommands = extractor.extractCommands(- new BufferedReader(new InputStreamReader(- getClass().getClassLoader().getResourceAsStream("sql/10-CreateSchema.sql"))- )- );- for (String sqlCommand : sqlCommands) {- Statement stmt = null;- try {- stmt = connection.createStatement();- rs = stmt.executeQuery(sqlCommand);- } finally {- if (stmt != null) {- stmt.close();- }- }- }- } else {- LOG.info("Table CONTROLLER found in database schema, not creating schema");- }- } 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.javadeleted file mode 100644index 01bcca242..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/GenericDAO.java+++ /dev/null@@ -1,52 +0,0 @@-/* 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.javadeleted file mode 100644index 296a4f53b..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/db/CustomMySQL5Dialect.java+++ /dev/null@@ -1,47 +0,0 @@-/* 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/proxy/Proxy.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/Proxy.javadeleted file mode 100644index 90971c7f3..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/proxy/Proxy.java+++ /dev/null@@ -1,151 +0,0 @@-/*- * 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/resources/ControllerCommandResource.java b/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandResource.javadeleted file mode 100644index ba8969162..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandResource.java+++ /dev/null@@ -1,134 +0,0 @@-/*- * 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.javadeleted file mode 100644index 8e9a88bd4..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/resources/ControllerCommandsResource.java+++ /dev/null@@ -1,91 +0,0 @@-/*- * 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.javadeleted file mode 100644index a09a73539..000000000--- a/beehive/ccs/src/main/java/org/openremote/controllercommand/service/AccountService.java+++ /dev/null@@ -1,67 +0,0 @@-/* 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/resources/META-INF/persistence.xml b/beehive/ccs/src/main/resources/META-INF/persistence.xmlindex c990a20f6..90ba12aad 100644--- a/beehive/ccs/src/main/resources/META-INF/persistence.xml+++ b/beehive/ccs/src/main/resources/META-INF/persistence.xml@@ -1,68 +1,27 @@-<?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"+ version="2.1"+ xmlns="http://xmlns.jcp.org/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">+ xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence+ http://xmlns.jcp.org/xml/ns/persistence_2_1.xsd">- <persistence-unit name="CCS-MySQL">- <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>+ <persistence-unit name="OpenRemotePU" transaction-type="RESOURCE_LOCAL">- <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>+ <class>org.openremote.container.persistence</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"/>-- <!-- TODO Use environment variables -->- <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.current_session_context_class" value="managed"/>+ <class>org.openremote.ccs.model.Account</class>+ <class>org.openremote.ccs.model.User</class>+ <class>org.openremote.ccs.model.Controller</class>+ <class>org.openremote.ccs.model.ControllerCommand</class>+ <class>org.openremote.ccs.model.InitiateProxyControllerCommand</class>- <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"/>+ <exclude-unlisted-classes>true</exclude-unlisted-classes>+ <properties>+ <property name="hibernate.format_sql" value="true"/>+ <property name="hibernate.use_sql_comments" value="true"/>+ <property name="hibernate.archive.autodetection" value="none"/>+ <property name="hibernate.current_session_context_class" value="thread"/></properties>-</persistence-unit></persistence>\ No newline at end of filediff --git a/beehive/ccs/src/main/resources/logging.properties b/beehive/ccs/src/main/resources/logging.propertiesnew file mode 100644index 000000000..00aa58ff9--- /dev/null+++ b/beehive/ccs/src/main/resources/logging.properties@@ -0,0 +1,28 @@+# This configuration file is used in the Manager's Docker image, it's the default+# configuration we ship to users.++handlers=java.util.logging.ConsoleHandler++java.util.logging.ConsoleHandler.formatter=org.openremote.container.util.LogFormatter+java.util.logging.ConsoleHandler.level=FINEST++.level=INFO++org.openremote.level=FINEST+org.openremote.container.message.level=INFO++# Low-level debugging+org.hibernate.level=WARNING+com.zaxxer.hikari.level=WARNING+javax.management.level=WARNING+org.xnio.level=WARNING+org.apache.camel.management.level=WARNING+org.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING++# Set this to FINEST to log outgoing HTTP traffic+org.apache.http.level=WARNING+org.apache.http.impl.conn.DefaultClientConnection.level=WARNING++# Set this to FINEST to log SQL execution+org.hibernate.SQL.level=FINEST+org.hibernate.type.descriptor.sql.BasicBinder.level=FINESTdiff --git a/beehive/ccs/src/main/webapp/WEB-INF/web.xml b/beehive/ccs/src/main/webapp/WEB-INF/web.xmldeleted file mode 100644index 37ff4e8eb..000000000--- a/beehive/ccs/src/main/webapp/WEB-INF/web.xml+++ /dev/null@@ -1,119 +0,0 @@-<?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>service-admin</role-name>- <role-name>account-owner</role-name>- </auth-constraint>-- </security-constraint>--- <!-- At minimum, require HTTP Basic authorization... -->-- <login-config>- <auth-method>BASIC</auth-method>- <realm-name>Restricted Service</realm-name>- </login-config>-- <!-- Define the security roles... -->- <security-role>- <description>- The user who owns an account- </description>- <role-name>account-owner</role-name>- </security-role>- <security-role>- <description>- The service administrator- </description>- <role-name>service-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.javadeleted file mode 100644index ca070a983..000000000--- a/beehive/ccs/src/test/java/org/openremote/controllercommand/rest/ControllerCommandTests.java+++ /dev/null@@ -1,9 +0,0 @@-package org.openremote.controllercommand.rest;--import org.junit.Ignore;--@Ignore-public class ControllerCommandTests-{--}diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex 6067b35e0..8ef5388d8 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -135,6 +135,16 @@ public class Container {Runtime.getRuntime().addShutdownHook(new Thread(this::stop));}+ public void putConfig(String variable, String value) {+ config.put(variable, value);+ }++ public void putConfigIfEmpty(String variable, String value) {+ if (!config.hasNonNull(variable)) {+ putConfig(variable, value);+ }+ }+public String getConfig(String variable, String defaultValue) {return config.has(variable) ? config.get(variable).asText() : defaultValue;}diff --git a/container/src/main/java/org/openremote/container/persistence/Database.java b/container/src/main/java/org/openremote/container/persistence/Database.javaindex f53001f7e..bb86ee44f 100644--- a/container/src/main/java/org/openremote/container/persistence/Database.java+++ b/container/src/main/java/org/openremote/container/persistence/Database.java@@ -22,7 +22,6 @@ package org.openremote.container.persistence;import com.zaxxer.hikari.HikariConfig;import com.zaxxer.hikari.HikariDataSource;import org.hibernate.cfg.AvailableSettings;-import org.hibernate.dialect.PostgreSQL94Dialect;import org.hibernate.spatial.dialect.postgis.PostgisDialect;import java.util.HashMap;diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.javaindex c9bfe0f8f..a883209a8 100644--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java@@ -45,11 +45,11 @@ public class PersistenceService implements ContainerService {public static final String DATABASE_PRODUCT = "DATABASE_PRODUCT";public static final String DATABASE_PRODUCT_DEFAULT = Database.Product.POSTGRES.name();public static final String DATABASE_CONNECTION_URL = "DATABASE_CONNECTION_URL";- public static final String DATABASE_CONNECTION_URL_DEFAULT = "jdbc:postgresql://192.168.99.100:8082/openremote";+ public static final String DATABASE_CONNECTION_URL_DEFAULT = "jdbc:postgresql://192.168.99.100:5432/openremote";public static final String DATABASE_USERNAME = "DATABASE_USERNAME";public static final String DATABASE_USERNAME_DEFAULT = "openremote";public static final String DATABASE_PASSWORD = "DATABASE_PASSWORD";- public static final String DATABASE_PASSWORD_DEFAULT = "secret";+ public static final String DATABASE_PASSWORD_DEFAULT = "CHANGE_ME_DB_USER_PASSWORD";public static final String DATABASE_MIN_POOL_SIZE = "DATABASE_MIN_POOL_SIZE";public static final int DATABASE_MIN_POOL_SIZE_DEFAULT = 5;public static final String DATABASE_MAX_POOL_SIZE = "DATABASE_MAX_POOL_SIZE";diff --git a/container/src/main/java/org/openremote/container/persistence/package-info.java b/container/src/main/java/org/openremote/container/persistence/package-info.javaindex e4f2364fb..4134db069 100644--- a/container/src/main/java/org/openremote/container/persistence/package-info.java+++ b/container/src/main/java/org/openremote/container/persistence/package-info.java@@ -5,7 +5,7 @@parameters = {@org.hibernate.annotations.Parameter(name = "sequence_name",- value = "OR_MANAGER_SEQUENCE"+ value = "OPENREMOTE_SEQUENCE"),@org.hibernate.annotations.Parameter(name = "initial_value",diff --git a/container/src/main/java/org/openremote/container/security/IdentityService.java b/container/src/main/java/org/openremote/container/security/IdentityService.javaindex 4e780b234..bb6083c6e 100644--- a/container/src/main/java/org/openremote/container/security/IdentityService.java+++ b/container/src/main/java/org/openremote/container/security/IdentityService.java@@ -28,11 +28,15 @@ import io.undertow.server.handlers.proxy.SimpleProxyClientProvider;import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;import org.keycloak.adapters.KeycloakDeployment;+import org.keycloak.admin.client.resource.ClientResource;+import org.keycloak.admin.client.resource.ClientsResource;import org.keycloak.admin.client.resource.RealmsResource;import org.keycloak.admin.client.resource.ServerInfoResource;import org.keycloak.common.enums.SslRequired;import org.keycloak.common.util.PemUtils;import org.keycloak.representations.adapters.config.AdapterConfig;+import org.keycloak.representations.idm.ClientRepresentation;+import org.keycloak.representations.idm.RealmRepresentation;import org.openremote.container.Constants;import org.openremote.container.Container;import org.openremote.container.ContainerService;@@ -48,6 +52,8 @@ import javax.ws.rs.client.Client;import javax.ws.rs.core.Response;import javax.ws.rs.core.UriBuilder;import java.net.URI;+import java.util.ArrayList;+import java.util.List;import java.util.Locale;import java.util.concurrent.TimeUnit;import java.util.logging.Level;@@ -71,6 +77,9 @@ public class IdentityService implements ContainerService {public static final String IDENTITY_NETWORK_HOST_DEFAULT = "localhost";public static final String IDENTITY_NETWORK_WEBSERVER_PORT = "IDENTITY_NETWORK_WEBSERVER_PORT";public static final int IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT = 8080;+ public static final String IDENTITY_SESSION_TIMEOUT_SECONDS = "IDENTITY_SESSION_TIMEOUT_SECONDS";+ public static final int IDENTITY_SESSION_TIMEOUT_SECONDS_DEFAULT = 10800; // 3 hours+public static final String KEYCLOAK_HOST = "KEYCLOAK_HOST";public static final String KEYCLOAK_HOST_DEFAULT = "192.168.99.100";public static final String KEYCLOAK_PORT = "KEYCLOAK_PORT";@@ -91,12 +100,14 @@ public class IdentityService implements ContainerService {protected LoadingCache<ClientRealm.Key, ClientRealm> clientApplicationCache;protected boolean keycloakReverseProxy;protected String clientId;+ protected int sessionTimeoutSeconds;@Overridepublic void init(Container container) throws Exception {boolean identityNetworkSecure = container.getConfigBoolean(IDENTITY_NETWORK_SECURE, IDENTITY_NETWORK_SECURE_DEFAULT);String identityNetworkHost = container.getConfig(IDENTITY_NETWORK_HOST, IDENTITY_NETWORK_HOST_DEFAULT);int identityNetworkPort = container.getConfigInteger(IDENTITY_NETWORK_WEBSERVER_PORT, IDENTITY_NETWORK_WEBSERVER_PORT_DEFAULT);+ sessionTimeoutSeconds = container.getConfigInteger(IDENTITY_SESSION_TIMEOUT_SECONDS, IDENTITY_SESSION_TIMEOUT_SECONDS_DEFAULT);UriBuilder externalAuthServerUrl = UriBuilder.fromUri("").scheme(identityNetworkSecure ? "https" : "http")@@ -267,8 +278,9 @@ public class IdentityService implements ContainerService {LOG.fine("Client '" + clientId + "' for realm '" + realm + "' not found on identity provider");} else {LOG.log(- Level.INFO,- "Error loading client '" + clientId + "' for realm '" + realm + "' from identity provider",+ Level.WARNING,+ "Error loading client '" + clientId + "' for realm '" + realm + "' from identity provider, " ++ "exception from call to identity provider follows",ex);}@@ -341,4 +353,43 @@ public class IdentityService implements ContainerService {public void setClientId(String clientId) {this.clientId = clientId;}++ public void configureRealm(RealmRepresentation realmRepresentation, int accessTokenLifespanSeconds) {+ realmRepresentation.setDisplayNameHtml(+ "<div class=\"kc-logo-text\"><span>OpenRemote: "+ + (realmRepresentation.getDisplayName().replaceAll("[^A-Za-z0-9]", ""))+ + " </span></div>"+ );+ realmRepresentation.setAccessTokenLifespan(accessTokenLifespanSeconds);+ realmRepresentation.setLoginTheme("openremote");+ realmRepresentation.setAccountTheme("openremote");+ realmRepresentation.setSsoSessionIdleTimeout(sessionTimeoutSeconds);++ // TODO: Make SSL setup configurable+ realmRepresentation.setSslRequired(SslRequired.NONE.toString());+ }++ public ClientRepresentation createClientApplication(String realm, String clientId, String appName, boolean isDevMode) {+ ClientRepresentation client = new ClientRepresentation();++ client.setClientId(clientId);+ client.setName(appName);+ client.setPublicClient(true);++ if (isDevMode) {+ // We need direct access for integration tests+ LOG.warning("### Allowing direct access grants for client app '" + appName + "', this must NOT be used in production! ###");+ client.setDirectAccessGrantsEnabled(true);+ }++ String callbackUrl = UriBuilder.fromUri("/").path(realm).path("*").build().toString();+ List<String> redirectUrls = new ArrayList<>();+ redirectUrls.add(callbackUrl);+ client.setRedirectUris(redirectUrls);++ String baseUrl = UriBuilder.fromUri("/").path(realm).build().toString();+ client.setBaseUrl(baseUrl);++ return client;+ }}\ No newline at end of filediff --git a/gradle.properties b/gradle.propertiesindex 2b48df711..cff48d50b 100644--- a/gradle.properties+++ b/gradle.properties@@ -24,6 +24,7 @@ sqliteVersion = 3.8.11.2hibernateVersion = 5.2.2.FinalhibernateValidatorVersion = 5.2.3.FinalpostgresJdbcVersion = 9.4.1209+mariadbJdbcVersion = 1.5.5hikaricpVersion = 2.4.3junitVersion = 4.12spockVersion = 1.0-groovy-2.4@@ -33,12 +34,5 @@ tyrusVersion = 1.10geojsonJacksonVersion = 1.6# Explicit dependency can be removed with Camel 2.18.x, then AHC 2.x is the defaultahcVersion = 1.9.39-servletVersion = 3.1.0flexjsonVersion = 2.1springVersion = 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/manager/build.gradle b/manager/build.gradleindex aef7ce762..c757c15ed 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -6,9 +6,9 @@ task createDockerfile(type: Dockerfile) {destFile = project.file("$project.buildDir/install/Dockerfile")from "java:8"environmentVariable "WEBSERVER_DOCROOT", "webapp"- environmentVariable "LOGGING_CONFIG_FILE", "config/logging.properties"- environmentVariable "MAP_TILES_PATH", "config/mapdata.mbtiles"- environmentVariable "MAP_SETTINGS_PATH", "config/mapsettings.json"+ environmentVariable "LOGGING_CONFIG_FILE", "conf/logging.properties"+ environmentVariable "MAP_TILES_PATH", "conf/mapdata.mbtiles"+ environmentVariable "MAP_SETTINGS_PATH", "conf/mapsettings.json"addFile project(':manager:server').distributions.main.baseName, "/opt/app"addFile project(':manager:client').distributions.main.baseName, "/opt/app"exposePort 8080diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java b/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.javaindex 3d0974377..ab1579624 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/AppControllerImpl.java@@ -91,7 +91,7 @@ public class AppControllerImpl implements AppController, AppView.Presenter {@Overridepublic void start() {- Window.setTitle(Constants.MANAGE_NAME);+ Window.setTitle(Constants.APP_NAME);RootPanel.get().add(appView);appView.setPresenter(this);placeHistoryHandler.handleCurrentHistory();diff --git a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.javaindex 816249c78..ad3ee6d8a 100644--- a/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java+++ b/manager/client/src/main/java/org/openremote/manager/client/app/HeaderPresenter.java@@ -132,6 +132,6 @@ public class HeaderPresenter implements HeaderView.Presenter {@Overridepublic boolean isUserInRole(String role) {- return securityService.hasResourceRoleOrIsAdmin(role, Constants.MANAGER_CLIENT_ID);+ return securityService.hasResourceRoleOrIsAdmin(role, Constants.APP_CLIENT_ID);}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.javaindex 7e3f9df97..729c53513 100644--- a/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/mvp/AppActivity.java@@ -45,7 +45,7 @@ public abstract class AppActivity<T extends Place> {public AppActivity<T> init(SecurityService securityService, T place) throws RoleRequiredException {for (String requiredRole : getRequiredRoles()) {- if (!securityService.hasResourceRoleOrIsAdmin(requiredRole, Constants.MANAGER_CLIENT_ID)) {+ if (!securityService.hasResourceRoleOrIsAdmin(requiredRole, Constants.APP_CLIENT_ID)) {throw new RoleRequiredException(requiredRole);}}diff --git a/manager/server/build.gradle b/manager/server/build.gradleindex 81b5e722d..3ed9aaaba 100644--- a/manager/server/build.gradle+++ b/manager/server/build.gradle@@ -20,8 +20,8 @@ dependencies {distributions {main {contents {- from("config") {- into "config"+ from("conf") {+ into "conf"}}}diff --git a/manager/server/config/logging.properties b/manager/server/conf/logging.propertiessimilarity index 100%rename from manager/server/config/logging.propertiesrename to manager/server/conf/logging.propertiesdiff --git a/manager/server/config/mapdata.mbtiles b/manager/server/conf/mapdata.mbtilessimilarity index 100%rename from manager/server/config/mapdata.mbtilesrename to manager/server/conf/mapdata.mbtilesdiff --git a/manager/server/config/mapsettings.json b/manager/server/conf/mapsettings.jsonsimilarity index 100%rename from manager/server/config/mapsettings.jsonrename to manager/server/conf/mapsettings.jsondiff --git a/manager/server/src/main/java/org/openremote/manager/server/DemoDataService.java b/manager/server/src/main/java/org/openremote/manager/server/DemoDataService.javaindex 00f377978..29d179c00 100644--- a/manager/server/src/main/java/org/openremote/manager/server/DemoDataService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/DemoDataService.java@@ -147,7 +147,7 @@ public class DemoDataService implements ContainerService {// Find out if there is a client already present for this application, if so, delete itfromCallable(clientsResource::findAll).flatMap(Observable::from)- .filter(clientRepresentation -> clientRepresentation.getClientId().equals(MANAGER_CLIENT_ID))+ .filter(clientRepresentation -> clientRepresentation.getClientId().equals(APP_CLIENT_ID)).map(ClientRepresentation::getId).subscribe(clientObjectId -> {clientsResource.get(clientObjectId).remove();@@ -155,7 +155,7 @@ public class DemoDataService implements ContainerService {identityService.createClientApplication(accessToken, masterRealm.getRealm());- String clientObjectId = fromCallable(() -> clientsResource.findByClientId(MANAGER_CLIENT_ID))+ String clientObjectId = fromCallable(() -> clientsResource.findByClientId(APP_CLIENT_ID)).flatMap(Observable::from).map(ClientRepresentation::getId).toBlocking().singleOrDefault(null);diff --git a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.javaindex 4aa46b732..9b9370d67 100644--- a/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/map/MapService.java@@ -41,9 +41,9 @@ public class MapService implements ContainerService {private static final Logger LOG = Logger.getLogger(MapService.class.getName());public static final String MAP_TILES_PATH = "MAP_TILES_PATH";- public static final String MAP_TILES_PATH_DEFAULT = "manager/server/config/mapdata.mbtiles";+ public static final String MAP_TILES_PATH_DEFAULT = "manager/server/conf/mapdata.mbtiles";public static final String MAP_SETTINGS_PATH = "MAP_SETTINGS_PATH";- public static final String MAP_SETTINGS_PATH_DEFAULT = "manager/server/config/mapsettings.json";+ public static final String MAP_SETTINGS_PATH_DEFAULT = "manager/server/conf/mapsettings.json";// Shared SQL connection is fine concurrently in SQLiteprotected Connection connection;diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.javaindex 72739ce67..614f40991 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java@@ -23,7 +23,6 @@ import org.keycloak.admin.client.resource.ClientResource;import org.keycloak.admin.client.resource.ClientsResource;import org.keycloak.admin.client.resource.RealmsResource;import org.keycloak.admin.client.resource.RolesResource;-import org.keycloak.common.enums.SslRequired;import org.keycloak.representations.idm.ClientRepresentation;import org.keycloak.representations.idm.RealmRepresentation;import org.keycloak.representations.idm.RoleRepresentation;@@ -34,7 +33,6 @@ import org.openremote.container.web.WebService;import org.openremote.manager.shared.Constants;import org.openremote.manager.shared.security.Tenant;-import javax.ws.rs.core.UriBuilder;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;@@ -42,23 +40,18 @@ import java.util.List;import java.util.logging.Logger;import static org.openremote.container.json.JsonUtil.convert;-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID;-import static org.openremote.manager.shared.Constants.MANAGE_NAME;-import static org.openremote.manager.shared.Constants.MASTER_REALM;+import static org.openremote.manager.shared.Constants.*;public class ManagerIdentityService extends IdentityService {private static final Logger LOG = Logger.getLogger(ManagerIdentityService.class.getName());- public static final String IDENTITY_TIMEOUT_SESSION_SECONDS = "IDENTITY_TIMEOUT_SESSION_SECONDS";- public static final int IDENTITY_TIMEOUT_SESSION_SECONDS_DEFAULT = 10800; // 3 hours-protected Container container;@Overridepublic void init(Container container) throws Exception {this.container = container;- setClientId(Constants.MANAGER_CLIENT_ID);+ setClientId(Constants.APP_CLIENT_ID);super.init(container);setKeycloakReverseProxy(true);}@@ -89,32 +82,6 @@ public class ManagerIdentityService extends IdentityService {return getRealms(bearerAuth, true);}- public ClientRepresentation createManagerClient(String realm) {- ClientRepresentation managerClient = new ClientRepresentation();-- managerClient.setClientId(MANAGER_CLIENT_ID);-- managerClient.setName(MANAGE_NAME);-- managerClient.setPublicClient(true);-- if (container.isDevMode()) {- // We need direct access for integration tests- LOG.warning("Allowing direct access grants for manager client, this must NOT be used in production");- managerClient.setDirectAccessGrantsEnabled(true);- }-- String callbackUrl = UriBuilder.fromUri("/").path(realm).path("*").build().toString();- List<String> redirectUrls = new ArrayList<>();- redirectUrls.add(callbackUrl);- managerClient.setRedirectUris(redirectUrls);-- String baseUrl = UriBuilder.fromUri("/").path(realm).build().toString();- managerClient.setBaseUrl(baseUrl);-- return managerClient;- }-public Tenant[] getTenants(String bearerAuth) {List<RealmRepresentation> realms = getRealms(bearerAuth).findAll();@@ -142,6 +109,10 @@ public class ManagerIdentityService extends IdentityService {);}+ public void configureRealm(RealmRepresentation realmRepresentation) {+ configureRealm(realmRepresentation, ACCESS_TOKEN_LIFESPAN_SECONDS);+ }+public void createTenant(String bearerAuth, Tenant tenant) throws Exception {LOG.fine("Create tenant: " + tenant);RealmRepresentation realmRepresentation = convert(container.JSON, RealmRepresentation.class, tenant);@@ -151,29 +122,14 @@ public class ManagerIdentityService extends IdentityService {createClientApplication(bearerAuth, realmRepresentation.getRealm());}- public void configureRealm(RealmRepresentation realmRepresentation) {- realmRepresentation.setDisplayNameHtml(- "<div class=\"kc-logo-text\"><span>OpenRemote: "- + (realmRepresentation.getDisplayName().replaceAll("[^A-Za-z0-9]", ""))- + " </span></div>"- );- realmRepresentation.setAccessTokenLifespan(Constants.ACCESS_TOKEN_LIFESPAN_SECONDS);- realmRepresentation.setLoginTheme("openremote");- realmRepresentation.setAccountTheme("openremote");- realmRepresentation.setSsoSessionIdleTimeout(- container.getConfigInteger(IDENTITY_TIMEOUT_SESSION_SECONDS, IDENTITY_TIMEOUT_SESSION_SECONDS_DEFAULT)- );-- // TODO: Make SSL setup configurable- realmRepresentation.setSslRequired(SslRequired.NONE.toString());- }-public void createClientApplication(String bearerAuth, String realm) {ClientsResource clientsResource = getRealms(bearerAuth).realm(realm).clients();- ClientRepresentation managerClient = createManagerClient(realm);- clientsResource.create(managerClient);- managerClient = clientsResource.findByClientId(managerClient.getClientId()).get(0);- ClientResource clientResource = clientsResource.get(managerClient.getId());+ ClientRepresentation client = createClientApplication(+ realm, APP_CLIENT_ID, APP_NAME, container.isDevMode()+ );+ clientsResource.create(client);+ client = clientsResource.findByClientId(client.getClientId()).get(0);+ ClientResource clientResource = clientsResource.get(client.getId());addDefaultRoles(clientResource.roles());}diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.javaindex 52b6629bc..949e82107 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java@@ -183,7 +183,7 @@ public class UserResourceImpl extends WebResource implements UserResource {managerIdentityService.getRealms(requestParams.getBearerAuth()).realm(realm).users().get(userId).roles();ClientsResource clientsResource =managerIdentityService.getRealms(requestParams.getBearerAuth()).realm(realm).clients();- String clientId = clientsResource.findByClientId(MANAGER_CLIENT_ID).get(0).getId();+ String clientId = clientsResource.findByClientId(APP_CLIENT_ID).get(0).getId();RolesResource rolesResource = clientsResource.get(clientId).roles();List<RoleRepresentation> allRoles = rolesResource.list();@@ -222,7 +222,7 @@ public class UserResourceImpl extends WebResource implements UserResource {managerIdentityService.getRealms(requestParams.getBearerAuth()).realm(realm).users().get(userId).roles();ClientsResource clientsResource =managerIdentityService.getRealms(requestParams.getBearerAuth()).realm(realm).clients();- String clientId = clientsResource.findByClientId(MANAGER_CLIENT_ID).get(0).getId();+ String clientId = clientsResource.findByClientId(APP_CLIENT_ID).get(0).getId();List<RoleRepresentation> rolesToAdd = new ArrayList<>();List<RoleRepresentation> rolesToRemove = new ArrayList<>();diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/Constants.java b/manager/shared/src/main/java/org/openremote/manager/shared/Constants.javaindex 457de0316..834c554d6 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/Constants.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/Constants.java@@ -21,8 +21,8 @@ package org.openremote.manager.shared;public interface Constants {- String MANAGE_NAME = "OpenRemote Manager";- String MANAGER_CLIENT_ID = "or-manager";+ String APP_NAME = "OpenRemote Manager";+ String APP_CLIENT_ID = "or-manager";String MASTER_REALM = "master";String MASTER_REALM_ADMIN_USER = "admin";String PERSISTENCE_SEQUENCE_ID_GENERATOR = "SEQUENCE_ID_GENERATOR";diff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovyindex 492cdf3f8..e683c260a 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy@@ -36,7 +36,7 @@ import org.openremote.test.ContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALMclass AdminTenantsActivityTest extends Specification implements ContainerTrait, GwtClientTrait {@@ -49,7 +49,7 @@ class AdminTenantsActivityTest extends Specification implements ContainerTrait,and: "An authenticated user and client security service"def realm = MASTER_REALM;- def accessToken = authenticate(container, realm, MANAGER_CLIENT_ID, "admin", "admin").token+ def accessToken = authenticate(container, realm, APP_CLIENT_ID, "admin", "admin").tokendef securityService = Stub(SecurityService) {getRealm() >> realmgetToken() >> accessTokendiff --git a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovyindex ff6ba16ea..fa4bc96f1 100644--- a/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy@@ -32,7 +32,7 @@ import org.openremote.test.ContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALMclass AdminUsersActivityTest extends Specification implements ContainerTrait, GwtClientTrait {@@ -45,7 +45,7 @@ class AdminUsersActivityTest extends Specification implements ContainerTrait, Gwand: "An authenticated user and client security service"def realm = MASTER_REALM;- def accessToken = authenticate(container, realm, MANAGER_CLIENT_ID, "admin", "admin").token+ def accessToken = authenticate(container, realm, APP_CLIENT_ID, "admin", "admin").tokendef securityService = Stub(SecurityService) {getRealm() >> realmgetToken() >> accessTokendiff --git a/manager/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy b/manager/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovyindex 8c73f8f08..9c1380a54 100644--- a/manager/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/controller2/Controller2Test.groovy@@ -23,7 +23,7 @@ import org.openremote.test.EventBusWebsocketEndpointimport spock.lang.Specificationimport spock.util.concurrent.BlockingVariables-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALMclass Controller2Test extends Specification implements ContainerTrait {@@ -35,7 +35,7 @@ class Controller2Test extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessToken = authenticate(container, realm, MANAGER_CLIENT_ID, "admin", "admin").token+ def accessToken = authenticate(container, realm, APP_CLIENT_ID, "admin", "admin").tokenand: "a client target"def clientTarget = getClientTarget(createClient(container).build(), serverUri(serverPort), realm)@@ -108,7 +108,7 @@ class Controller2Test extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessToken = authenticate(container, realm, MANAGER_CLIENT_ID, "admin", "admin").token+ def accessToken = authenticate(container, realm, APP_CLIENT_ID, "admin", "admin").tokenand: "a client target"def clientTarget = getClientTarget(createClient(container).build(), serverUri(serverPort), realm)diff --git a/manager/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovyindex f29bbaf4a..bbb674e9f 100644--- a/manager/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovy@@ -15,12 +15,11 @@ import org.openremote.manager.shared.Consumerimport org.openremote.manager.shared.Runnableimport org.openremote.manager.shared.http.EntityReaderimport org.openremote.manager.shared.map.MapResource-import org.openremote.manager.shared.validation.ConstraintViolationReportimport org.openremote.test.ContainerTraitimport spock.lang.Ignoreimport spock.lang.Specification-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALM// TODO Fix this when we do Asset testing@@ -42,7 +41,7 @@ class MapActivityTest extends Specification implements ContainerTrait {and: "An authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")def securityService = Stub(SecurityService) {getRealm() >> realm;getToken() >> accessTokenResponse.getToken();diff --git a/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovyindex bc438f448..e58f68afb 100644--- a/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy@@ -5,7 +5,7 @@ import org.openremote.manager.shared.map.MapResourceimport org.openremote.test.ContainerTraitimport spock.lang.Specification-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALMclass MapResourceTest extends Specification implements ContainerTrait {@@ -17,7 +17,7 @@ class MapResourceTest extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")and: "a test client target"def client = createClient(container).build();diff --git a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovyindex 9fc28666f..d94ea91cf 100644--- a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityResourceTest.groovy@@ -18,7 +18,7 @@ import spock.lang.Specificationimport javax.ws.rs.NotFoundException-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALM@Ignore@@ -31,7 +31,7 @@ class EntityResourceTest extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")and: "a test client target"def client = createClient(container)@@ -132,7 +132,7 @@ class EntityResourceTest extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")and: "a test client target"def client = createClient(container)diff --git a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovyindex d94c22292..f3f8a473d 100644--- a/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/ngsi/EntityServiceTest.groovy@@ -41,7 +41,7 @@ import spock.util.concurrent.PollingConditionsimport javax.ws.rs.NotFoundException-import static org.openremote.manager.shared.Constants.MANAGER_CLIENT_ID+import static org.openremote.manager.shared.Constants.APP_CLIENT_IDimport static org.openremote.manager.shared.Constants.MASTER_REALM@Ignore@@ -226,7 +226,7 @@ class EntityServiceTest extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")and: "a test client target"def client = createClient(container)@@ -339,7 +339,7 @@ class EntityServiceTest extends Specification implements ContainerTrait {and: "an authenticated user"def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")+ def accessTokenResponse = authenticate(container, realm, APP_CLIENT_ID, "test", "test")and: "a test client target"def client = createClient(container)diff --git a/profile/README.md b/profile/README.mdindex 864ed56a5..63c13b1b1 100644--- a/profile/README.md+++ b/profile/README.md@@ -52,7 +52,5 @@ TODO: Old Tomcat can't have separate key and store passwords...## Deploying profiles```-./gradlew -p beehive/ccs clean war-docker-compose -p <my_project_name> -f profile/mysql.yml -f profile/ccs.yml up```diff --git a/profile/dependencies/keycloak.yml b/profile/dependencies/keycloak.ymlnew file mode 100644index 000000000..6f8c286af--- /dev/null+++ b/profile/dependencies/keycloak.yml@@ -0,0 +1,21 @@+#+# Keycloak identity provider+#+version: '2'+services:++ keycloak:+ build:+ context: ../../base/keycloak+ environment:+ TZ: "Europe/Zurich"+ KEYCLOAK_USER: admin+ KEYCLOAK_PASSWORD: admin+ KEYCLOAK_LOGLEVEL: INFO+ POSTGRES_DATABASE: openremote+ POSTGRES_USER: openremote+ POSTGRES_PASSWORD: CHANGE_ME_DB_USER_PASSWORD+ links:+ - postgresql+ ports:+ - "8081:8080"\ No newline at end of filediff --git a/profile/dependencies/postgresql.yml b/profile/dependencies/postgresql.ymlnew file mode 100644index 000000000..0d5a2511e--- /dev/null+++ b/profile/dependencies/postgresql.yml@@ -0,0 +1,19 @@+#+# PostgreSQL database service(s)+#+version: '2'+services:++ postgresql:+ build:+ context: ../../base/postgres+ environment:+ TZ: "Europe/Zurich"+ # This is the database superuser+ POSTGRES_PASSWORD: CHANGE_ME_DB_SUPERUSER_PASSWORD+ # Create default database when started (see scripts)+ POSTGRES_DB: openremote+ OPENREMOTE_USERNAME: openremote+ OPENREMOTE_PASSWORD: CHANGE_ME_DB_USER_PASSWORD+ ports:+ - "5432:5432"diff --git a/settings.gradle b/settings.gradleindex ad6ac7373..6a12b87b0 100644--- a/settings.gradle+++ b/settings.gradle@@ -2,7 +2,6 @@ rootProject.name = "openremote"include "base:postgres","base:mysql",- "base:tomcat","base:keycloak","container","controller",