From b7a03f7dc3b6eb47957d0840d76178f2f42933eb Mon Sep 17 00:00:00 2001 From: Stefan Feilmeier Date: Sat, 8 Jan 2022 00:24:21 +0100 Subject: [PATCH] Backend-Code clean-up and modernization for Java 11 (#1692) - Clean-up code using Eclipse IDE - Apply checkstyle - Use Java 11 features - mainly the `var` keyword, where appropriate --- cnf/checkstyle.xml | 2 +- .../backend/application/BackendApp.java | 25 ++- .../io/openems/backend/b2brest/B2bRest.java | 6 +- .../openems/backend/b2brest/RestHandler.java | 24 +-- .../backend/b2bwebsocket/B2bWebsocket.java | 8 +- .../openems/backend/b2bwebsocket/OnClose.java | 5 +- .../openems/backend/b2bwebsocket/OnOpen.java | 10 +- .../backend/b2bwebsocket/OnRequest.java | 6 +- .../SubscribedEdgesChannelsWorker.java | 19 +- .../backend/b2bwebsocket/WebsocketServer.java | 2 +- .../openems/backend/b2bwebsocket/WsData.java | 15 +- .../EdgesCurrentDataNotification.java | 15 +- .../SubscribeEdgesChannelsRequest.java | 57 +++-- .../b2bwebsocket/B2bWebsocketTest.java | 43 ++-- .../backend/b2bwebsocket/TestClient.java | 22 +- .../AbstractOpenemsBackendComponent.java | 12 +- .../common/edgewebsocket/EdgeWebsocket.java | 6 +- .../common/jsonrpc/JsonRpcRequestHandler.java | 2 +- .../jsonrpc/request/AddEdgeToUserRequest.java | 12 +- .../GetEdgesChannelsValuesRequest.java | 30 +-- .../request/GetEdgesStatusRequest.java | 8 +- .../request/GetSetupProtocolRequest.java | 8 +- .../request/GetUserInformationRequest.java | 6 +- .../jsonrpc/request/RegisterUserRequest.java | 8 +- .../request/SetUserInformationRequest.java | 10 +- .../request/SubmitSetupProtocolRequest.java | 12 +- .../response/AddEdgeToUserResponse.java | 4 +- .../GetEdgesChannelsValuesResponse.java | 8 +- .../response/GetEdgesStatusResponse.java | 4 +- .../response/GetUserInformationResponse.java | 8 +- .../common/metadata/AbstractMetadata.java | 2 +- .../openems/backend/common/metadata/Edge.java | 82 +++++-- .../backend/common/metadata/Metadata.java | 74 ++++--- .../openems/backend/common/metadata/User.java | 37 ++-- .../backend/common/timedata/EdgeCache.java | 22 +- .../backend/common/timedata/Timedata.java | 8 +- .../common/uiwebsocket/UiWebsocket.java | 6 +- .../EdgeRpcRequestHandler.java | 32 ++- .../JsonRpcRequestHandlerImpl.java | 40 ++-- .../edgewebsocket/EdgeWebsocketImpl.java | 74 ++++--- .../backend/edgewebsocket/OnClose.java | 9 +- .../backend/edgewebsocket/OnError.java | 10 +- .../backend/edgewebsocket/OnNotification.java | 29 ++- .../openems/backend/edgewebsocket/OnOpen.java | 13 +- .../backend/edgewebsocket/OnRequest.java | 2 +- .../edgewebsocket/SystemLogHandler.java | 27 ++- .../edgewebsocket/WebsocketServer.java | 30 +-- .../openems/backend/edgewebsocket/WsData.java | 40 ++-- .../backend/metadata/dummy/DummyMetadata.java | 34 ++- .../backend/metadata/file/FileMetadata.java | 20 +- .../backend/metadata/odoo/EdgeCache.java | 53 +++-- .../openems/backend/metadata/odoo/Field.java | 39 ++-- .../openems/backend/metadata/odoo/MyUser.java | 2 +- .../backend/metadata/odoo/OdooMetadata.java | 46 ++-- .../metadata/odoo/odoo/Credentials.java | 2 +- .../metadata/odoo/odoo/FieldValue.java | 2 +- .../metadata/odoo/odoo/OdooHandler.java | 185 ++++++++-------- .../metadata/odoo/odoo/OdooUserRole.java | 8 +- .../backend/metadata/odoo/odoo/OdooUtils.java | 203 +++++++++--------- .../metadata/odoo/postgres/Credentials.java | 2 +- .../odoo/postgres/InitializeEdgesWorker.java | 6 +- .../odoo/postgres/PeriodicWriteWorker.java | 29 ++- .../metadata/odoo/postgres/PgUtils.java | 17 +- .../odoo/postgres/PostgresHandler.java | 8 +- .../odoo/postgres/QueueWriteWorker.java | 30 +-- .../odoo/postgres/task/DatabaseTask.java | 4 +- .../postgres/task/InsertEdgeConfigUpdate.java | 4 +- .../task/InsertOrUpdateDeviceStates.java | 6 +- .../odoo/postgres/task/UpdateEdgeConfig.java | 4 +- .../postgres/task/UpdateEdgeProducttype.java | 4 +- .../postgres/task/UpdateEdgeStateActive.java | 4 +- .../odoo/postgres/task/UpdateSumState.java | 4 +- .../backend/timedata/dummy/TimedataDummy.java | 8 +- .../timedata/influx/ChannelFormula.java | 8 +- .../influx/FieldTypeConflictHandler.java | 54 +++-- .../backend/timedata/influx/Influx.java | 112 +++++----- .../backend/uiwebsocket/impl/OnClose.java | 7 +- .../backend/uiwebsocket/impl/OnRequest.java | 64 +++--- .../impl/SubscribedChannelsWorker.java | 6 +- .../uiwebsocket/impl/UiWebsocketImpl.java | 44 ++-- .../uiwebsocket/impl/WebsocketServer.java | 4 +- .../backend/uiwebsocket/impl/WsData.java | 25 ++- 82 files changed, 1027 insertions(+), 955 deletions(-) diff --git a/cnf/checkstyle.xml b/cnf/checkstyle.xml index cc887fb5119..ba4b0fbf0ee 100644 --- a/cnf/checkstyle.xml +++ b/cnf/checkstyle.xml @@ -108,7 +108,7 @@ - + diff --git a/io.openems.backend.application/src/io/openems/backend/application/BackendApp.java b/io.openems.backend.application/src/io/openems/backend/application/BackendApp.java index 66b58e5c16d..03b6c1165c8 100644 --- a/io.openems.backend.application/src/io/openems/backend/application/BackendApp.java +++ b/io.openems.backend.application/src/io/openems/backend/application/BackendApp.java @@ -1,7 +1,6 @@ package io.openems.backend.application; import java.io.IOException; -import java.util.Dictionary; import java.util.Hashtable; import org.osgi.service.cm.Configuration; @@ -23,22 +22,22 @@ public class BackendApp { private final Logger log = LoggerFactory.getLogger(BackendApp.class); @Reference - ConfigurationAdmin cm; + private ConfigurationAdmin cm; @Activate - void activate() { - String message = "OpenEMS Backend version [" + OpenemsConstants.VERSION + "] started"; - String line = Strings.repeat("=", message.length()); - log.info(line); - log.info(message); - log.info(line); + private void activate() { + final var message = "OpenEMS Backend version [" + OpenemsConstants.VERSION + "] started"; + final var line = Strings.repeat("=", message.length()); + this.log.info(line); + this.log.info(message); + this.log.info(line); Configuration config; try { - config = cm.getConfiguration("org.ops4j.pax.logging", null); - Dictionary properties = config.getProperties(); + config = this.cm.getConfiguration("org.ops4j.pax.logging", null); + final var properties = config.getProperties(); if (properties == null || properties.isEmpty() || properties.get("log4j2.rootLogger.level") == null) { - Hashtable log4j = new Hashtable<>(); + final var log4j = new Hashtable(); log4j.put("log4j2.appender.console.type", "Console"); log4j.put("log4j2.appender.console.name", "console"); log4j.put("log4j2.appender.console.layout.type", "PatternLayout"); @@ -58,8 +57,8 @@ void activate() { } @Deactivate - void deactivate() { - log.info("Deactivate BackendApp"); + private void deactivate() { + this.log.info("Deactivate BackendApp"); } } diff --git a/io.openems.backend.b2brest/src/io/openems/backend/b2brest/B2bRest.java b/io.openems.backend.b2brest/src/io/openems/backend/b2brest/B2bRest.java index fd165f6c747..a7d7f97ec5c 100644 --- a/io.openems.backend.b2brest/src/io/openems/backend/b2brest/B2bRest.java +++ b/io.openems.backend.b2brest/src/io/openems/backend/b2brest/B2bRest.java @@ -42,18 +42,18 @@ public B2bRest() { } @Activate - void activate(Config config) throws OpenemsException { + private void activate(Config config) throws OpenemsException { this.startServer(config.port()); } @Deactivate - void deactivate() { + private void deactivate() { this.stopServer(); } /** * Create and start new server. - * + * * @param port the port * @throws OpenemsException on error */ diff --git a/io.openems.backend.b2brest/src/io/openems/backend/b2brest/RestHandler.java b/io.openems.backend.b2brest/src/io/openems/backend/b2brest/RestHandler.java index f038015f9c7..ef6cc491eeb 100644 --- a/io.openems.backend.b2brest/src/io/openems/backend/b2brest/RestHandler.java +++ b/io.openems.backend.b2brest/src/io/openems/backend/b2brest/RestHandler.java @@ -72,7 +72,7 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques /** * Authenticate a user. - * + * * @param request the HttpServletRequest * @return the {@link User} * @throws OpenemsNamedException on error @@ -80,7 +80,7 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques private User authenticate(HttpServletRequest request) throws OpenemsNamedException { String authHeader = request.getHeader("Authorization"); if (authHeader != null) { - StringTokenizer st = new StringTokenizer(authHeader); + var st = new StringTokenizer(authHeader); if (st.hasMoreTokens()) { String basic = st.nextToken(); if (basic.equalsIgnoreCase("Basic")) { @@ -92,8 +92,8 @@ private User authenticate(HttpServletRequest request) throws OpenemsNamedExcepti } int p = credentials.indexOf(":"); if (p != -1) { - String username = credentials.substring(0, p).trim(); - String password = credentials.substring(p + 1).trim(); + var username = credentials.substring(0, p).trim(); + var password = credentials.substring(p + 1).trim(); // authenticate using username & password return this.parent.metadata.authenticate(username, password); } @@ -140,7 +140,7 @@ private void sendErrorResponse(Request baseRequest, HttpServletResponse response /** * Parses a Request to JSON. - * + * * @param baseRequest the Request * @return the {@link JsonObject} * @throws OpenemsException on error @@ -159,7 +159,7 @@ private static JsonObject parseJson(Request baseRequest) throws OpenemsException /** * Handles an http request to 'jsonrpc' endpoint. - * + * * @param user the {@link User} * @param baseRequest the {@link Request} * @param httpRequest the {@link HttpServletRequest} @@ -167,7 +167,7 @@ private static JsonObject parseJson(Request baseRequest) throws OpenemsException */ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest httpRequest, HttpServletResponse httpResponse) { - UUID requestId = new UUID(0L, 0L); /* dummy UUID */ + var requestId = new UUID(0L, 0L); /* dummy UUID */ try { // call handler methods if (!httpRequest.getMethod().equals("POST")) { @@ -176,7 +176,7 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht } // parse json and add "jsonrpc" and "id" properties if missing - JsonObject json = RestHandler.parseJson(baseRequest); + var json = RestHandler.parseJson(baseRequest); if (!json.has("jsonrpc")) { json.addProperty("jsonrpc", "2.0"); } @@ -184,9 +184,9 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht json.addProperty("id", UUID.randomUUID().toString()); } if (json.has("params")) { - JsonObject params = JsonUtils.getAsJsonObject(json, "params"); + var params = JsonUtils.getAsJsonObject(json, "params"); if (params.has("payload")) { - JsonObject payload = JsonUtils.getAsJsonObject(params, "payload"); + var payload = JsonUtils.getAsJsonObject(params, "payload"); if (!payload.has("jsonrpc")) { payload.addProperty("jsonrpc", "2.0"); } @@ -198,11 +198,11 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht json.add("params", params); } // parse JSON-RPC Request - JsonrpcMessage message = JsonrpcMessage.from(json); + var message = JsonrpcMessage.from(json); if (!(message instanceof JsonrpcRequest)) { throw new OpenemsException("Only JSON-RPC Request is supported here."); } - JsonrpcRequest request = (JsonrpcRequest) message; + var request = (JsonrpcRequest) message; // handle the request CompletableFuture responseFuture = this.parent.jsonRpcRequestHandler diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/B2bWebsocket.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/B2bWebsocket.java index 1adc16df348..98e4587567e 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/B2bWebsocket.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/B2bWebsocket.java @@ -52,17 +52,17 @@ public B2bWebsocket() { private Config config; private final Runnable startServerWhenMetadataIsInitialized = () -> { - this.startServer(config.port(), config.poolSize(), config.debugMode()); + this.startServer(this.config.port(), this.config.poolSize(), this.config.debugMode()); }; @Activate - void activate(Config config) { + private void activate(Config config) { this.config = config; this.metadata.addOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); } @Deactivate - void deactivate() { + private void deactivate() { ThreadPoolUtils.shutdownAndAwaitTermination(this.executor, 5); this.metadata.removeOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); this.stopServer(); @@ -70,7 +70,7 @@ void deactivate() { /** * Create and start new server. - * + * * @param port the port * @param poolSize number of threads dedicated to handle the tasks * @param debugMode activate a regular debug log about the state of the tasks diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnClose.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnClose.java index 10789be885d..cd6d1427d80 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnClose.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnClose.java @@ -1,12 +1,9 @@ package io.openems.backend.b2bwebsocket; -import java.util.Optional; - import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsException; public class OnClose implements io.openems.common.websocket.OnClose { @@ -21,7 +18,7 @@ public OnClose(B2bWebsocket parent) { @Override public void run(WebSocket ws, int code, String reason, boolean remote) throws OpenemsException { WsData wsData = ws.getAttachment(); - Optional user = wsData.getUserOpt(); + var user = wsData.getUserOpt(); if (user.isPresent()) { this.parent.logInfo(this.log, "User [" + user.get().getName() + "] closed connection"); } else { diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnOpen.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnOpen.java index 310d2c971fe..917ef5eecd9 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnOpen.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnOpen.java @@ -28,21 +28,21 @@ public void run(WebSocket ws, JsonObject handshake) throws OpenemsNamedException try { // Read "Authorization" header for Simple HTTP authentication. Source: // https://stackoverflow.com/questions/16000517/how-to-get-password-from-http-basic-authentication - final String authorization = JsonUtils.getAsString(handshake, "Authorization"); + final var authorization = JsonUtils.getAsString(handshake, "Authorization"); if (authorization == null || !authorization.toLowerCase().startsWith("basic")) { throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception(); } String base64Credentials = authorization.substring("Basic".length()).trim(); byte[] credDecoded = Base64.getDecoder().decode(base64Credentials); - String credentials = new String(credDecoded, StandardCharsets.UTF_8); + var credentials = new String(credDecoded, StandardCharsets.UTF_8); // credentials = username:password - final String[] values = credentials.split(":", 2); + final var values = credentials.split(":", 2); if (values.length != 2) { throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception(); } - String username = values[0]; - String password = values[1]; + var username = values[0]; + var password = values[1]; User user = this.parent.metadata.authenticate(username, password); WsData wsData = ws.getAttachment(); diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnRequest.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnRequest.java index b85f866ad23..591341b0ff9 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnRequest.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/OnRequest.java @@ -27,7 +27,7 @@ public OnRequest(B2bWebsocket parent) { public CompletableFuture run(WebSocket ws, JsonrpcRequest request) throws OpenemsException, OpenemsNamedException { WsData wsData = ws.getAttachment(); - User user = wsData.getUserWithTimeout(5, TimeUnit.SECONDS); + var user = wsData.getUserWithTimeout(5, TimeUnit.SECONDS); switch (request.getMethod()) { @@ -42,7 +42,7 @@ public CompletableFuture run(WebSocket ws, Jso /** * Handles a {@link SubscribeEdgesChannelsRequest}. - * + * * @param wsData the WebSocket attachment * @param user the {@link User} * @param messageId the JSON-RPC Message-ID @@ -58,7 +58,7 @@ private CompletableFuture handleSubscribeEdgesCha } // activate SubscribedChannelsWorker - SubscribedEdgesChannelsWorker worker = wsData.getSubscribedChannelsWorker(); + var worker = wsData.getSubscribedChannelsWorker(); worker.handleSubscribeEdgesChannelsRequest(request); // JSON-RPC response diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/SubscribedEdgesChannelsWorker.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/SubscribedEdgesChannelsWorker.java index 1d4f7d4b9e4..f3a8f42c4e9 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/SubscribedEdgesChannelsWorker.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/SubscribedEdgesChannelsWorker.java @@ -6,7 +6,6 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -15,7 +14,6 @@ import io.openems.backend.b2bwebsocket.jsonrpc.notification.EdgesCurrentDataNotification; import io.openems.backend.b2bwebsocket.jsonrpc.request.SubscribeEdgesChannelsRequest; -import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.session.Role; import io.openems.common.types.ChannelAddress; @@ -54,7 +52,7 @@ public SubscribedEdgesChannelsWorker(B2bWebsocket parent, WsData wsData) { /** * Applies a SubscribeChannelsRequest. - * + * * @param request the SubscribeEdgesChannelsRequest */ public synchronized void handleSubscribeEdgesChannelsRequest(SubscribeEdgesChannelsRequest request) { @@ -66,7 +64,7 @@ public synchronized void handleSubscribeEdgesChannelsRequest(SubscribeEdgesChann /** * Updates the Subscription data. - * + * * @param edgeIds Set of Edge-IDs * @param channels Set of ChannelAddresses */ @@ -91,7 +89,7 @@ private synchronized void updateSubscription(Set edgeIds, Set edgeIds, Set user = new CompletableFuture(); + private final CompletableFuture user = new CompletableFuture<>(); public WsData(B2bWebsocket parent) { this.parent = parent; @@ -35,6 +35,14 @@ public CompletableFuture getUser() { return this.user; } + /** + * Gets the logged in User with a timeout. + * + * @param timeout the timeout length + * @param unit the {@link TimeUnit} of the timeout + * @return the {@link User} + * @throws OpenemsNamedException on error + */ public User getUserWithTimeout(long timeout, TimeUnit unit) throws OpenemsNamedException { try { return this.user.get(timeout, unit); @@ -49,7 +57,7 @@ public Optional getUserOpt() { /** * Gets the SubscribedChannelsWorker to take care of subscribe to CurrentData. - * + * * @return the SubscribedChannelsWorker */ public SubscribedEdgesChannelsWorker getSubscribedChannelsWorker() { @@ -60,9 +68,8 @@ public SubscribedEdgesChannelsWorker getSubscribedChannelsWorker() { public String toString() { if (this.user == null) { return "B2bWebsocket.WsData [user=UNKNOWN]"; - } else { - return "B2bWebsocket.WsData [user=" + user + "]"; } + return "B2bWebsocket.WsData [user=" + this.user + "]"; } @Override diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/notification/EdgesCurrentDataNotification.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/notification/EdgesCurrentDataNotification.java index 7d6143e13bf..36a50f361d7 100644 --- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/notification/EdgesCurrentDataNotification.java +++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/notification/EdgesCurrentDataNotification.java @@ -14,7 +14,7 @@ /** * Represents a JSON-RPC Notification for sending the current data of all * subscribed Channels of multiple Edges. - * + * *
  * {
  *   "jsonrpc": "2.0",
@@ -34,20 +34,27 @@ public class EdgesCurrentDataNotification extends JsonrpcNotification {
 	private final Table values = HashBasedTable.create();
 
 	public EdgesCurrentDataNotification() {
-		super(METHOD);
+		super(EdgesCurrentDataNotification.METHOD);
 	}
 
+	/**
+	 * Adds a value to the notification.
+	 * 
+	 * @param edgeId  the Edge-ID
+	 * @param channel the {@link ChannelAddress}
+	 * @param value   the value
+	 */
 	public void addValue(String edgeId, ChannelAddress channel, JsonElement value) {
 		this.values.put(edgeId, channel, value);
 	}
 
 	@Override
 	public JsonObject getParams() {
-		JsonObject j = new JsonObject();
+		var j = new JsonObject();
 		for (Entry> row : this.values.rowMap().entrySet()) {
 			String edgeId = row.getKey();
 			Map columns = row.getValue();
-			JsonObject jEdge = new JsonObject();
+			var jEdge = new JsonObject();
 			for (Entry column : columns.entrySet()) {
 				ChannelAddress channel = column.getKey();
 				JsonElement value = column.getValue();
diff --git a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/request/SubscribeEdgesChannelsRequest.java b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/request/SubscribeEdgesChannelsRequest.java
index 38ccd729fff..733100b96b9 100644
--- a/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/request/SubscribeEdgesChannelsRequest.java
+++ b/io.openems.backend.b2bwebsocket/src/io/openems/backend/b2bwebsocket/jsonrpc/request/SubscribeEdgesChannelsRequest.java
@@ -14,7 +14,7 @@
 
 /**
  * Represents a JSON-RPC Request to subscribe to Channels of multiple Edges.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -32,24 +32,38 @@ public class SubscribeEdgesChannelsRequest extends JsonrpcRequest {
 
 	public static final String METHOD = "subscribeEdgesChannels";
 
+	/**
+	 * Builds a {@link SubscribeEdgesChannelsRequest} from a {@link JsonrpcRequest}.
+	 * 
+	 * @param r the {@link JsonrpcRequest}
+	 * @return the {@link SubscribeEdgesChannelsRequest}
+	 * @throws OpenemsNamedException on error
+	 */
 	public static SubscribeEdgesChannelsRequest from(JsonrpcRequest r) throws OpenemsNamedException {
-		JsonObject p = r.getParams();
-		int count = JsonUtils.getAsInt(p, "count");
-		SubscribeEdgesChannelsRequest result = new SubscribeEdgesChannelsRequest(r, count);
-		JsonArray edgeIds = JsonUtils.getAsJsonArray(p, "ids");
+		var p = r.getParams();
+		var count = JsonUtils.getAsInt(p, "count");
+		var result = new SubscribeEdgesChannelsRequest(r, count);
+		var edgeIds = JsonUtils.getAsJsonArray(p, "ids");
 		for (JsonElement edgeId : edgeIds) {
 			result.addEdgeId(JsonUtils.getAsString(edgeId));
 		}
-		JsonArray channels = JsonUtils.getAsJsonArray(p, "channels");
+		var channels = JsonUtils.getAsJsonArray(p, "channels");
 		for (JsonElement channel : channels) {
-			ChannelAddress address = ChannelAddress.fromString(JsonUtils.getAsString(channel));
+			var address = ChannelAddress.fromString(JsonUtils.getAsString(channel));
 			result.addChannel(address);
 		}
 		return result;
 	}
 
+	/**
+	 * Builds a {@link SubscribeEdgesChannelsRequest} from a {@link JsonObject}.
+	 * 
+	 * @param j the {@link JsonObject}
+	 * @return the {@link SubscribeEdgesChannelsRequest}
+	 * @throws OpenemsNamedException on error
+	 */
 	public static SubscribeEdgesChannelsRequest from(JsonObject j) throws OpenemsNamedException {
-		return from(GenericJsonrpcRequest.from(j));
+		return SubscribeEdgesChannelsRequest.from(GenericJsonrpcRequest.from(j));
 	}
 
 	private final int count;
@@ -57,27 +71,42 @@ public static SubscribeEdgesChannelsRequest from(JsonObject j) throws OpenemsNam
 	private final TreeSet channels = new TreeSet<>();
 
 	private SubscribeEdgesChannelsRequest(JsonrpcRequest request, int count) {
-		super(request, METHOD);
+		super(request, SubscribeEdgesChannelsRequest.METHOD);
 		this.count = count;
 	}
 
 	public SubscribeEdgesChannelsRequest(int count) {
-		super(METHOD);
+		super(SubscribeEdgesChannelsRequest.METHOD);
 		this.count = count;
 	}
 
+	/**
+	 * Adds an Edge-ID.
+	 * 
+	 * @param edgeId the Edge-ID.
+	 */
 	public void addEdgeId(String edgeId) {
 		this.edgeIds.add(edgeId);
 	}
 
+	/**
+	 * Removes an Edge-ID.
+	 * 
+	 * @param edgeId the Edge-ID
+	 */
 	public void removeEdgeId(String edgeId) {
 		this.edgeIds.remove(edgeId);
 	}
 
 	public TreeSet getEdgeIds() {
-		return edgeIds;
+		return this.edgeIds;
 	}
 
+	/**
+	 * Adds a Channel.
+	 * 
+	 * @param address the {@link ChannelAddress}
+	 */
 	public void addChannel(ChannelAddress address) {
 		this.channels.add(address);
 	}
@@ -87,16 +116,16 @@ public int getCount() {
 	}
 
 	public TreeSet getChannels() {
-		return channels;
+		return this.channels;
 	}
 
 	@Override
 	public JsonObject getParams() {
-		JsonArray edgeIds = new JsonArray();
+		var edgeIds = new JsonArray();
 		for (String edgeId : this.edgeIds) {
 			edgeIds.add(edgeId);
 		}
-		JsonArray channels = new JsonArray();
+		var channels = new JsonArray();
 		for (ChannelAddress address : this.channels) {
 			channels.add(address.toString());
 		}
diff --git a/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/B2bWebsocketTest.java b/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/B2bWebsocketTest.java
index 4ad0fc7a177..fa63b164e9f 100644
--- a/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/B2bWebsocketTest.java
+++ b/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/B2bWebsocketTest.java
@@ -6,14 +6,12 @@
 import java.util.Base64;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
 
 import io.openems.backend.b2bwebsocket.jsonrpc.request.SubscribeEdgesChannelsRequest;
 import io.openems.backend.common.jsonrpc.request.GetEdgesChannelsValuesRequest;
 import io.openems.backend.common.jsonrpc.request.GetEdgesStatusRequest;
 import io.openems.common.exceptions.OpenemsError.OpenemsNamedException;
-import io.openems.common.jsonrpc.base.JsonrpcResponseSuccess;
 import io.openems.common.jsonrpc.request.SetGridConnScheduleRequest;
 import io.openems.common.jsonrpc.request.SetGridConnScheduleRequest.GridConnSchedule;
 import io.openems.common.types.ChannelAddress;
@@ -32,22 +30,23 @@ public class B2bWebsocketTest {
 
 	private static TestClient prepareTestClient() throws URISyntaxException, InterruptedException {
 		Map httpHeaders = new HashMap<>();
-		String auth = new String(Base64.getEncoder().encode((USERNAME + ":" + PASSWORD).getBytes()),
+		var auth = new String(
+				Base64.getEncoder().encode((B2bWebsocketTest.USERNAME + ":" + B2bWebsocketTest.PASSWORD).getBytes()),
 				StandardCharsets.UTF_8);
 		httpHeaders.put("Authorization", "Basic " + auth);
-		TestClient client = new TestClient(new URI(URI), httpHeaders);
+		var client = new TestClient(new URI(B2bWebsocketTest.URI), httpHeaders);
 		client.startBlocking();
 		return client;
 	}
 
 	// @Test
-	public void testGetEdgesStatusRequest()
+	protected void testGetEdgesStatusRequest()
 			throws URISyntaxException, InterruptedException, ExecutionException, OpenemsNamedException {
-		TestClient client = prepareTestClient();
+		var client = B2bWebsocketTest.prepareTestClient();
 
-		GetEdgesStatusRequest request = new GetEdgesStatusRequest();
+		var request = new GetEdgesStatusRequest();
 		try {
-			CompletableFuture responseFuture = client.sendRequest(request);
+			var responseFuture = client.sendRequest(request);
 			System.out.println(responseFuture.get().toString());
 		} catch (InterruptedException | ExecutionException | OpenemsNamedException e) {
 			System.out.println(e.getMessage());
@@ -56,15 +55,15 @@ public void testGetEdgesStatusRequest()
 	}
 
 	// @Test
-	public void testGetEdgesChannelsValuesRequest() throws URISyntaxException, InterruptedException {
-		TestClient client = prepareTestClient();
+	protected void testGetEdgesChannelsValuesRequest() throws URISyntaxException, InterruptedException {
+		var client = B2bWebsocketTest.prepareTestClient();
 
-		GetEdgesChannelsValuesRequest request = new GetEdgesChannelsValuesRequest();
+		var request = new GetEdgesChannelsValuesRequest();
 		request.addEdgeId("edge0");
 		request.addChannel(new ChannelAddress("_sum", "EssSoc"));
 		request.addChannel(new ChannelAddress("_sum", "ProductionActivePower"));
 		try {
-			CompletableFuture responseFuture = client.sendRequest(request);
+			var responseFuture = client.sendRequest(request);
 			System.out.println(responseFuture.get().toString());
 		} catch (InterruptedException | ExecutionException | OpenemsNamedException e) {
 			System.out.println(e.getMessage());
@@ -73,19 +72,19 @@ public void testGetEdgesChannelsValuesRequest() throws URISyntaxException, Inter
 	}
 
 	// @Test
-	public void testSubscribeEdgesChannelsRequest()
+	protected void testSubscribeEdgesChannelsRequest()
 			throws URISyntaxException, InterruptedException, ExecutionException, OpenemsNamedException {
-		TestClient client = prepareTestClient();
+		var client = B2bWebsocketTest.prepareTestClient();
 		client.setOnNotification((ws, notification) -> {
 			System.out.println(notification.toString());
 		});
 
-		SubscribeEdgesChannelsRequest request = new SubscribeEdgesChannelsRequest(0);
+		var request = new SubscribeEdgesChannelsRequest(0);
 		request.addEdgeId("edge0");
 		request.addChannel(new ChannelAddress("_sum", "EssSoc"));
 		request.addChannel(new ChannelAddress("_sum", "ProductionActivePower"));
 		try {
-			CompletableFuture responseFuture = client.sendRequest(request);
+			var responseFuture = client.sendRequest(request);
 			System.out.println(responseFuture.get().toString());
 		} catch (InterruptedException | ExecutionException | OpenemsNamedException e) {
 			System.out.println(e.getMessage());
@@ -95,16 +94,16 @@ public void testSubscribeEdgesChannelsRequest()
 		client.stop();
 	}
 
-//	@Test
-	public void testSetGridConnSchedule() throws URISyntaxException, InterruptedException {
-		TestClient client = prepareTestClient();
+	// @Test
+	protected void testSetGridConnSchedule() throws URISyntaxException, InterruptedException {
+		var client = B2bWebsocketTest.prepareTestClient();
 
-		SetGridConnScheduleRequest request = new SetGridConnScheduleRequest("edge0");
-		long now = System.currentTimeMillis() / 1000;
+		var request = new SetGridConnScheduleRequest("edge0");
+		var now = System.currentTimeMillis() / 1000;
 		request.addScheduleEntry(new GridConnSchedule(now, 60, 0));
 		// request.addScheduleEntry(new GridConnSchedule(now + 60, 60, -5000));
 		try {
-			CompletableFuture responseFuture = client.sendRequest(request);
+			var responseFuture = client.sendRequest(request);
 			System.out.println(responseFuture.get().toString());
 		} catch (InterruptedException | ExecutionException | OpenemsNamedException e) {
 			System.out.println(e.getMessage());
diff --git a/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/TestClient.java b/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/TestClient.java
index fd7a14ad926..ea09598672f 100644
--- a/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/TestClient.java
+++ b/io.openems.backend.b2bwebsocket/test/io/openems/backend/b2bwebsocket/TestClient.java
@@ -17,7 +17,7 @@
 
 public class TestClient extends AbstractWebsocketClient {
 
-	private Logger log = LoggerFactory.getLogger(TestClient.class);
+	private final Logger log = LoggerFactory.getLogger(TestClient.class);
 
 	private OnOpen onOpen;
 	private OnRequest onRequest;
@@ -28,26 +28,26 @@ public class TestClient extends AbstractWebsocketClient {
 	protected TestClient(URI serverUri, Map httpHeaders) {
 		super("B2bwebsocket.Unittest", serverUri, httpHeaders);
 		this.onOpen = (ws, handshake) -> {
-			log.info("OnOpen: " + handshake);
+			this.log.info("OnOpen: " + handshake);
 		};
 		this.onRequest = (ws, request) -> {
-			log.info("OnRequest: " + request);
+			this.log.info("OnRequest: " + request);
 			return null;
 		};
 		this.onNotification = (ws, notification) -> {
-			log.info("OnNotification: " + notification);
+			this.log.info("OnNotification: " + notification);
 		};
 		this.onError = (ws, ex) -> {
-			log.info("onError: " + ex.getMessage());
+			this.log.info("onError: " + ex.getMessage());
 		};
 		this.onClose = (ws, code, reason, remote) -> {
-			log.info("onClose: " + reason);
+			this.log.info("onClose: " + reason);
 		};
 	}
 
 	@Override
 	public OnOpen getOnOpen() {
-		return onOpen;
+		return this.onOpen;
 	}
 
 	public void setOnOpen(OnOpen onOpen) {
@@ -56,7 +56,7 @@ public void setOnOpen(OnOpen onOpen) {
 
 	@Override
 	public OnRequest getOnRequest() {
-		return onRequest;
+		return this.onRequest;
 	}
 
 	public void setOnRequest(OnRequest onRequest) {
@@ -65,7 +65,7 @@ public void setOnRequest(OnRequest onRequest) {
 
 	@Override
 	public OnError getOnError() {
-		return onError;
+		return this.onError;
 	}
 
 	public void setOnError(OnError onError) {
@@ -74,7 +74,7 @@ public void setOnError(OnError onError) {
 
 	@Override
 	public OnClose getOnClose() {
-		return onClose;
+		return this.onClose;
 	}
 
 	public void setOnClose(OnClose onClose) {
@@ -83,7 +83,7 @@ public void setOnClose(OnClose onClose) {
 
 	@Override
 	protected OnNotification getOnNotification() {
-		return onNotification;
+		return this.onNotification;
 	}
 
 	public void setOnNotification(OnNotification onNotification) {
diff --git a/io.openems.backend.common/src/io/openems/backend/common/component/AbstractOpenemsBackendComponent.java b/io.openems.backend.common/src/io/openems/backend/common/component/AbstractOpenemsBackendComponent.java
index 3579857fd7f..433c67a0846 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/component/AbstractOpenemsBackendComponent.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/component/AbstractOpenemsBackendComponent.java
@@ -9,7 +9,7 @@ public class AbstractOpenemsBackendComponent {
 
 	/**
 	 * Initializes the AbstractOpenemsBackendComponent.
-	 * 
+	 *
 	 * @param name a descriptive name for this component. Available via
 	 *             {@link #getName()}
 	 */
@@ -19,7 +19,7 @@ public AbstractOpenemsBackendComponent(String name) {
 
 	/**
 	 * A descriptive name for this component.
-	 * 
+	 *
 	 * @return the name
 	 */
 	public String getName() {
@@ -28,7 +28,7 @@ public String getName() {
 
 	/**
 	 * Log an info message including the Component ID.
-	 * 
+	 *
 	 * @param log     the Logger that is used for writing the log
 	 * @param message the Info-message
 	 */
@@ -38,7 +38,7 @@ protected void logInfo(Logger log, String message) {
 
 	/**
 	 * Log a warn message including the Component ID.
-	 * 
+	 *
 	 * @param log     the Logger that is used for writing the log
 	 * @param message the Warn-message
 	 */
@@ -48,7 +48,7 @@ protected void logWarn(Logger log, String message) {
 
 	/**
 	 * Log an error message including the Component ID.
-	 * 
+	 *
 	 * @param log     the Logger that is used for writing the log
 	 * @param message the Error-message
 	 */
@@ -58,7 +58,7 @@ protected void logError(Logger log, String message) {
 
 	/**
 	 * Log a debug message including the Component ID.
-	 * 
+	 *
 	 * @param log     the Logger that is used for writing the log
 	 * @param message the Debug-message
 	 */
diff --git a/io.openems.backend.common/src/io/openems/backend/common/edgewebsocket/EdgeWebsocket.java b/io.openems.backend.common/src/io/openems/backend/common/edgewebsocket/EdgeWebsocket.java
index 9418e2e6b44..c661efc99d8 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/edgewebsocket/EdgeWebsocket.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/edgewebsocket/EdgeWebsocket.java
@@ -17,7 +17,7 @@ public interface EdgeWebsocket {
 	/**
 	 * Send an authenticated JSON-RPC Request to an Edge via Websocket and expect a
 	 * JSON-RPC Response.
-	 * 
+	 *
 	 * @param edgeId  the Edge-ID
 	 * @param user    the authenticated {@link User}
 	 * @param request the {@link JsonrpcRequest}
@@ -29,7 +29,7 @@ public CompletableFuture send(String edgeId, User user,
 
 	/**
 	 * Send a JSON-RPC Notification to an Edge.
-	 * 
+	 *
 	 * @param edgeId       the Edge-ID
 	 * @param notification the JsonrpcNotification
 	 * @throws OpenemsNamedException on error
@@ -38,7 +38,7 @@ public CompletableFuture send(String edgeId, User user,
 
 	/**
 	 * Handles a {@link SubscribeSystemLogRequest}.
-	 * 
+	 *
 	 * @param edgeId  the Edge-ID
 	 * @param user    the {@link User}
 	 * @param token   the UI session token
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/JsonRpcRequestHandler.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/JsonRpcRequestHandler.java
index 4a418c1a575..875fc9b39f9 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/JsonRpcRequestHandler.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/JsonRpcRequestHandler.java
@@ -11,7 +11,7 @@ public interface JsonRpcRequestHandler {
 
 	/**
 	 * Handles a JSON-RPC Request.
-	 * 
+	 *
 	 * @param context the Logger context, i.e. the name of the parent source
 	 * @param user    the User
 	 * @param request the JsonrpcRequest
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/AddEdgeToUserRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/AddEdgeToUserRequest.java
index 8d38068a7ac..c0f38201189 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/AddEdgeToUserRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/AddEdgeToUserRequest.java
@@ -8,7 +8,7 @@
 
 /**
  * Adds a Edge to a User.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -26,26 +26,26 @@ public class AddEdgeToUserRequest extends JsonrpcRequest {
 
 	/**
 	 * Create {@link AddEdgeToUserRequest} from a template {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param r the template {@link JsonrpcRequest}
 	 * @return the {@link AddEdgeToUserRequest}
 	 * @throws OpenemsNamedException on parse error
 	 */
 	public static AddEdgeToUserRequest from(JsonrpcRequest r) throws OpenemsNamedException {
-		JsonObject p = r.getParams();
-		String setupPassword = JsonUtils.getAsString(p, "setupPassword");
+		var p = r.getParams();
+		var setupPassword = JsonUtils.getAsString(p, "setupPassword");
 		return new AddEdgeToUserRequest(r, setupPassword);
 	}
 
 	private final String setupPassword;
 
 	public AddEdgeToUserRequest(String setupPassword) {
-		super(METHOD);
+		super(AddEdgeToUserRequest.METHOD);
 		this.setupPassword = setupPassword;
 	}
 
 	private AddEdgeToUserRequest(JsonrpcRequest request, String setupPassword) {
-		super(request, METHOD);
+		super(request, AddEdgeToUserRequest.METHOD);
 		this.setupPassword = setupPassword;
 	}
 
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesChannelsValuesRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesChannelsValuesRequest.java
index f269612d9b9..557df13c06f 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesChannelsValuesRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesChannelsValuesRequest.java
@@ -13,7 +13,7 @@
 
 /**
  * Represents a JSON-RPC Request for 'getChannelsValues'.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -33,21 +33,21 @@ public class GetEdgesChannelsValuesRequest extends JsonrpcRequest {
 	/**
 	 * Create {@link GetEdgesChannelsValuesRequest} from a template
 	 * {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param r the template {@link JsonrpcRequest}
 	 * @return the {@link GetEdgesChannelsValuesRequest}
 	 * @throws OpenemsNamedException on parse error
 	 */
 	public static GetEdgesChannelsValuesRequest from(JsonrpcRequest r) throws OpenemsNamedException {
-		JsonObject p = r.getParams();
-		GetEdgesChannelsValuesRequest result = new GetEdgesChannelsValuesRequest(r);
-		JsonArray edgeIds = JsonUtils.getAsJsonArray(p, "ids");
+		var p = r.getParams();
+		var result = new GetEdgesChannelsValuesRequest(r);
+		var edgeIds = JsonUtils.getAsJsonArray(p, "ids");
 		for (JsonElement edgeId : edgeIds) {
 			result.addEdgeId(JsonUtils.getAsString(edgeId));
 		}
-		JsonArray channels = JsonUtils.getAsJsonArray(p, "channels");
+		var channels = JsonUtils.getAsJsonArray(p, "channels");
 		for (JsonElement channel : channels) {
-			ChannelAddress address = ChannelAddress.fromString(JsonUtils.getAsString(channel));
+			var address = ChannelAddress.fromString(JsonUtils.getAsString(channel));
 			result.addChannel(address);
 		}
 		return result;
@@ -57,16 +57,16 @@ public static GetEdgesChannelsValuesRequest from(JsonrpcRequest r) throws Openem
 	private final TreeSet channels = new TreeSet<>();
 
 	public GetEdgesChannelsValuesRequest() {
-		super(METHOD);
+		super(GetEdgesChannelsValuesRequest.METHOD);
 	}
 
 	private GetEdgesChannelsValuesRequest(JsonrpcRequest request) {
-		super(request, METHOD);
+		super(request, GetEdgesChannelsValuesRequest.METHOD);
 	}
 
 	/**
 	 * Adds a Edge-ID.
-	 * 
+	 *
 	 * @param edgeId the Edge-ID
 	 */
 	public void addEdgeId(String edgeId) {
@@ -75,7 +75,7 @@ public void addEdgeId(String edgeId) {
 
 	/**
 	 * Gets the Edge-IDs.
-	 * 
+	 *
 	 * @return set of Edge-IDs.
 	 */
 	public TreeSet getEdgeIds() {
@@ -84,7 +84,7 @@ public TreeSet getEdgeIds() {
 
 	/**
 	 * Adds a {@link ChannelAddress}.
-	 * 
+	 *
 	 * @param address the {@link ChannelAddress}
 	 */
 	public void addChannel(ChannelAddress address) {
@@ -93,7 +93,7 @@ public void addChannel(ChannelAddress address) {
 
 	/**
 	 * Gets the {@link ChannelAddress}es.
-	 * 
+	 *
 	 * @return the {@link ChannelAddress}es
 	 */
 	public TreeSet getChannels() {
@@ -102,11 +102,11 @@ public TreeSet getChannels() {
 
 	@Override
 	public JsonObject getParams() {
-		JsonArray edgeIds = new JsonArray();
+		var edgeIds = new JsonArray();
 		for (String edgeId : this.edgeIds) {
 			edgeIds.add(edgeId);
 		}
-		JsonArray channels = new JsonArray();
+		var channels = new JsonArray();
 		for (ChannelAddress address : this.channels) {
 			channels.add(address.toString());
 		}
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesStatusRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesStatusRequest.java
index e5f763aaa1c..2c58f519a1c 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesStatusRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetEdgesStatusRequest.java
@@ -8,7 +8,7 @@
 
 /**
  * Represents a JSON-RPC Request for 'getEdgesStatus'.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -24,7 +24,7 @@ public class GetEdgesStatusRequest extends JsonrpcRequest {
 
 	/**
 	 * Create {@link GetEdgesStatusRequest} from a template {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param r the template {@link JsonrpcRequest}
 	 * @return the {@link GetEdgesStatusRequest}
 	 * @throws OpenemsNamedException on parse error
@@ -34,11 +34,11 @@ public static GetEdgesStatusRequest from(JsonrpcRequest r) throws OpenemsExcepti
 	}
 
 	public GetEdgesStatusRequest() {
-		super(METHOD);
+		super(GetEdgesStatusRequest.METHOD);
 	}
 
 	private GetEdgesStatusRequest(JsonrpcRequest request) {
-		super(request, METHOD);
+		super(request, GetEdgesStatusRequest.METHOD);
 	}
 
 	@Override
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetSetupProtocolRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetSetupProtocolRequest.java
index 49d4951c965..aaf4dbb4d89 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetSetupProtocolRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetSetupProtocolRequest.java
@@ -13,12 +13,12 @@ public class GetSetupProtocolRequest extends JsonrpcRequest {
 	/**
 	 * Create {@link GetSetupProtocolRequest} from a template
 	 * {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param request the template {@link JsonrpcRequest}
 	 * @return Created {@link GetSetupProtocolRequest}
 	 */
 	public static GetSetupProtocolRequest from(JsonrpcRequest request) throws OpenemsNamedException {
-		JsonObject params = request.getParams();
+		var params = request.getParams();
 
 		return new GetSetupProtocolRequest(request, JsonUtils.getAsInt(params, "setupProtocolId"));
 	}
@@ -26,7 +26,7 @@ public static GetSetupProtocolRequest from(JsonrpcRequest request) throws Openem
 	private final int setupProtocolId;
 
 	private GetSetupProtocolRequest(JsonrpcRequest request, int setupProtocolId) {
-		super(request, METHOD);
+		super(request, GetSetupProtocolRequest.METHOD);
 		this.setupProtocolId = setupProtocolId;
 	}
 
@@ -39,7 +39,7 @@ public JsonObject getParams() {
 
 	/**
 	 * Gets the Setup Protocol ID.
-	 * 
+	 *
 	 * @return the Setup Protocol ID
 	 */
 	public int getSetupProtocolId() {
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetUserInformationRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetUserInformationRequest.java
index 31b824c1a37..8c70f547b0c 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetUserInformationRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/GetUserInformationRequest.java
@@ -6,7 +6,7 @@
 
 /**
  * Gets the User Information.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -23,7 +23,7 @@ public class GetUserInformationRequest extends JsonrpcRequest {
 	/**
 	 * Create {@link GetUserInformationRequest} from a template
 	 * {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param request the template {@link JsonrpcRequest}
 	 * @return Created {@link GetUserInformationRequest}
 	 */
@@ -32,7 +32,7 @@ public static GetUserInformationRequest from(JsonrpcRequest request) {
 	}
 
 	private GetUserInformationRequest(JsonrpcRequest request) {
-		super(request, METHOD);
+		super(request, GetUserInformationRequest.METHOD);
 	}
 
 	@Override
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/RegisterUserRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/RegisterUserRequest.java
index 3adf0d3b58c..a1f1dd1f35a 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/RegisterUserRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/RegisterUserRequest.java
@@ -12,12 +12,12 @@ public class RegisterUserRequest extends JsonrpcRequest {
 
 	/**
 	 * Create {@link RegisterUserRequest} from a template {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param request the template {@link JsonrpcRequest}
 	 * @return Created {@link RegisterUserRequest}
 	 */
 	public static RegisterUserRequest from(JsonrpcRequest request) throws OpenemsNamedException {
-		JsonObject params = request.getParams();
+		var params = request.getParams();
 
 		return new RegisterUserRequest(request, JsonUtils.getAsJsonObject(params, "user"));
 	}
@@ -25,7 +25,7 @@ public static RegisterUserRequest from(JsonrpcRequest request) throws OpenemsNam
 	private final JsonObject jsonObject;
 
 	private RegisterUserRequest(JsonrpcRequest request, JsonObject jsonObject) {
-		super(request, METHOD);
+		super(request, RegisterUserRequest.METHOD);
 		this.jsonObject = jsonObject;
 	}
 
@@ -36,7 +36,7 @@ public JsonObject getParams() {
 
 	/**
 	 * Gets the User Registration information as {@link JsonObject}.
-	 * 
+	 *
 	 * @return the {@link JsonObject}
 	 */
 	public JsonObject getJsonObject() {
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SetUserInformationRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SetUserInformationRequest.java
index 8b28ce227dd..e5504cef444 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SetUserInformationRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SetUserInformationRequest.java
@@ -8,7 +8,7 @@
 
 /**
  * Sets the User Information.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -41,13 +41,13 @@ public class SetUserInformationRequest extends JsonrpcRequest {
 	/**
 	 * Create {@link SetUserInformationRequest} from a template
 	 * {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param request the template {@link JsonrpcRequest}
 	 * @return Created {@link SetUserInformationRequest}
 	 * @throws OpenemsNamedException on parse error
 	 */
 	public static SetUserInformationRequest from(JsonrpcRequest request) throws OpenemsNamedException {
-		JsonObject params = request.getParams();
+		var params = request.getParams();
 
 		return new SetUserInformationRequest(request, JsonUtils.getAsJsonObject(params, "user"));
 	}
@@ -55,7 +55,7 @@ public static SetUserInformationRequest from(JsonrpcRequest request) throws Open
 	private final JsonObject jsonObject;
 
 	private SetUserInformationRequest(JsonrpcRequest request, JsonObject jsonObject) {
-		super(request, METHOD);
+		super(request, SetUserInformationRequest.METHOD);
 		this.jsonObject = jsonObject;
 	}
 
@@ -66,7 +66,7 @@ public JsonObject getParams() {
 
 	/**
 	 * Gets the User Information as {@link JsonObject}.
-	 * 
+	 *
 	 * @return the {@link JsonObject}
 	 */
 	public JsonObject getJsonObject() {
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SubmitSetupProtocolRequest.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SubmitSetupProtocolRequest.java
index 13c27d7f46e..679f563f266 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SubmitSetupProtocolRequest.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/request/SubmitSetupProtocolRequest.java
@@ -8,7 +8,7 @@
 
 /**
  * Submits the Setup Protocol.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -18,7 +18,7 @@
  *     "protocol": {
  *       "edge": {
  *         "id": string
- *       }, 
+ *       },
  *       "customer": {
  *         "firstname": string,
  *         "lastname": string,
@@ -71,20 +71,20 @@ public class SubmitSetupProtocolRequest extends JsonrpcRequest {
 	/**
 	 * Create {@link SubmitSetupProtocolRequest} from a template
 	 * {@link JsonrpcRequest}.
-	 * 
+	 *
 	 * @param request the template {@link JsonrpcRequest}
 	 * @return Created {@link SubmitSetupProtocolRequest}
 	 * @throws OpenemsNamedException on parse error
 	 */
 	public static SubmitSetupProtocolRequest from(JsonrpcRequest request) throws OpenemsNamedException {
-		JsonObject params = request.getParams();
+		var params = request.getParams();
 		return new SubmitSetupProtocolRequest(request, JsonUtils.getAsJsonObject(params, "protocol"));
 	}
 
 	private final JsonObject jsonObject;
 
 	private SubmitSetupProtocolRequest(JsonrpcRequest request, JsonObject jsonObject) {
-		super(request, METHOD);
+		super(request, SubmitSetupProtocolRequest.METHOD);
 		this.jsonObject = jsonObject;
 	}
 
@@ -95,7 +95,7 @@ public JsonObject getParams() {
 
 	/**
 	 * Gets the Setup Protocol information as {@link JsonObject}.
-	 * 
+	 *
 	 * @return the {@link JsonObject}
 	 */
 	public JsonObject getJsonObject() {
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/AddEdgeToUserResponse.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/AddEdgeToUserResponse.java
index 30ce30a1c3b..05045d53474 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/AddEdgeToUserResponse.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/AddEdgeToUserResponse.java
@@ -11,7 +11,7 @@
 
 /**
  * Represents a JSON-RPC Response for {@link AddEdgeToUserRequest}.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -34,7 +34,7 @@ public AddEdgeToUserResponse(UUID id, Edge edge) {
 		super(id);
 		this.edge = edge;
 	}
-	
+
 	@Override
 	public JsonObject getResult() {
 		return JsonUtils.buildJsonObject() //
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesChannelsValuesResponse.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesChannelsValuesResponse.java
index b0f46c0ab7e..6e4b8544af6 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesChannelsValuesResponse.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesChannelsValuesResponse.java
@@ -15,7 +15,7 @@
 
 /**
  * Represents a JSON-RPC Response for {@link GetEdgesChannelsValuesRequest}.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -42,7 +42,7 @@ public GetEdgesChannelsValuesResponse(UUID id) {
 
 	/**
 	 * Adds a Value to the JSON-RPC Response.
-	 * 
+	 *
 	 * @param edgeId  the Edge-ID
 	 * @param channel the {@link ChannelAddress}
 	 * @param value   the value
@@ -53,11 +53,11 @@ public void addValue(String edgeId, ChannelAddress channel, JsonElement value) {
 
 	@Override
 	public JsonObject getResult() {
-		JsonObject j = new JsonObject();
+		var j = new JsonObject();
 		for (Entry> row : this.values.rowMap().entrySet()) {
 			String edgeId = row.getKey();
 			Map columns = row.getValue();
-			JsonObject jEdge = new JsonObject();
+			var jEdge = new JsonObject();
 			for (Entry column : columns.entrySet()) {
 				ChannelAddress channel = column.getKey();
 				JsonElement value = column.getValue();
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesStatusResponse.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesStatusResponse.java
index 3e63200a0cb..7680bf570b9 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesStatusResponse.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetEdgesStatusResponse.java
@@ -12,7 +12,7 @@
 
 /**
  * Represents a JSON-RPC Response for {@link GetEdgesStatusRequest}.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -51,7 +51,7 @@ public GetEdgesStatusResponse(UUID id, Map edgeInfos) {
 
 	@Override
 	public JsonObject getResult() {
-		JsonObject j = new JsonObject();
+		var j = new JsonObject();
 		for (Entry entry : this.edgeInfos.entrySet()) {
 			EdgeInfo edge = entry.getValue();
 			j.add(entry.getKey(), JsonUtils.buildJsonObject() //
diff --git a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetUserInformationResponse.java b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetUserInformationResponse.java
index 67564d25451..5ce64b7e5ce 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetUserInformationResponse.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/jsonrpc/response/GetUserInformationResponse.java
@@ -12,7 +12,7 @@
 
 /**
  * Represents a JSON-RPC Response for {@link GetUserInformationRequest}.
- * 
+ *
  * 
  * {
  *   "jsonrpc": "2.0",
@@ -48,7 +48,7 @@ public GetUserInformationResponse(UUID id, Map userInformation)
 
 	@Override
 	public JsonObject getResult() {
-		JsonObject companyJson = JsonUtils.buildJsonObject() //
+		var companyJson = JsonUtils.buildJsonObject() //
 				.addProperty("name", ObjectUtils.getAsString(this.userInformation.get("commercial_company_name"))) //
 				.build();
 
@@ -58,14 +58,14 @@ public JsonObject getResult() {
 			country = ObjectUtils.getAsString(array[2]).toLowerCase();
 		}
 
-		JsonObject addressJson = JsonUtils.buildJsonObject() //
+		var addressJson = JsonUtils.buildJsonObject() //
 				.addProperty("street", ObjectUtils.getAsString(this.userInformation.get("street"))) //
 				.addProperty("zip", ObjectUtils.getAsString(this.userInformation.get("zip"))) //
 				.addProperty("city", ObjectUtils.getAsString(this.userInformation.get("city"))) //
 				.addProperty("country", country) //
 				.build();
 
-		JsonObject userJson = JsonUtils.buildJsonObject() //
+		var userJson = JsonUtils.buildJsonObject() //
 				.addProperty("firstname", ObjectUtils.getAsString(this.userInformation.get("firstname"))) //
 				.addProperty("lastname", ObjectUtils.getAsString(this.userInformation.get("lastname"))) //
 				.addProperty("email", ObjectUtils.getAsString(this.userInformation.get("email"))) //
diff --git a/io.openems.backend.common/src/io/openems/backend/common/metadata/AbstractMetadata.java b/io.openems.backend.common/src/io/openems/backend/common/metadata/AbstractMetadata.java
index 0fb4af2c6ff..7e6c3d6f0b6 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/metadata/AbstractMetadata.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/metadata/AbstractMetadata.java
@@ -10,7 +10,7 @@ public abstract class AbstractMetadata extends AbstractOpenemsBackendComponent i
 
 	/**
 	 * Initializes the AbstractMetadata.
-	 * 
+	 *
 	 * @param name a descriptive name for this component. Available via
 	 *             {@link #getName()}
 	 */
diff --git a/io.openems.backend.common/src/io/openems/backend/common/metadata/Edge.java b/io.openems.backend.common/src/io/openems/backend/common/metadata/Edge.java
index 3f0bfd94f44..012a510e375 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/metadata/Edge.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/metadata/Edge.java
@@ -66,6 +66,11 @@ public EdgeConfig getConfig() {
 		return this.config;
 	}
 
+	/**
+	 * Gets this {@link Edge} as {@link JsonObject}.
+	 * 
+	 * @return a {@link JsonObject}
+	 */
 	public JsonObject toJsonObject() {
 		return JsonUtils.buildJsonObject() //
 				.addProperty("id", this.id) //
@@ -78,10 +83,17 @@ public JsonObject toJsonObject() {
 
 	@Override
 	public String toString() {
-		return "Edge [id=" + id + ", comment=" + comment + ", state=" + state + ", version=" + version
-				+ ", producttype=" + producttype + ", deprecatedConfig="
-				+ (config.toString().isEmpty() ? "NOT_SET" : "set") + ", lastMessage=" + lastMessage + ", lastUpdate="
-				+ lastUpdate + ", isOnline=" + isOnline + "]";
+		return "Edge [" //
+				+ "id=" + this.id + ", " //
+				+ "comment=" + this.comment + ", " //
+				+ "state=" + this.state + ", " //
+				+ "version=" + this.version + ", " //
+				+ "producttype=" + this.producttype + ", " //
+				+ "deprecatedConfig=" + (this.config.toString().isEmpty() ? "NOT_SET" : "set") + ", " //
+				+ "lastMessage=" + this.lastMessage + ", " //
+				+ "lastUpdate=" + this.lastUpdate + ", " //
+				+ "isOnline=" + this.isOnline //
+				+ "]";
 	}
 
 	/*
@@ -89,6 +101,11 @@ public String toString() {
 	 */
 	private final List> onSetOnline = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Online events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetOnline(Consumer listener) {
 		this.onSetOnline.add(listener);
 	}
@@ -99,7 +116,7 @@ public boolean isOnline() {
 
 	/**
 	 * Marks this Edge as being online. This is called by an event listener.
-	 * 
+	 *
 	 * @param isOnline true if the Edge is online
 	 */
 	public synchronized void setOnline(boolean isOnline) {
@@ -115,7 +132,7 @@ public synchronized void setOnline(boolean isOnline) {
 	/**
 	 * Adds a listener for reception of new EdgeConfig. The listener is called
 	 * before the new config is applied.
-	 * 
+	 *
 	 * @param listener the Listener
 	 */
 	public void onSetConfig(Consumer listener) {
@@ -124,7 +141,7 @@ public void onSetConfig(Consumer listener) {
 
 	/**
 	 * Sets the configuration for this Edge and calls the SetConfig-Listeners.
-	 * 
+	 *
 	 * @param config the configuration
 	 */
 	public synchronized void setConfig(EdgeConfig config) {
@@ -133,7 +150,7 @@ public synchronized void setConfig(EdgeConfig config) {
 
 	/**
 	 * Sets the configuration for this Edge.
-	 * 
+	 *
 	 * @param config        the configuration
 	 * @param callListeners whether to call the SetConfig-Listeners
 	 */
@@ -160,6 +177,11 @@ public State getState() {
 	 */
 	private final List onSetLastMessageTimestamp = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Last-Message events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetLastMessage(Runnable listener) {
 		this.onSetLastMessageTimestamp.add(listener);
 	}
@@ -173,14 +195,14 @@ public synchronized void setLastMessageTimestamp() {
 
 	/**
 	 * Sets the Last-Message-Timestamp.
-	 * 
+	 *
 	 * @param callListeners whether to call the SetLastMessage-Listeners
 	 */
 	public synchronized void setLastMessageTimestamp(boolean callListeners) {
 		if (callListeners) {
-			this.onSetLastMessageTimestamp.forEach(listener -> listener.run());
+			this.onSetLastMessageTimestamp.forEach(Runnable::run);
 		}
-		ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
+		var now = ZonedDateTime.now(ZoneOffset.UTC);
 		this.lastMessage = now;
 	}
 
@@ -193,6 +215,11 @@ public ZonedDateTime getLastMessageTimestamp() {
 	 */
 	private final List onSetLastUpdateTimestamp = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Last-Update events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetLastUpdate(Runnable listener) {
 		this.onSetLastUpdateTimestamp.add(listener);
 	}
@@ -206,14 +233,14 @@ public synchronized void setLastUpdateTimestamp() {
 
 	/**
 	 * Sets the Last-Update-Timestamp.
-	 * 
+	 *
 	 * @param callListeners whether to call the SetLastUpdate-Listeners
 	 */
 	public synchronized void setLastUpdateTimestamp(boolean callListeners) {
 		if (callListeners) {
-			this.onSetLastUpdateTimestamp.forEach(listener -> listener.run());
+			this.onSetLastUpdateTimestamp.forEach(Runnable::run);
 		}
-		ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
+		var now = ZonedDateTime.now(ZoneOffset.UTC);
 		this.lastUpdate = now;
 	}
 
@@ -230,13 +257,18 @@ public SemanticVersion getVersion() {
 
 	private final List> onSetVersion = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Version events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetVersion(Consumer listener) {
 		this.onSetVersion.add(listener);
 	}
 
 	/**
 	 * Sets the version and calls the SetVersion-Listeners.
-	 * 
+	 *
 	 * @param version the version
 	 */
 	public synchronized void setVersion(SemanticVersion version) {
@@ -245,7 +277,7 @@ public synchronized void setVersion(SemanticVersion version) {
 
 	/**
 	 * Sets the version.
-	 * 
+	 *
 	 * @param version       the version
 	 * @param callListeners whether to call the SetVersion-Listeners
 	 */
@@ -269,13 +301,18 @@ public String getProducttype() {
 
 	private final List> onSetProducttype = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Product-Type events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetProducttype(Consumer listener) {
 		this.onSetProducttype.add(listener);
 	}
 
 	/**
 	 * Sets the Producttype and calls the SetProducttype-Listeners.
-	 * 
+	 *
 	 * @param producttype the Producttype
 	 */
 	public synchronized void setProducttype(String producttype) {
@@ -284,7 +321,7 @@ public synchronized void setProducttype(String producttype) {
 
 	/**
 	 * Sets the Producttype.
-	 * 
+	 *
 	 * @param producttype   the Producttype
 	 * @param callListeners whether to call the SetProducttype-Listeners
 	 */
@@ -308,13 +345,18 @@ public Level getSumState() {
 
 	private final List> onSetSumState = new CopyOnWriteArrayList<>();
 
+	/**
+	 * Add a Listener for Set-Sum-State events.
+	 * 
+	 * @param listener the listener
+	 */
 	public void onSetSumState(Consumer listener) {
 		this.onSetSumState.add(listener);
 	}
 
 	/**
 	 * Sets the sumState and calls the SetSumState-Listeners.
-	 * 
+	 *
 	 * @param sumState the sumState
 	 */
 	public synchronized void setSumState(Level sumState) {
@@ -323,7 +365,7 @@ public synchronized void setSumState(Level sumState) {
 
 	/**
 	 * Sets the version.
-	 * 
+	 *
 	 * @param sumState      the sumState
 	 * @param callListeners whether to call the SetSumState-Listeners
 	 */
diff --git a/io.openems.backend.common/src/io/openems/backend/common/metadata/Metadata.java b/io.openems.backend.common/src/io/openems/backend/common/metadata/Metadata.java
index abac6f29180..47033b1fa42 100644
--- a/io.openems.backend.common/src/io/openems/backend/common/metadata/Metadata.java
+++ b/io.openems.backend.common/src/io/openems/backend/common/metadata/Metadata.java
@@ -15,8 +15,8 @@
 import io.openems.common.channel.Level;
 import io.openems.common.exceptions.OpenemsError;
 import io.openems.common.exceptions.OpenemsError.OpenemsNamedException;
-import io.openems.common.jsonrpc.request.UpdateUserLanguageRequest.Language;
 import io.openems.common.exceptions.OpenemsException;
+import io.openems.common.jsonrpc.request.UpdateUserLanguageRequest.Language;
 import io.openems.common.types.ChannelAddress;
 import io.openems.common.types.EdgeConfig;
 import io.openems.common.types.EdgeConfig.Component.Channel;
@@ -28,32 +28,32 @@ public interface Metadata {
 
 	/**
 	 * Was the Metadata service fully initialized?.
-	 * 
+	 *
 	 * 

* The service might take some time in the beginning to establish a connection * or to cache data from an external database. - * + * * @return true if it is initialized */ public boolean isInitialized(); /** * See {@link #isInitialized()}. - * + * * @param callback the callback on 'isInitialized' */ public void addOnIsInitializedListener(Runnable callback); /** * See {@link #isInitialized()}. - * + * * @param callback the callback on 'isInitialized' */ public void removeOnIsInitializedListener(Runnable callback); /** * Authenticates the User by username and password. - * + * * @param username the Username * @param password the Password * @return the {@link User} @@ -63,7 +63,7 @@ public interface Metadata { /** * Authenticates the User by a Token. - * + * * @param token the Token * @return the {@link User} * @throws OpenemsNamedException on error @@ -72,14 +72,14 @@ public interface Metadata { /** * Closes a session for a User. - * + * * @param user the {@link User} */ public void logout(User user); /** * Gets the Edge-ID for an API-Key, i.e. authenticates the API-Key. - * + * * @param apikey the API-Key * @return the Edge-ID or Empty */ @@ -87,7 +87,7 @@ public interface Metadata { /** * Get an Edge by its unique Edge-ID. - * + * * @param edgeId the Edge-ID * @return the Edge as Optional */ @@ -96,23 +96,22 @@ public interface Metadata { /** * Get an Edge by its unique Edge-ID. Throws an Exception if there is no Edge * with this ID. - * + * * @param edgeId the Edge-ID * @return the Edge * @throws OpenemsException on error */ public default Edge getEdgeOrError(String edgeId) throws OpenemsException { - Optional edgeOpt = this.getEdge(edgeId); + var edgeOpt = this.getEdge(edgeId); if (edgeOpt.isPresent()) { return edgeOpt.get(); - } else { - throw new OpenemsException("Unable to get Edge for id [" + edgeId + "]"); } + throw new OpenemsException("Unable to get Edge for id [" + edgeId + "]"); } /** * Get an Edge by Edge-SetupPassword. - * + * * @param setupPassword to find Edge * @return Edge as a Optional */ @@ -120,7 +119,7 @@ public default Edge getEdgeOrError(String edgeId) throws OpenemsException { /** * Gets the User for the given User-ID. - * + * * @param userId the User-ID * @return the {@link User}, or Empty */ @@ -128,29 +127,29 @@ public default Edge getEdgeOrError(String edgeId) throws OpenemsException { /** * Gets all Edges. - * + * * @return collection of Edges. */ public abstract Collection getAllEdges(); /** * Assigns Edge with given setupPassword to the logged in user and returns it. - * + * *

* If the setupPassword is invalid, an OpenemsNamedException is thrown. - * + * * @param user the {@link User} * @param setupPassword the Setup-Password * @return the Edge for the given Setup-Password * @throws OpenemsNamedException on error */ public default Edge addEdgeToUser(User user, String setupPassword) throws OpenemsNamedException { - Optional optEdge = this.getEdgeBySetupPassword(setupPassword); - if (!optEdge.isPresent()) { + var edgeOpt = this.getEdgeBySetupPassword(setupPassword); + if (!edgeOpt.isPresent()) { throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception(); } - Edge edge = optEdge.get(); + var edge = edgeOpt.get(); this.addEdgeToUser(user, edge); return edge; @@ -158,10 +157,10 @@ public default Edge addEdgeToUser(User user, String setupPassword) throws Openem /** * Assigns Edge to current user. - * + * *

* If assignment fails, an OpenemsNamedException is thrown. - * + * * @param user The {@link User} * @param edge The {@link Edge} * @@ -171,7 +170,7 @@ public default Edge addEdgeToUser(User user, String setupPassword) throws Openem /** * Helper method for creating a String of all active State-Channels by Level. - * + * * @param activeStateChannels Map of ChannelAddress and * EdgeConfig.Component.Channel; as returned by * Edge.onSetSumState() @@ -180,11 +179,11 @@ public default Edge addEdgeToUser(User user, String setupPassword) throws Openem public static String activeStateChannelsToString( Map activeStateChannels) { // Sort active State-Channels by Level and Component-ID - HashMap> states = new HashMap<>(); + var states = new HashMap>(); for (Entry entry : activeStateChannels.entrySet()) { ChannelDetail detail = entry.getValue().getDetail(); if (detail instanceof ChannelDetailState) { - Level level = ((ChannelDetailState) detail).getLevel(); + var level = ((ChannelDetailState) detail).getLevel(); HashMultimap channelsByComponent = states.get(level); if (channelsByComponent == null) { channelsByComponent = HashMultimap.create(); @@ -195,15 +194,15 @@ public static String activeStateChannelsToString( entry.getValue()); } } - StringBuilder result = new StringBuilder(); + var result = new StringBuilder(); for (Level level : Level.values()) { - HashMultimap channelsByComponent = states.get(level); + var channelsByComponent = states.get(level); if (channelsByComponent != null) { if (result.length() > 0) { result.append("| "); } result.append(level.name() + ": "); - StringBuilder subResult = new StringBuilder(); + var subResult = new StringBuilder(); for (Entry> entry : channelsByComponent.asMap().entrySet()) { if (subResult.length() > 0) { subResult.append("; "); @@ -213,9 +212,8 @@ public static String activeStateChannelsToString( .map(channel -> { if (!channel.getText().isEmpty()) { return channel.getText(); - } else { - return channel.getId(); } + return channel.getId(); }) // .collect(Collectors.joining(", "))); } @@ -227,7 +225,7 @@ public static String activeStateChannelsToString( /** * Gets information about the given user {@link User}. - * + * * @param user {@link User} to read information * @return {@link Map} about the user * @throws OpenemsNamedException on error @@ -236,7 +234,7 @@ public static String activeStateChannelsToString( /** * Update the given user {@link User} with new information {@link JsonObject}. - * + * * @param user {@link User} to update * @param jsonObject {@link JsonObject} information about the user * @throws OpenemsNamedException on error @@ -245,7 +243,7 @@ public static String activeStateChannelsToString( /** * Returns the Setup Protocol PDF for the given id. - * + * * @param user {@link User} the current user * @param setupProtocolId the setup protocol id to search * @return the Setup Protocol PDF as a byte array @@ -255,7 +253,7 @@ public static String activeStateChannelsToString( /** * Submit the installation assistant protocol. - * + * * @param user {@link User} the current user * @param jsonObject {@link JsonObject} the setup protocol * @return id of created setup protocol @@ -265,7 +263,7 @@ public static String activeStateChannelsToString( /** * Register a user. - * + * * @param jsonObject {@link JsonObject} that represents an user * @throws OpenemsNamedException on error */ @@ -273,7 +271,7 @@ public static String activeStateChannelsToString( /** * Update language from given user. - * + * * @param user {@link User} the current user * @param language to set language * @throws OpenemsNamedException on error diff --git a/io.openems.backend.common/src/io/openems/backend/common/metadata/User.java b/io.openems.backend.common/src/io/openems/backend/common/metadata/User.java index 9fbee5b8d8d..6b15d66f796 100644 --- a/io.openems.backend.common/src/io/openems/backend/common/metadata/User.java +++ b/io.openems.backend.common/src/io/openems/backend/common/metadata/User.java @@ -4,7 +4,6 @@ import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; -import java.util.Optional; import io.openems.common.exceptions.OpenemsError; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; @@ -33,7 +32,7 @@ public User(String id, String name, String token, Role globalRole, NavigableMap< /** * Gets the login token. - * + * * @return the token */ public String getToken() { @@ -42,23 +41,23 @@ public String getToken() { /** * Gets the user language. - * + * * @return the language */ public String getLanguage() { - return language; + return this.language; } /** * Gets the information whether the Users Role for the given Edge is equal or * more privileged than the given Role. - * + * * @param edgeId the Edge-Id * @param role the compared Role * @return true if the Users Role privileges are equal or higher */ public boolean roleIsAtLeast(String edgeId, Role role) { - Optional thisRoleOpt = this.getRole(edgeId); + var thisRoleOpt = this.getRole(edgeId); if (!thisRoleOpt.isPresent()) { return false; } @@ -68,7 +67,7 @@ public boolean roleIsAtLeast(String edgeId, Role role) { /** * Throws an exception if the current Role is equal or more privileged than the * given Role. - * + * * @param resource a resource identifier; used for the exception * @param edgeId the Edge-ID * @param role the compared Role @@ -76,11 +75,11 @@ public boolean roleIsAtLeast(String edgeId, Role role) { * @throws OpenemsNamedException if the current Role privileges are less */ public Role assertEdgeRoleIsAtLeast(String resource, String edgeId, Role role) throws OpenemsNamedException { - Optional thisRoleOpt = this.getRole(edgeId); + var thisRoleOpt = this.getRole(edgeId); if (!thisRoleOpt.isPresent()) { throw OpenemsError.COMMON_ROLE_UNDEFINED.exception(this.getId()); } - Role thisRole = thisRoleOpt.get(); + var thisRole = thisRoleOpt.get(); if (!thisRole.isAtLeast(role)) { throw OpenemsError.COMMON_ROLE_ACCESS_DENIED.exception(resource, role.toString()); } @@ -89,7 +88,7 @@ public Role assertEdgeRoleIsAtLeast(String resource, String edgeId, Role role) t /** * Gets the Metadata information of the accessible Edges. - * + * * @param user the {@link User} * @param metadataService a {@link Metadata} provider * @return a list of {@link EdgeMetadata} @@ -97,18 +96,18 @@ public Role assertEdgeRoleIsAtLeast(String resource, String edgeId, Role role) t public static List generateEdgeMetadatas(User user, Metadata metadataService) { List metadatas = new ArrayList<>(); for (Entry edgeRole : user.getEdgeRoles().entrySet()) { - String edgeId = edgeRole.getKey(); - Role role = edgeRole.getValue(); - Optional edgeOpt = metadataService.getEdge(edgeId); + var edgeId = edgeRole.getKey(); + var role = edgeRole.getValue(); + var edgeOpt = metadataService.getEdge(edgeId); if (edgeOpt.isPresent()) { - Edge e = edgeOpt.get(); + var edge = edgeOpt.get(); metadatas.add(new EdgeMetadata(// - e.getId(), // Edge-ID - e.getComment(), // Comment - e.getProducttype(), // Product-Type - e.getVersion(), // Version + edge.getId(), // Edge-ID + edge.getComment(), // Comment + edge.getProducttype(), // Product-Type + edge.getVersion(), // Version role, // Role - e.isOnline() // Online-State + edge.isOnline() // Online-State )); } } diff --git a/io.openems.backend.common/src/io/openems/backend/common/timedata/EdgeCache.java b/io.openems.backend.common/src/io/openems/backend/common/timedata/EdgeCache.java index 1507dc88d0f..b2b3d7c6f59 100644 --- a/io.openems.backend.common/src/io/openems/backend/common/timedata/EdgeCache.java +++ b/io.openems.backend.common/src/io/openems/backend/common/timedata/EdgeCache.java @@ -21,19 +21,31 @@ public class EdgeCache { /** * The Timestamp of the data in the Cache. */ - private long cacheTimestamp = 0l; + private long cacheTimestamp = 0L; /** * The Timestamp when the Cache was last applied to the incoming data. */ - private long lastAppliedTimestamp = 0l; + private long lastAppliedTimestamp = 0L; private final HashMap cacheData = new HashMap<>(); - public synchronized final Optional getChannelValue(ChannelAddress address) { + /** + * Gets the channel value from cache. + * + * @param address the {@link ChannelAddress} of the channel + * @return the value; empty if it is not in cache + */ + public final synchronized Optional getChannelValue(ChannelAddress address) { return Optional.ofNullable(this.cacheData.get(address)); } + /** + * Updates the 'incoming data' with the data from the cache. + * + * @param edgeId the Edge-ID + * @param incomingDatas the incoming data + */ public synchronized void complementDataFromCache(String edgeId, SortedMap> incomingDatas) { for (Entry> entry : incomingDatas.entrySet()) { @@ -52,7 +64,7 @@ public synchronized void complementDataFromCache(String edgeId, if (this.cacheTimestamp != 0L) { this.log.info("Edge [" + edgeId + "]: invalidate cache. Incoming [" + Instant.ofEpochMilli(incomingTimestamp) + "]. Cache [" - + Instant.ofEpochMilli(cacheTimestamp) + "]"); + + Instant.ofEpochMilli(this.cacheTimestamp) + "]"); } // Clear Cache this.cacheData.clear(); @@ -66,7 +78,7 @@ public synchronized void complementDataFromCache(String edgeId, // cache is valid (not elder than 5 minutes) this.lastAppliedTimestamp = incomingTimestamp; for (Entry cacheEntry : this.cacheData.entrySet()) { - ChannelAddress channel = cacheEntry.getKey(); + var channel = cacheEntry.getKey(); // check if there is a current value for this timestamp + channel if (!incomingData.containsKey(channel)) { // if not -> add cache data to write data diff --git a/io.openems.backend.common/src/io/openems/backend/common/timedata/Timedata.java b/io.openems.backend.common/src/io/openems/backend/common/timedata/Timedata.java index 201bb8ec071..dc27fa5d687 100644 --- a/io.openems.backend.common/src/io/openems/backend/common/timedata/Timedata.java +++ b/io.openems.backend.common/src/io/openems/backend/common/timedata/Timedata.java @@ -16,20 +16,20 @@ public interface Timedata extends CommonTimedataService { /** * Sends the data points to the Timedata service. - * + * * @param edgeId The unique Edge-ID * @param data Table of timestamp (epoch in milliseconds), Channel-Address and * the Channel value as JsonElement. Sorted by timestamp. - * @throws OpenemsException + * @throws OpenemsException on error */ public void write(String edgeId, TreeBasedTable data) throws OpenemsException; /** * Gets the latest value for the given ChannelAddress. - * + * * @param edgeId The unique Edge-ID * @param channelAddress The Channel-Address - * @return + * @return the value */ public Optional getChannelValue(String edgeId, ChannelAddress channelAddress); diff --git a/io.openems.backend.common/src/io/openems/backend/common/uiwebsocket/UiWebsocket.java b/io.openems.backend.common/src/io/openems/backend/common/uiwebsocket/UiWebsocket.java index fbd75ca8318..8e63b295948 100644 --- a/io.openems.backend.common/src/io/openems/backend/common/uiwebsocket/UiWebsocket.java +++ b/io.openems.backend.common/src/io/openems/backend/common/uiwebsocket/UiWebsocket.java @@ -15,7 +15,7 @@ public interface UiWebsocket { /** * Send a JSON-RPC Request to a UI session via WebSocket and expect a JSON-RPC * Response. - * + * * @param token the UI token * @param request the JsonrpcRequest * @return the JSON-RPC Success Response Future @@ -26,7 +26,7 @@ public CompletableFuture send(String token, JsonrpcReque /** * Send a JSON-RPC Notification to a UI session. - * + * * @param token the UI token * @param notification the JsonrpcNotification * @throws OpenemsNamedException on error @@ -36,7 +36,7 @@ public CompletableFuture send(String token, JsonrpcReque /** * Send a JSON-RPC Notification broadcast to all UI sessions with a given * Edge-ID. - * + * * @param edgeId the Edge-ID * @param notification the JsonrpcNotification * @throws OpenemsNamedException on error diff --git a/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/EdgeRpcRequestHandler.java b/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/EdgeRpcRequestHandler.java index 3e70153dbaf..5e17d13410e 100644 --- a/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/EdgeRpcRequestHandler.java +++ b/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/EdgeRpcRequestHandler.java @@ -11,7 +11,6 @@ import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsError; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; -import io.openems.common.jsonrpc.base.JsonrpcRequest; import io.openems.common.jsonrpc.base.JsonrpcResponseSuccess; import io.openems.common.jsonrpc.request.ComponentJsonApiRequest; import io.openems.common.jsonrpc.request.CreateComponentConfigRequest; @@ -31,7 +30,6 @@ import io.openems.common.jsonrpc.response.QueryHistoricTimeseriesEnergyResponse; import io.openems.common.session.Role; import io.openems.common.types.ChannelAddress; -import io.openems.common.types.EdgeConfig; public class EdgeRpcRequestHandler { @@ -43,7 +41,7 @@ protected EdgeRpcRequestHandler(JsonRpcRequestHandlerImpl parent) { /** * Handles an {@link EdgeRpcRequest}. - * + * * @param user the {@link User} * @param edgeRpcRequest the {@link EdgeRpcRequest} * @param messageId the JSON-RPC Message-ID @@ -52,8 +50,8 @@ protected EdgeRpcRequestHandler(JsonRpcRequestHandlerImpl parent) { */ protected CompletableFuture handleRequest(User user, UUID messageId, EdgeRpcRequest edgeRpcRequest) throws OpenemsNamedException { - String edgeId = edgeRpcRequest.getEdgeId(); - JsonrpcRequest request = edgeRpcRequest.getPayload(); + var edgeId = edgeRpcRequest.getEdgeId(); + var request = edgeRpcRequest.getPayload(); user.assertEdgeRoleIsAtLeast(EdgeRpcRequest.METHOD, edgeRpcRequest.getEdgeId(), Role.GUEST); CompletableFuture resultFuture; @@ -111,7 +109,7 @@ protected CompletableFuture handleRequest(User user, UUID messa } // Wrap reply in EdgeRpcResponse - CompletableFuture result = new CompletableFuture(); + var result = new CompletableFuture(); resultFuture.whenComplete((r, ex) -> { if (ex != null) { result.completeExceptionally(ex); @@ -127,7 +125,7 @@ protected CompletableFuture handleRequest(User user, UUID messa /** * Handles a {@link QueryHistoricTimeseriesDataRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - no specific level required * @param request the {@link QueryHistoricTimeseriesDataRequest} @@ -146,7 +144,7 @@ private CompletableFuture handleQueryHistoricDataRequest /** * Handles a {@link QueryHistoricTimeseriesEnergyRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - no specific level required * @param request the {@link QueryHistoricTimeseriesEnergyRequest} @@ -164,7 +162,7 @@ private CompletableFuture handleQueryHistoricEnergyReque /** * Handles a {@link QueryHistoricTimeseriesEnergyPerPeriodRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - no specific level required * @param request the {@link QueryHistoricTimeseriesEnergyPerPeriodRequest} @@ -185,7 +183,7 @@ private CompletableFuture handleQueryHistoricEnergyPerPe /** * Handles a {@link QueryHistoricTimeseriesExportXlxsRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} * @param request the {@link QueryHistoricTimeseriesExportXlxsRequest} @@ -200,7 +198,7 @@ private CompletableFuture handleQueryHistoricTimeseriesE /** * Handles a {@link GetEdgeConfigRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - no specific level required * @param request the {@link GetEdgeConfigRequest} @@ -209,7 +207,7 @@ private CompletableFuture handleQueryHistoricTimeseriesE */ private CompletableFuture handleGetEdgeConfigRequest(String edgeId, User user, GetEdgeConfigRequest request) throws OpenemsNamedException { - EdgeConfig config = this.parent.metadata.getEdgeOrError(edgeId).getConfig(); + var config = this.parent.metadata.getEdgeOrError(edgeId).getConfig(); // JSON-RPC response return CompletableFuture.completedFuture(new GetEdgeConfigResponse(request.getId(), config)); @@ -217,7 +215,7 @@ private CompletableFuture handleGetEdgeConfigRequest(Str /** * Handles a {@link CreateComponentConfigRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - Installer-level required * @param request the {@link CreateComponentConfigRequest} @@ -233,7 +231,7 @@ private CompletableFuture handleCreateComponentConfigReq /** * Handles a {@link UpdateComponentConfigRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - Installer-level required * @param request the {@link UpdateComponentConfigRequest} @@ -249,7 +247,7 @@ private CompletableFuture handleUpdateComponentConfigReq /** * Handles a {@link DeleteComponentConfigRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - Installer-level required * @param request the {@link DeleteComponentConfigRequest} @@ -265,7 +263,7 @@ private CompletableFuture handleDeleteComponentConfigReq /** * Handles a {@link SetChannelValueRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} * @param request the {@link SetChannelValueRequest} @@ -281,7 +279,7 @@ private CompletableFuture handleSetChannelValueRequest(S /** * Handles a {@link UpdateComponentConfigRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} - Guest-level required * @param componentJsonApiRequest the {@link ComponentJsonApiRequest} diff --git a/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/JsonRpcRequestHandlerImpl.java b/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/JsonRpcRequestHandlerImpl.java index f8d30a68b03..24da43e5438 100644 --- a/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/JsonRpcRequestHandlerImpl.java +++ b/io.openems.backend.core/src/io/openems/backend/core/jsonrpcrequesthandler/JsonRpcRequestHandlerImpl.java @@ -3,7 +3,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -14,7 +13,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonElement; import com.google.gson.JsonNull; import io.openems.backend.common.component.AbstractOpenemsBackendComponent; @@ -25,7 +23,6 @@ import io.openems.backend.common.jsonrpc.response.GetEdgesChannelsValuesResponse; import io.openems.backend.common.jsonrpc.response.GetEdgesStatusResponse; import io.openems.backend.common.jsonrpc.response.GetEdgesStatusResponse.EdgeInfo; -import io.openems.backend.common.metadata.Edge; import io.openems.backend.common.metadata.Metadata; import io.openems.backend.common.metadata.User; import io.openems.backend.common.timedata.Timedata; @@ -66,13 +63,14 @@ public JsonRpcRequestHandlerImpl() { /** * Handles a JSON-RPC Request. - * + * * @param context the Logger context, i.e. the name of the parent source * @param user the {@link User} * @param request the JsonrpcRequest * @return the JSON-RPC Success Response Future * @throws OpenemsNamedException on error */ + @Override public CompletableFuture handleRequest(String context, User user, JsonrpcRequest request) throws OpenemsNamedException { switch (request.getMethod()) { @@ -99,7 +97,7 @@ public CompletableFuture handleRequest(String /** * Handles a {@link GetEdgesStatusRequest}. - * + * * @param user the {@link User} * @param messageId the JSON-RPC Message-ID * @param request the {@link GetEdgesStatusRequest} @@ -110,17 +108,17 @@ private CompletableFuture handleGetStatusOfEdgesRequest( GetEdgesStatusRequest request) throws OpenemsNamedException { Map result = new HashMap<>(); for (Entry entry : user.getEdgeRoles().entrySet()) { - String edgeId = entry.getKey(); + var edgeId = entry.getKey(); // assure read permissions of this User for this Edge. if (!user.roleIsAtLeast(edgeId, Role.GUEST)) { continue; } - Optional edgeOpt = this.metadata.getEdge(edgeId); + var edgeOpt = this.metadata.getEdge(edgeId); if (edgeOpt.isPresent()) { - Edge edge = edgeOpt.get(); - EdgeInfo info = new EdgeInfo(edge.isOnline()); + var edge = edgeOpt.get(); + var info = new EdgeInfo(edge.isOnline()); result.put(edge.getId(), info); } } @@ -129,7 +127,7 @@ private CompletableFuture handleGetStatusOfEdgesRequest( /** * Handles a {@link GetEdgesChannelsValuesRequest}. - * + * * @param user the {@link User} * @param messageId the JSON-RPC Message-ID * @param request the GetChannelsValuesRequest @@ -138,7 +136,7 @@ private CompletableFuture handleGetStatusOfEdgesRequest( */ private CompletableFuture handleGetChannelsValuesRequest(User user, UUID messageId, GetEdgesChannelsValuesRequest request) throws OpenemsNamedException { - GetEdgesChannelsValuesResponse response = new GetEdgesChannelsValuesResponse(messageId); + var response = new GetEdgesChannelsValuesResponse(messageId); for (String edgeId : request.getEdgeIds()) { // assure read permissions of this User for this Edge. if (!user.roleIsAtLeast(edgeId, Role.GUEST)) { @@ -146,7 +144,7 @@ private CompletableFuture handleGetChannelsValue } for (ChannelAddress channel : request.getChannels()) { - Optional value = this.timeData.getChannelValue(edgeId, channel); + var value = this.timeData.getChannelValue(edgeId, channel); response.addValue(edgeId, channel, value.orElse(JsonNull.INSTANCE)); } } @@ -155,7 +153,7 @@ private CompletableFuture handleGetChannelsValue /** * Handles a {@link SetGridConnScheduleRequest}. - * + * * @param user the {@link User} * @param messageId the JSON-RPC Message-ID * @param setGridConnScheduleRequest the {@link SetGridConnScheduleRequest} @@ -164,17 +162,17 @@ private CompletableFuture handleGetChannelsValue */ private CompletableFuture handleSetGridConnScheduleRequest(User user, UUID messageId, SetGridConnScheduleRequest setGridConnScheduleRequest) throws OpenemsNamedException { - String edgeId = setGridConnScheduleRequest.getEdgeId(); + var edgeId = setGridConnScheduleRequest.getEdgeId(); user.assertEdgeRoleIsAtLeast(SetGridConnScheduleRequest.METHOD, edgeId, Role.ADMIN); // wrap original request inside ComponentJsonApiRequest - String componentId = "ctrlBalancingSchedule0"; // TODO find dynamic Component-ID of BalancingScheduleController - ComponentJsonApiRequest request = new ComponentJsonApiRequest(componentId, setGridConnScheduleRequest); + var componentId = "ctrlBalancingSchedule0"; // TODO find dynamic Component-ID of BalancingScheduleController + var request = new ComponentJsonApiRequest(componentId, setGridConnScheduleRequest); - CompletableFuture resultFuture = this.edgeWebsocket.send(edgeId, user, request); + var resultFuture = this.edgeWebsocket.send(edgeId, user, request); // Wrap reply in GenericJsonrpcResponseSuccess - CompletableFuture result = new CompletableFuture(); + var result = new CompletableFuture(); resultFuture.whenComplete((r, ex) -> { if (ex != null) { result.completeExceptionally(ex); @@ -190,7 +188,7 @@ private CompletableFuture handleSetGridConnSchedu /** * Log an info message including the Handler name. - * + * * @param context the Logger context, i.e. the name of the parent source * @param message the Info-message */ @@ -200,7 +198,7 @@ protected void logInfo(String context, String message) { /** * Log a warn message including the Handler name. - * + * * @param context the Logger context, i.e. the name of the parent source * @param message the Warn-message */ @@ -210,7 +208,7 @@ protected void logWarn(String context, String message) { /** * Log an error message including the Handler name. - * + * * @param context the Logger context, i.e. the name of the parent source * @param message the Error-message */ diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/EdgeWebsocketImpl.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/EdgeWebsocketImpl.java index 4deb9893861..47cf565ddfc 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/EdgeWebsocketImpl.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/EdgeWebsocketImpl.java @@ -1,6 +1,5 @@ package io.openems.backend.edgewebsocket; -import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.java_websocket.WebSocket; @@ -62,24 +61,24 @@ public EdgeWebsocketImpl() { private Config config; private final Runnable startServerWhenMetadataIsInitialized = () -> { - this.startServer(config.port(), config.poolSize(), config.debugMode()); + this.startServer(this.config.port(), this.config.poolSize(), this.config.debugMode()); }; @Activate - void activate(Config config) { + private void activate(Config config) { this.config = config; this.metadata.addOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); } @Deactivate - void deactivate() { + private void deactivate() { this.metadata.removeOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); this.stopServer(); } /** * Create and start new server. - * + * * @param port the port * @param poolSize number of threads dedicated to handle the tasks * @param debugMode activate a regular debug log about the state of the tasks @@ -100,7 +99,7 @@ private synchronized void stopServer() { /** * Gets whether the Websocket for this Edge is connected. - * + * * @param edgeId the Edge-ID * @return true if it is online */ @@ -111,40 +110,39 @@ protected boolean isOnline(String edgeId) { @Override public CompletableFuture send(String edgeId, User user, JsonrpcRequest request) throws OpenemsNamedException { - WebSocket ws = this.getWebSocketForEdgeId(edgeId); - if (ws != null) { - WsData wsData = ws.getAttachment(); - // Wrap Request in AuthenticatedRpc - AuthenticatedRpcRequest authenticatedRpc = new AuthenticatedRpcRequest(edgeId, user, request); - CompletableFuture responseFuture = wsData.send(authenticatedRpc); - - // Unwrap Response - CompletableFuture result = new CompletableFuture(); - responseFuture.whenComplete((r, ex) -> { - if (ex != null) { - result.completeExceptionally(ex); - } else if (r != null) { - try { - AuthenticatedRpcResponse response = AuthenticatedRpcResponse.from(r); - result.complete(response.getPayload()); - } catch (OpenemsNamedException e) { - this.logError(this.log, e.getMessage()); - result.completeExceptionally(e); - } - } else { - result.completeExceptionally( - new OpenemsNamedException(OpenemsError.JSONRPC_UNHANDLED_METHOD, request.getMethod())); - } - }); - return result; - } else { + var ws = this.getWebSocketForEdgeId(edgeId); + if (ws == null) { throw OpenemsError.BACKEND_EDGE_NOT_CONNECTED.exception(edgeId); } + WsData wsData = ws.getAttachment(); + // Wrap Request in AuthenticatedRpc + var authenticatedRpc = new AuthenticatedRpcRequest<>(edgeId, user, request); + var responseFuture = wsData.send(authenticatedRpc); + + // Unwrap Response + var result = new CompletableFuture(); + responseFuture.whenComplete((r, ex) -> { + if (ex != null) { + result.completeExceptionally(ex); + } else if (r != null) { + try { + var response = AuthenticatedRpcResponse.from(r); + result.complete(response.getPayload()); + } catch (OpenemsNamedException e) { + this.logError(this.log, e.getMessage()); + result.completeExceptionally(e); + } + } else { + result.completeExceptionally( + new OpenemsNamedException(OpenemsError.JSONRPC_UNHANDLED_METHOD, request.getMethod())); + } + }); + return result; } @Override public void send(String edgeId, JsonrpcNotification notification) throws OpenemsException { - WebSocket ws = this.getWebSocketForEdgeId(edgeId); + var ws = this.getWebSocketForEdgeId(edgeId); if (ws != null) { WsData wsData = ws.getAttachment(); wsData.send(notification); @@ -154,15 +152,15 @@ public void send(String edgeId, JsonrpcNotification notification) throws Openems /** * Gets the WebSocket connection for an Edge-ID. If more than one connection * exists, the first one is returned. Returns null if none is found. - * + * * @param edgeId the Edge-ID * @return the WebSocket connection */ private final WebSocket getWebSocketForEdgeId(String edgeId) { for (WebSocket ws : this.server.getConnections()) { WsData wsData = ws.getAttachment(); - Optional wsEdgeId = wsData.getEdgeId(); - if (wsEdgeId.isPresent() && wsEdgeId.get().equals(edgeId)) { + var wsEdgeIdOpt = wsData.getEdgeId(); + if (wsEdgeIdOpt.isPresent() && wsEdgeIdOpt.get().equals(edgeId)) { return ws; } } @@ -188,7 +186,7 @@ public CompletableFuture handleSubscribeSystemLogRequest /** * Handles a {@link SystemLogNotification}, i.e. the replies to * {@link SubscribeSystemLogRequest}. - * + * * @param edgeId the Edge-ID * @param notification the SystemLogNotification */ diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnClose.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnClose.java index c181a15bb58..450af63c330 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnClose.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnClose.java @@ -1,13 +1,10 @@ package io.openems.backend.edgewebsocket; -import java.util.Optional; - import org.java_websocket.WebSocket; import org.java_websocket.framing.CloseFrame; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.openems.backend.common.metadata.Edge; import io.openems.common.exceptions.OpenemsException; public class OnClose implements io.openems.common.websocket.OnClose { @@ -23,15 +20,15 @@ public OnClose(EdgeWebsocketImpl parent) { public void run(WebSocket ws, int code, String reason, boolean remote) throws OpenemsException { // get edgeId from websocket WsData wsData = ws.getAttachment(); - Optional edgeIdOpt = wsData.getEdgeId(); + var edgeIdOpt = wsData.getEdgeId(); String edgeId; if (edgeIdOpt.isPresent()) { edgeId = edgeIdOpt.get(); - Optional edgeOpt = this.parent.metadata.getEdge(edgeId); + var edgeOpt = this.parent.metadata.getEdge(edgeId); // if there is no other websocket connection for this edgeId -> announce Edge as // offline if (edgeOpt.isPresent()) { - boolean isOnline = this.parent.isOnline(edgeId); + var isOnline = this.parent.isOnline(edgeId); edgeOpt.get().setOnline(isOnline); } diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnError.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnError.java index 94dbde7cb91..16fad99467b 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnError.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnError.java @@ -1,7 +1,5 @@ package io.openems.backend.edgewebsocket; -import java.util.Optional; - import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -16,13 +14,13 @@ public class OnError implements io.openems.common.websocket.OnError { public OnError(EdgeWebsocketImpl parent) { this.parent = parent; } - + @Override public void run(WebSocket ws, Exception ex) throws OpenemsException { WsData wsData = ws.getAttachment(); - Optional edgeId = wsData.getEdgeId(); - this.parent.logWarn(this.log, "Edge [" + edgeId.orElse("UNKNOWN") + "] websocket error. " + ex.getClass().getSimpleName() + ": " - + ex.getMessage()); + var edgeIdOpt = wsData.getEdgeId(); + this.parent.logWarn(this.log, "Edge [" + edgeIdOpt.orElse("UNKNOWN") + "] websocket error. " + + ex.getClass().getSimpleName() + ": " + ex.getMessage()); ex.printStackTrace(); } diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnNotification.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnNotification.java index eaa7dcb7a1c..8029c340b88 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnNotification.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnNotification.java @@ -1,7 +1,6 @@ package io.openems.backend.edgewebsocket; import java.util.Map.Entry; -import java.util.Optional; import java.util.concurrent.TimeUnit; import org.java_websocket.WebSocket; @@ -9,9 +8,7 @@ import org.slf4j.LoggerFactory; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import io.openems.backend.common.metadata.Edge; import io.openems.common.channel.Level; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsException; @@ -44,9 +41,9 @@ public void run(WebSocket ws, JsonrpcNotification notification) throws OpenemsNa } // announce incoming message for this Edge - Optional edge = wsData.getEdge(this.parent.metadata); - if (edge.isPresent()) { - edge.get().setLastMessageTimestamp(); + var edgeOpt = wsData.getEdge(this.parent.metadata); + if (edgeOpt.isPresent()) { + edgeOpt.get().setLastMessageTimestamp(); } // Handle notification @@ -69,16 +66,16 @@ public void run(WebSocket ws, JsonrpcNotification notification) throws OpenemsNa /** * Handles EdgeConfigNotification. - * + * * @param message the EdgeConfigNotification * @param wsData the WebSocket attachment * @throws OpenemsException on error */ private void handleEdgeConfigNotification(EdgeConfigNotification message, WsData wsData) throws OpenemsException { - String edgeId = wsData.assertEdgeId(message); + var edgeId = wsData.assertEdgeId(message); // save config in metadata - Edge edge = this.parent.metadata.getEdgeOrError(edgeId); + var edge = this.parent.metadata.getEdgeOrError(edgeId); edge.setConfig(message.getConfig()); // forward @@ -94,14 +91,14 @@ private void handleEdgeConfigNotification(EdgeConfigNotification message, WsData /** * Handles TimestampedDataNotification. - * + * * @param message the TimestampedDataNotification * @param wsData the WebSocket attachment * @throws OpenemsNamedException on error */ private void handleTimestampedDataNotification(TimestampedDataNotification message, WsData wsData) throws OpenemsNamedException { - String edgeId = wsData.assertEdgeId(message); + var edgeId = wsData.assertEdgeId(message); try { this.parent.timedata.write(edgeId, message.getData()); @@ -110,9 +107,9 @@ private void handleTimestampedDataNotification(TimestampedDataNotification messa } // Read some specific channels - Edge edge = this.parent.metadata.getEdgeOrError(edgeId); + var edge = this.parent.metadata.getEdgeOrError(edgeId); for (Entry entry : message.getParams().entrySet()) { - JsonObject data = JsonUtils.getAsJsonObject(entry.getValue()); + var data = JsonUtils.getAsJsonObject(entry.getValue()); // set Edge last update timestamp only for those channels for (String channel : data.keySet()) { if (channel.endsWith("ActivePower") @@ -129,7 +126,7 @@ private void handleTimestampedDataNotification(TimestampedDataNotification messa } if (data.has("_meta/Version") && data.get("_meta/Version").isJsonPrimitive()) { - String version = JsonUtils.getAsPrimitive(data, "_meta/Version").getAsString(); + var version = JsonUtils.getAsPrimitive(data, "_meta/Version").getAsString(); edge.setVersion(SemanticVersion.fromString(version)); } @@ -138,14 +135,14 @@ private void handleTimestampedDataNotification(TimestampedDataNotification messa /** * Handles SystemLogNotification. - * + * * @param message the SystemLogNotification * @param wsData the WebSocket attachment * @throws OpenemsNamedException on error */ private void handleSystemLogNotification(SystemLogNotification message, WsData wsData) throws OpenemsNamedException { - String edgeId = wsData.assertEdgeId(message); + var edgeId = wsData.assertEdgeId(message); this.parent.handleSystemLogNotification(edgeId, message); } } diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnOpen.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnOpen.java index 4fc2050a117..0d2b120b0bd 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnOpen.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnOpen.java @@ -1,7 +1,5 @@ package io.openems.backend.edgewebsocket; -import java.util.Optional; - import org.java_websocket.WebSocket; import org.java_websocket.framing.CloseFrame; import org.slf4j.Logger; @@ -9,7 +7,6 @@ import com.google.gson.JsonObject; -import io.openems.backend.common.metadata.Edge; import io.openems.common.exceptions.OpenemsException; import io.openems.common.utils.JsonUtils; @@ -30,7 +27,7 @@ public void run(WebSocket ws, JsonObject handshake) { String apikey = ""; try { // get apikey from handshake - Optional apikeyOpt = JsonUtils.getAsOptionalString(handshake, "apikey"); + var apikeyOpt = JsonUtils.getAsOptionalString(handshake, "apikey"); if (!apikeyOpt.isPresent()) { throw new OpenemsException("Apikey is missing in handshake"); } @@ -38,19 +35,19 @@ public void run(WebSocket ws, JsonObject handshake) { wsData.setApikey(apikey); // get edgeId for apikey - Optional edgeIdOpt = this.parent.metadata.getEdgeIdForApikey(apikey); + var edgeIdOpt = this.parent.metadata.getEdgeIdForApikey(apikey); if (!edgeIdOpt.isPresent()) { throw new OpenemsException("Unable to authenticate this Apikey."); } - String edgeId = edgeIdOpt.get(); + var edgeId = edgeIdOpt.get(); wsData.setEdgeId(edgeId); // get metadata for Edge - Optional edgeOpt = this.parent.metadata.getEdge(edgeId); + var edgeOpt = this.parent.metadata.getEdge(edgeId); if (!edgeOpt.isPresent()) { throw new OpenemsException("Unable to get metadata for Edge [" + edgeId + "]"); } - Edge edge = edgeOpt.get(); + var edge = edgeOpt.get(); // log this.parent.logInfo(this.log, "Edge [" + edge.getId() + "] connected."); diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnRequest.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnRequest.java index f6a5251f0e5..100f9362a8f 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnRequest.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/OnRequest.java @@ -6,8 +6,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsError; +import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsException; import io.openems.common.jsonrpc.base.JsonrpcRequest; import io.openems.common.jsonrpc.base.JsonrpcResponseSuccess; diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/SystemLogHandler.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/SystemLogHandler.java index 5734f1fa1cb..3ccf65b9bfd 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/SystemLogHandler.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/SystemLogHandler.java @@ -1,7 +1,6 @@ package io.openems.backend.edgewebsocket; import java.util.Collection; -import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; @@ -10,7 +9,6 @@ import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; -import io.openems.backend.common.metadata.Edge; import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.jsonrpc.base.DeprecatedJsonrpcNotification; @@ -38,7 +36,7 @@ public SystemLogHandler(EdgeWebsocketImpl parent) { /** * Handles a {@link SubscribeSystemLogRequest}. - * + * * @param edgeId the Edge-ID * @param user the {@link User} * @param token the UI session token @@ -119,7 +117,7 @@ public void handleSystemLogNotification(String edgeId, User user, SystemLogNotif /** * Unsubscribe from System-Log. - * + * * @param edgeId the Edge-ID# * @param user the {@link User}; possibly null * @param token the UI token @@ -134,15 +132,14 @@ private void unsubscribe(String edgeId, User user, String token) { if (isAnySubscriptionForThisEdgeLeft) { return; + } - } else { - // send unsubscribe to Edge - try { - this.parent.send(edgeId, user, SubscribeSystemLogRequest.unsubscribe()); - } catch (OpenemsNamedException e) { - this.log.error("Unable to Unsubscribe from Edge [" + edgeId + "]"); - e.printStackTrace(); - } + // send unsubscribe to Edge + try { + this.parent.send(edgeId, user, SubscribeSystemLogRequest.unsubscribe()); + } catch (OpenemsNamedException e) { + this.log.error("Unable to Unsubscribe from Edge [" + edgeId + "]"); + e.printStackTrace(); } } @@ -150,9 +147,9 @@ private void unsubscribe(String edgeId, User user, String token) { private CompletableFuture sendSubscribe(String edgeId, User user, SubscribeSystemLogRequest request, boolean subscribe) throws OpenemsNamedException { // handling deprecated: remove after full migration - Optional edge = this.parent.metadata.getEdge(edgeId); - if (edge.isPresent()) { - if (!edge.get().getVersion().isAtLeast(new SemanticVersion(2018, 11, 0))) { + var edgeOpt = this.parent.metadata.getEdge(edgeId); + if (edgeOpt.isPresent()) { + if (!edgeOpt.get().getVersion().isAtLeast(new SemanticVersion(2018, 11, 0))) { this.parent.send(edgeId, new DeprecatedJsonrpcNotification(JsonUtils.buildJsonObject() // .add("messageId", JsonUtils.buildJsonObject() // .addProperty("ui", request.getId().toString()) // diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WebsocketServer.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WebsocketServer.java index e1f6e3830a5..67811fc1b52 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WebsocketServer.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WebsocketServer.java @@ -14,7 +14,6 @@ import org.slf4j.LoggerFactory; import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsException; @@ -51,10 +50,15 @@ public WebsocketServer(EdgeWebsocketImpl parent, String name, int port, int pool @Override protected WsData createWsData() { - WsData wsData = new WsData(this); - return wsData; + return new WsData(this); } + /** + * Is the given Edge online?. + * + * @param edgeId the Edge-ID + * @return true if it is online. + */ public boolean isOnline(String edgeId) { final Optional edgeIdOpt = Optional.of(edgeId); return this.getConnections().parallelStream().anyMatch( @@ -73,7 +77,7 @@ protected OnRequest getOnRequest() { @Override public OnNotification getOnNotification() { - return onNotification; + return this.onNotification; } @Override @@ -89,24 +93,24 @@ protected OnClose getOnClose() { @Override protected JsonrpcMessage handleNonJsonrpcMessage(String stringMessage, OpenemsNamedException lastException) throws OpenemsNamedException { - JsonObject message = JsonUtils.parseToJsonObject(stringMessage); + var message = JsonUtils.parseToJsonObject(stringMessage); // config if (message.has("config")) { - EdgeConfig config = EdgeConfig.fromJson(JsonUtils.getAsJsonObject(message, "config")); + var config = EdgeConfig.fromJson(JsonUtils.getAsJsonObject(message, "config")); return new EdgeConfigNotification(config); } // timedata if (message.has("timedata")) { - TimestampedDataNotification d = new TimestampedDataNotification(); - JsonObject timedata = JsonUtils.getAsJsonObject(message, "timedata"); + var d = new TimestampedDataNotification(); + var timedata = JsonUtils.getAsJsonObject(message, "timedata"); for (Entry entry : timedata.entrySet()) { - long timestamp = Long.valueOf(entry.getKey()); - JsonObject values = JsonUtils.getAsJsonObject(entry.getValue()); + var timestamp = Long.parseLong(entry.getKey()); + var values = JsonUtils.getAsJsonObject(entry.getValue()); Map data = new HashMap<>(); for (Entry value : values.entrySet()) { - ChannelAddress address = ChannelAddress.fromString(value.getKey()); + var address = ChannelAddress.fromString(value.getKey()); data.put(address, value.getValue()); } d.add(timestamp, data); @@ -116,7 +120,7 @@ protected JsonrpcMessage handleNonJsonrpcMessage(String stringMessage, OpenemsNa // log if (message.has("log")) { - JsonObject log = JsonUtils.getAsJsonObject(message, "log"); + var log = JsonUtils.getAsJsonObject(message, "log"); return new SystemLogNotification(new SystemLog( ZonedDateTime.ofInstant(Instant.ofEpochMilli(JsonUtils.getAsLong(log, "time")), ZoneId.systemDefault()), // @@ -125,7 +129,7 @@ protected JsonrpcMessage handleNonJsonrpcMessage(String stringMessage, OpenemsNa JsonUtils.getAsString(log, "message"))); } - log.info("EdgeWs. handleNonJsonrpcMessage: " + stringMessage); + this.log.info("EdgeWs. handleNonJsonrpcMessage: " + stringMessage); throw new OpenemsException("EdgeWs. handleNonJsonrpcMessage", lastException); } diff --git a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WsData.java b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WsData.java index f4ccce727c0..7fa48cdbb15 100644 --- a/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WsData.java +++ b/io.openems.backend.edgewebsocket/src/io/openems/backend/edgewebsocket/WsData.java @@ -9,6 +9,7 @@ import io.openems.backend.common.metadata.Edge; import io.openems.backend.common.metadata.Metadata; +import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsException; import io.openems.common.jsonrpc.base.JsonrpcMessage; import io.openems.common.utils.StringUtils; @@ -16,7 +17,7 @@ public class WsData extends io.openems.common.websocket.WsData { private final WebsocketServer parent; - private CompletableFuture isAuthenticated = new CompletableFuture(); + private final CompletableFuture isAuthenticated = new CompletableFuture<>(); private Optional apikey = Optional.empty(); private Optional edgeId = Optional.empty(); @@ -32,6 +33,14 @@ public CompletableFuture isAuthenticated() { return this.isAuthenticated; } + /** + * Asserts that the User is authenticated within a timeout. + * + * @param message a identification message on error + * @param timeout the timeout length + * @param unit the {@link TimeUnit} of the timeout + * @throws OpenemsNamedException on error + */ public void assertAuthenticatedWithTimeout(JsonrpcMessage message, long timeout, TimeUnit unit) throws OpenemsException { try { @@ -53,7 +62,7 @@ public synchronized void setApikey(String apikey) { } public synchronized Optional getApikey() { - return apikey; + return this.apikey; } public synchronized void setEdgeId(String edgeId) { @@ -61,43 +70,50 @@ public synchronized void setEdgeId(String edgeId) { } public synchronized Optional getEdgeId() { - return edgeId; + return this.edgeId; } /** * Gets the Edge. - * + * * @param metadata the Metadata service * @return the Edge or Optional.Empty if the Edge-ID was not set or it is not * available from Metadata service */ public synchronized Optional getEdge(Metadata metadata) { - Optional edgeId = this.getEdgeId(); + var edgeId = this.getEdgeId(); if (edgeId.isPresent()) { - Optional edge = metadata.getEdge(edgeId.get()); - return edge; + return metadata.getEdge(edgeId.get()); } return Optional.empty(); } + /** + * Asserts that the Edge-ID is present. + * + * @param message a identification message on error + * @return the Edge-ID + * @throws OpenemsException on error + */ public String assertEdgeId(JsonrpcMessage message) throws OpenemsException { if (this.edgeId.isPresent()) { return this.edgeId.get(); - } else { - throw new OpenemsException( - "EdgeId is not set. Unable to handle " + StringUtils.toShortString(message.toString(), 100)); } + throw new OpenemsException( + "EdgeId is not set. Unable to handle " + StringUtils.toShortString(message.toString(), 100)); } @Override public String toString() { - return "EdgeWebsocket.WsData [apikey=" + apikey.orElse("UNKNOWN") + ", edgeId=" + edgeId.orElse("UNKNOWN") + return "EdgeWebsocket.WsData [" // + + "apikey=" + this.apikey.orElse("UNKNOWN") + ", " // + + "edgeId=" + this.edgeId.orElse("UNKNOWN") // + "]"; } /** * Gets an Id of this Edge - either the Edge-ID or the Apikey or "UNKNOWN". - * + * * @return the Id */ private String getId() { diff --git a/io.openems.backend.metadata.dummy/src/io/openems/backend/metadata/dummy/DummyMetadata.java b/io.openems.backend.metadata.dummy/src/io/openems/backend/metadata/dummy/DummyMetadata.java index 827139ae300..d01679b0c18 100644 --- a/io.openems.backend.metadata.dummy/src/io/openems/backend/metadata/dummy/DummyMetadata.java +++ b/io.openems.backend.metadata.dummy/src/io/openems/backend/metadata/dummy/DummyMetadata.java @@ -8,7 +8,6 @@ import java.util.TreeMap; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Matcher; import java.util.regex.Pattern; import org.osgi.service.component.annotations.Activate; @@ -61,24 +60,24 @@ public DummyMetadata() { } @Activate - void activate() { + private void activate() { this.logInfo(this.log, "Activate"); } @Deactivate - void deactivate() { + private void deactivate() { this.logInfo(this.log, "Deactivate"); } @Override public User authenticate(String username, String password) throws OpenemsNamedException { - String name = "User #" + this.nextUserId.incrementAndGet(); - String token = UUID.randomUUID().toString(); - TreeMap roles = new TreeMap<>(); + var name = "User #" + this.nextUserId.incrementAndGet(); + var token = UUID.randomUUID().toString(); + var roles = new TreeMap(); for (String edgeId : this.edges.keySet()) { roles.put(edgeId, Role.ADMIN); } - User user = new User(username, name, token, Role.ADMIN, roles, this.defaultLanguage.name()); + var user = new User(username, name, token, Role.ADMIN, roles, this.defaultLanguage.name()); this.users.put(user.getId(), user); return user; } @@ -100,28 +99,27 @@ public void logout(User user) { @Override public Optional getEdgeIdForApikey(String apikey) { - Optional edgeOpt = this.edges.values().stream() // + var edgeOpt = this.edges.values().stream() // .filter(edge -> apikey.equals(edge.getApikey())) // .findFirst(); if (edgeOpt.isPresent()) { return Optional.ofNullable(edgeOpt.get().getId()); } // not found. Is apikey a valid Edge-ID? - Optional idOpt = DummyMetadata.parseNumberFromName(apikey); + var idOpt = DummyMetadata.parseNumberFromName(apikey); int id; String edgeId; String setupPassword; if (idOpt.isPresent()) { edgeId = apikey; id = idOpt.get(); - setupPassword = edgeId; } else { // create new ID id = this.nextEdgeId.incrementAndGet(); edgeId = "edge" + id; - setupPassword = edgeId; } - MyEdge edge = new MyEdge(edgeId, apikey, setupPassword, "OpenEMS Edge #" + id, State.ACTIVE, "", "", Level.OK, + setupPassword = edgeId; + var edge = new MyEdge(edgeId, apikey, setupPassword, "OpenEMS Edge #" + id, State.ACTIVE, "", "", Level.OK, new EdgeConfig()); edge.onSetConfig(config -> { this.logInfo(this.log, "Edge [" + edgeId + "]. Update config: " @@ -134,11 +132,11 @@ public Optional getEdgeIdForApikey(String apikey) { @Override public Optional getEdgeBySetupPassword(String setupPassword) { - Optional optEdge = this.edges.values().stream() - .filter(edge -> edge.getSetupPassword().equals(setupPassword)).findFirst(); + var edgeOpt = this.edges.values().stream().filter(edge -> edge.getSetupPassword().equals(setupPassword)) + .findFirst(); - if (optEdge.isPresent()) { - MyEdge edge = optEdge.get(); + if (edgeOpt.isPresent()) { + var edge = edgeOpt.get(); return Optional.of(edge); } @@ -163,9 +161,9 @@ public Collection getAllEdges() { private static Optional parseNumberFromName(String name) { try { - Matcher matcher = NAME_NUMBER_PATTERN.matcher(name); + var matcher = DummyMetadata.NAME_NUMBER_PATTERN.matcher(name); if (matcher.find()) { - String nameNumberString = matcher.group(1); + var nameNumberString = matcher.group(1); return Optional.ofNullable(Integer.parseInt(nameNumberString)); } } catch (NullPointerException e) { diff --git a/io.openems.backend.metadata.file/src/io/openems/backend/metadata/file/FileMetadata.java b/io.openems.backend.metadata.file/src/io/openems/backend/metadata/file/FileMetadata.java index e6b669615e0..c10a63469d1 100644 --- a/io.openems.backend.metadata.file/src/io/openems/backend/metadata/file/FileMetadata.java +++ b/io.openems.backend.metadata.file/src/io/openems/backend/metadata/file/FileMetadata.java @@ -43,18 +43,18 @@ /** * This implementation of MetadataService reads Edges configuration from a file. * The layout of the file is as follows: - * + * *

  * {
  *   edges: {
  *     [edgeId: string]: {
  *       comment: string,
  *       apikey: string
- *     } 
+ *     }
  *   }
  * }
  * 
- * + * *

* This implementation does not require any login. It always serves the same * user, which has 'ADMIN'-permissions on all given Edges. @@ -83,7 +83,7 @@ public FileMetadata() { } @Activate - void activate(Config config) { + private void activate(Config config) { this.log.info("Activate [path=" + config.path() + "]"); this.path = config.path(); @@ -94,7 +94,7 @@ void activate(Config config) { } @Deactivate - void deactivate() { + private void deactivate() { this.logInfo(this.log, "Deactivate"); } @@ -120,7 +120,7 @@ public void logout(User user) { public synchronized Optional getEdgeIdForApikey(String apikey) { this.refreshData(); for (Entry entry : this.edges.entrySet()) { - MyEdge edge = entry.getValue(); + var edge = entry.getValue(); if (edge.getApikey().equals(apikey)) { return Optional.of(edge.getId()); } @@ -160,9 +160,9 @@ public synchronized Collection getAllEdges() { private synchronized void refreshData() { if (this.edges.isEmpty()) { // read file - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); String line = null; - try (BufferedReader br = new BufferedReader(new FileReader(this.path))) { + try (var br = new BufferedReader(new FileReader(this.path))) { while ((line = br.readLine()) != null) { sb.append(line); } @@ -209,7 +209,7 @@ private synchronized void refreshData() { private static User generateUser() { return new User(FileMetadata.USER_ID, FileMetadata.USER_NAME, UUID.randomUUID().toString(), - FileMetadata.USER_GLOBAL_ROLE, new TreeMap<>(), LANGUAGE.name()); + FileMetadata.USER_GLOBAL_ROLE, new TreeMap<>(), FileMetadata.LANGUAGE.name()); } @Override @@ -244,7 +244,7 @@ public void registerUser(JsonObject jsonObject) throws OpenemsNamedException { @Override public void updateUserLanguage(User user, Language locale) throws OpenemsNamedException { - LANGUAGE = locale; + FileMetadata.LANGUAGE = locale; } } diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/EdgeCache.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/EdgeCache.java index 04efee92e20..821d8517972 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/EdgeCache.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/EdgeCache.java @@ -15,7 +15,6 @@ import io.openems.backend.metadata.odoo.Field.EdgeDevice; import io.openems.backend.metadata.odoo.odoo.FieldValue; import io.openems.backend.metadata.odoo.postgres.PgUtils; -import io.openems.backend.metadata.odoo.postgres.QueueWriteWorker; import io.openems.backend.metadata.odoo.postgres.task.InsertEdgeConfigUpdate; import io.openems.backend.metadata.odoo.postgres.task.UpdateEdgeConfig; import io.openems.backend.metadata.odoo.postgres.task.UpdateEdgeProducttype; @@ -37,17 +36,17 @@ public class EdgeCache { /** * Map Edge-ID (String) to Edge. */ - private Map edgeIdToEdge = new HashMap<>(); + private final Map edgeIdToEdge = new HashMap<>(); /** * Map Odoo-ID (Integer) to Edge-ID (String). */ - private Map odooIdToEdgeId = new HashMap<>(); + private final Map odooIdToEdgeId = new HashMap<>(); /** * Map Apikey (String) to Edge-ID (String). */ - private Map apikeyToEdgeId = new HashMap<>(); + private final Map apikeyToEdgeId = new HashMap<>(); public EdgeCache(OdooMetadata parent) { this.parent = parent; @@ -55,7 +54,7 @@ public EdgeCache(OdooMetadata parent) { /** * Adds a Edge or Updates an existing Edge from a SQL ResultSet. - * + * * @param rs the ResultSet record * @return the new or updated Edge instance * @throws SQLException on error @@ -63,13 +62,13 @@ public EdgeCache(OdooMetadata parent) { */ public synchronized MyEdge addOrUpate(ResultSet rs) throws SQLException, OpenemsException { // simple fields - String edgeId = PgUtils.getAsString(rs, EdgeDevice.NAME); - int odooId = PgUtils.getAsInt(rs, EdgeDevice.ID); - String apikey = PgUtils.getAsString(rs, EdgeDevice.APIKEY); + var edgeId = PgUtils.getAsString(rs, EdgeDevice.NAME); + var odooId = PgUtils.getAsInt(rs, EdgeDevice.ID); + var apikey = PgUtils.getAsString(rs, EdgeDevice.APIKEY); // Config EdgeConfig config; - String configString = PgUtils.getAsStringOrElse(rs, EdgeDevice.OPENEMS_CONFIG, ""); + var configString = PgUtils.getAsStringOrElse(rs, EdgeDevice.OPENEMS_CONFIG, ""); if (configString.isEmpty()) { config = new EdgeConfig(); } else { @@ -85,10 +84,10 @@ public synchronized MyEdge addOrUpate(ResultSet rs) throws SQLException, Openems } // State - String stateString = PgUtils.getAsStringOrElse(rs, EdgeDevice.STATE, State.INACTIVE.name()); + var stateString = PgUtils.getAsStringOrElse(rs, EdgeDevice.STATE, State.INACTIVE.name()); State state; try { - state = State.valueOf(stateString.toUpperCase().replaceAll("-", "_")); + state = State.valueOf(stateString.toUpperCase().replace('-', '_')); } catch (IllegalArgumentException e) { this.parent.logWarn(this.log, "Edge [" + edgeId + "]. Unable to get State from [" + stateString + "]: " + e.getMessage()); @@ -96,13 +95,13 @@ public synchronized MyEdge addOrUpate(ResultSet rs) throws SQLException, Openems } // more simple fields - String comment = PgUtils.getAsStringOrElse(rs, EdgeDevice.COMMENT, ""); - String version = PgUtils.getAsStringOrElse(rs, EdgeDevice.OPENEMS_VERSION, ""); - String productType = PgUtils.getAsStringOrElse(rs, EdgeDevice.PRODUCT_TYPE, ""); + var comment = PgUtils.getAsStringOrElse(rs, EdgeDevice.COMMENT, ""); + var version = PgUtils.getAsStringOrElse(rs, EdgeDevice.OPENEMS_VERSION, ""); + var productType = PgUtils.getAsStringOrElse(rs, EdgeDevice.PRODUCT_TYPE, ""); int sumStateInt = PgUtils.getAsIntegerOrElse(rs, EdgeDevice.OPENEMS_SUM_STATE, -1); - Level sumState = Level.fromValue(sumStateInt).orElse(null); + var sumState = Level.fromValue(sumStateInt).orElse(null); - MyEdge edge = this.edgeIdToEdge.get(edgeId); + var edge = this.edgeIdToEdge.get(edgeId); if (edge == null) { // This is new -> create instance of Edge and register listeners edge = new MyEdge(odooId, edgeId, apikey, comment, state, version, productType, sumState, config); @@ -125,7 +124,7 @@ public synchronized MyEdge addOrUpate(ResultSet rs) throws SQLException, Openems /** * Gets an Edge from its Edge-ID. - * + * * @param edgeId the Edge-ID * @return the Edge, or null */ @@ -135,12 +134,12 @@ public synchronized MyEdge getEdgeFromEdgeId(String edgeId) { /** * Gets an Edge from its Odoo-ID. - * + * * @param odooId the Odoo-ID * @return the Edge, or null */ public synchronized MyEdge getEdgeFromOdooId(int odooId) { - String edgeId = this.odooIdToEdgeId.get(odooId); + var edgeId = this.odooIdToEdgeId.get(odooId); if (edgeId == null) { return null; } @@ -149,12 +148,12 @@ public synchronized MyEdge getEdgeFromOdooId(int odooId) { /** * Gets an Edge from its Apikey. - * + * * @param apikey the Apikey * @return the Edge, or null */ public synchronized MyEdge getEdgeForApikey(String apikey) { - String edgeId = this.apikeyToEdgeId.get(apikey); + var edgeId = this.apikeyToEdgeId.get(apikey); if (edgeId == null) { return null; } @@ -163,7 +162,7 @@ public synchronized MyEdge getEdgeForApikey(String apikey) { /** * Gets all Edges as an unmodifiable Collection. - * + * * @return a collection of Edges */ public Collection getAllEdges() { @@ -172,7 +171,7 @@ public Collection getAllEdges() { /** * Adds Listeners to act on changes to Edge. - * + * * @param edge the Edge */ private void addListeners(MyEdge edge) { @@ -187,7 +186,7 @@ private void addListeners(MyEdge edge) { "Mark Edge [" + edge.getId() + "] as ACTIVE. It was [" + edge.getState().name() + "]"); edge.setState(State.ACTIVE); this.parent.getPostgresHandler().getQueueWriteWorker(); - QueueWriteWorker queueWriteWorker = this.parent.getPostgresHandler().getQueueWriteWorker(); + var queueWriteWorker = this.parent.getPostgresHandler().getQueueWriteWorker(); queueWriteWorker.addTask(new UpdateEdgeStateActive(edge.getOdooId())); } } else { @@ -197,14 +196,14 @@ private void addListeners(MyEdge edge) { }); edge.onSetConfig(config -> { // Update Edge Config in Odoo/Postgres - EdgeConfigDiff diff = EdgeConfigDiff.diff(config, edge.getConfig()); + var diff = EdgeConfigDiff.diff(config, edge.getConfig()); if (!diff.isDifferent()) { return; } this.parent.logInfo(this.log, "Edge [" + edge.getId() + "]. Update config: " + diff.toString()); - QueueWriteWorker queueWriteWorker = this.parent.getPostgresHandler().getQueueWriteWorker(); + var queueWriteWorker = this.parent.getPostgresHandler().getQueueWriteWorker(); queueWriteWorker.addTask(new UpdateEdgeConfig(edge.getOdooId(), config)); queueWriteWorker.addTask(new InsertEdgeConfigUpdate(edge.getOdooId(), diff)); }); @@ -221,7 +220,7 @@ private void addListeners(MyEdge edge) { this.parent.logInfo(this.log, "Edge [" + edge.getId() + "]: Update OpenEMS Edge version to [" + version + "]. It was [" + edge.getVersion() + "]"); this.parent.odooHandler.writeEdge(edge, - new FieldValue(Field.EdgeDevice.OPENEMS_VERSION, version.toString())); + new FieldValue<>(Field.EdgeDevice.OPENEMS_VERSION, version.toString())); }); edge.onSetSumState(sumState -> { // Set Sum-State in Odoo/Postgres diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/Field.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/Field.java index cf1a4be5d8e..50e2f16ac1c 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/Field.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/Field.java @@ -7,42 +7,42 @@ public interface Field { /** * Gets the Field ID. - * + * * @return the ID */ public String id(); /** * Gets the Field index. - * + * * @return the index */ public int index(); /** * Gets the Field name. - * + * * @return the name */ public String name(); /** * Should this Field be queried?. - * + * * @return true if yes */ public boolean isQuery(); /** * Gets all fields that should be queried as a comma separated string. - * + * * @param fields an array of {@link Field}s * @return the String */ public static String getSqlQueryFields(Field[] fields) { return Stream.of(fields) // - .filter(f -> f.isQuery()) // - .map(f -> f.id()) // + .filter(Field::isQuery) // + .map(Field::id) // .collect(Collectors.joining(",")); } @@ -66,7 +66,7 @@ public enum EdgeDevice implements Field { OPENEMS_IS_CONNECTED("openems_is_connected", false); public static final String ODOO_MODEL = "openems.edge"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = EdgeDevice.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -99,6 +99,7 @@ public int index() { return this.queryIndex; } + @Override public boolean isQuery() { return this.query; } @@ -119,7 +120,7 @@ public enum EdgeDeviceStatus implements Field { ACKNOWLEDGE_DAYS("acknowledge_days", false); public static final String ODOO_MODEL = "openems.edge_status"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = EdgeDeviceStatus.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -153,6 +154,7 @@ public int index() { return this.queryIndex; } + @Override public boolean isQuery() { return this.query; } @@ -168,7 +170,7 @@ public enum EdgeConfigUpdate implements Field { DETAILS("details", false); public static final String ODOO_MODEL = "openems.openemsconfigupdate"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = EdgeConfigUpdate.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -202,6 +204,7 @@ public int index() { return this.queryIndex; } + @Override public boolean isQuery() { return this.query; } @@ -217,7 +220,7 @@ public enum EdgeDeviceUserRole implements Field { ROLE("role", false); public static final String ODOO_MODEL = "openems.edge_user_role"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = EdgeDeviceUserRole.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -268,7 +271,7 @@ public enum User implements Field { OPENEMS_LANGUAGE("openems_language", true); public static final String ODOO_MODEL = "res.users"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = User.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -327,7 +330,7 @@ public enum Partner implements Field { LANGUAGE("lang", true); public static final String ODOO_MODEL = "res.partner"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = Partner.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -374,7 +377,7 @@ public enum Country implements Field { CODE("code", true); public static final String ODOO_MODEL = "res.country"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = Country.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -422,7 +425,7 @@ public enum SetupProtocol implements Field { EDGE("edge_id", true); public static final String ODOO_MODEL = "openems.setup_protocol"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = SetupProtocol.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -469,7 +472,7 @@ public enum SetupProtocolProductionLot implements Field { LOT("lot_id", true); public static final String ODOO_MODEL = "openems.setup_protocol_production_lot"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = SetupProtocolProductionLot.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -515,7 +518,7 @@ public enum SetupProtocolItem implements Field { SEQUENCE("sequence", true); public static final String ODOO_MODEL = "openems.setup_protocol_item"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = SetupProtocolItem.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; @@ -561,7 +564,7 @@ public enum StockProductionLot implements Field { PRODUCT("product_id", true); public static final String ODOO_MODEL = "stock.production.lot"; - public static final String ODOO_TABLE = ODOO_MODEL.replace(".", "_"); + public static final String ODOO_TABLE = StockProductionLot.ODOO_MODEL.replace(".", "_"); private static final class StaticFields { private static int nextQueryIndex = 1; diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/MyUser.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/MyUser.java index e004fa73d5a..4e97300a742 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/MyUser.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/MyUser.java @@ -17,7 +17,7 @@ public MyUser(int odooId, String login, String name, String token, Role globalRo /** * Gets the internal Odoo record ID. - * + * * @return the odoo id */ public int getOdooId() { diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/OdooMetadata.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/OdooMetadata.java index f3133bab0b3..b4361fdbb67 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/OdooMetadata.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/OdooMetadata.java @@ -16,7 +16,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -28,8 +27,8 @@ import io.openems.backend.metadata.odoo.odoo.OdooUserRole; import io.openems.backend.metadata.odoo.postgres.PostgresHandler; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; -import io.openems.common.jsonrpc.request.UpdateUserLanguageRequest.Language; import io.openems.common.exceptions.OpenemsException; +import io.openems.common.jsonrpc.request.UpdateUserLanguageRequest.Language; import io.openems.common.session.Role; import io.openems.common.utils.JsonUtils; @@ -49,7 +48,7 @@ public class OdooMetadata extends AbstractMetadata implements Metadata { /** * Maps User-ID to {@link User}. */ - private ConcurrentHashMap users = new ConcurrentHashMap<>(); + private final ConcurrentHashMap users = new ConcurrentHashMap<>(); public OdooMetadata() { super("Metadata.Odoo"); @@ -58,7 +57,7 @@ public OdooMetadata() { } @Activate - void activate(Config config) throws SQLException { + private void activate(Config config) throws SQLException { this.logInfo(this.log, "Activate. " // + "Odoo [" + config.odooHost() + ":" + config.odooPort() + ";PW " + (config.odooPassword() != null ? "ok" : "NOT_SET") + "] " // @@ -73,7 +72,7 @@ void activate(Config config) throws SQLException { } @Deactivate - void deactivate() { + private void deactivate() { this.logInfo(this.log, "Deactivate"); if (this.postgresHandler != null) { this.postgresHandler.deactivate(); @@ -97,17 +96,17 @@ public User authenticate(String sessionId) throws OpenemsNamedException { JsonObject result = this.odooHandler.authenticateSession(sessionId); // Parse Result - JsonArray jDevices = JsonUtils.getAsJsonArray(result, "devices"); + var jDevices = JsonUtils.getAsJsonArray(result, "devices"); NavigableMap roles = new TreeMap<>(); for (JsonElement device : jDevices) { - String edgeId = JsonUtils.getAsString(device, "name"); - Role role = Role.getRole(JsonUtils.getAsString(device, "role")); + var edgeId = JsonUtils.getAsString(device, "name"); + var role = Role.getRole(JsonUtils.getAsString(device, "role")); roles.put(edgeId, role); } - JsonObject jUser = JsonUtils.getAsJsonObject(result, "user"); - int odooUserId = JsonUtils.getAsInt(jUser, "id"); + var jUser = JsonUtils.getAsJsonObject(result, "user"); + var odooUserId = JsonUtils.getAsInt(jUser, "id"); - MyUser user = new MyUser(// + var user = new MyUser(// odooUserId, // JsonUtils.getAsString(jUser, "login"), // JsonUtils.getAsString(jUser, "name"), // @@ -127,17 +126,16 @@ public void logout(User user) { @Override public Optional getEdgeIdForApikey(String apikey) { - Optional edge = this.postgresHandler.getEdgeForApikey(apikey); - if (edge.isPresent()) { - return Optional.of(edge.get().getId()); - } else { - return Optional.empty(); + var edgeOpt = this.postgresHandler.getEdgeForApikey(apikey); + if (edgeOpt.isPresent()) { + return Optional.of(edgeOpt.get().getId()); } + return Optional.empty(); } @Override public Optional getEdgeBySetupPassword(String setupPassword) { - Optional optEdgeId = this.odooHandler.getEdgeIdBySetupPassword(setupPassword); + var optEdgeId = this.odooHandler.getEdgeIdBySetupPassword(setupPassword); if (!optEdgeId.isPresent()) { return Optional.empty(); } @@ -161,7 +159,7 @@ public Collection getAllEdges() { /** * Gets the {@link OdooHandler}. - * + * * @return the {@link OdooHandler} */ public OdooHandler getOdooHandler() { @@ -170,7 +168,7 @@ public OdooHandler getOdooHandler() { /** * Gets the {@link PostgresHandler}. - * + * * @return the {@link PostgresHandler} */ public PostgresHandler getPostgresHandler() { @@ -219,11 +217,13 @@ public int submitSetupProtocol(User user, JsonObject jsonObject) throws OpenemsN @Override public void registerUser(JsonObject jsonObject) throws OpenemsNamedException { - OdooUserRole role = OdooUserRole.OWNER; + final OdooUserRole role; - Optional optRole = JsonUtils.getAsOptionalString(jsonObject, "role"); - if (optRole.isPresent()) { - role = OdooUserRole.getRole(optRole.get()); + var roleOpt = JsonUtils.getAsOptionalString(jsonObject, "role"); + if (roleOpt.isPresent()) { + role = OdooUserRole.getRole(roleOpt.get()); + } else { + role = OdooUserRole.OWNER; } this.odooHandler.registerUser(jsonObject, role); diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/Credentials.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/Credentials.java index 969469cce57..8702c15cf1e 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/Credentials.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/Credentials.java @@ -9,7 +9,7 @@ public class Credentials { /** * Creates {@link Credentials} from a {@link Config}uration. - * + * * @param config the configuration * @return a new {@link Credentials} object */ diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/FieldValue.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/FieldValue.java index 3bddbb1804d..3a6b88d5a41 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/FieldValue.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/FieldValue.java @@ -32,7 +32,7 @@ public String toString() { } else { string = this.value.toString(); } - string = string.replaceAll("\n", ""); + string = string.replace("\n", ""); return this.field.id() + ":" + string; } } diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooHandler.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooHandler.java index 2ba3a905269..5c66193001d 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooHandler.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooHandler.java @@ -46,7 +46,7 @@ public OdooHandler(OdooMetadata parent, Config config) { /** * Writes one field to Odoo Edge model. - * + * * @param edge the Edge * @param fieldValues the FieldValues */ @@ -57,14 +57,14 @@ public void writeEdge(MyEdge edge, FieldValue... fieldValues) { } catch (OpenemsException e) { this.parent.logError(this.log, "Unable to update Edge [" + edge.getId() + "] " // + "Odoo-ID [" + edge.getOdooId() + "] " // - + "Fields [" + Stream.of(fieldValues).map(v -> v.toString()).collect(Collectors.joining(",")) + + "Fields [" + Stream.of(fieldValues).map(FieldValue::toString).collect(Collectors.joining(",")) + "]: " + e.getMessage()); } } /** * Adds a message in Odoo Chatter ('mail.thread'). - * + * * @param edge the Edge * @param message the message */ @@ -80,12 +80,12 @@ public void addChatterMessage(MyEdge edge, String message) { /** * Returns Edge by setupPassword, otherwise an empty {@link Optional}. - * + * * @param setupPassword to find Edge * @return Edge or empty {@link Optional} */ public Optional getEdgeIdBySetupPassword(String setupPassword) { - Domain filter = new Domain(Field.EdgeDevice.SETUP_PASSWORD, "=", setupPassword); + var filter = new Domain(Field.EdgeDevice.SETUP_PASSWORD, "=", setupPassword); try { int[] search = OdooUtils.search(this.credentials, Field.EdgeDevice.ODOO_MODEL, filter); @@ -96,7 +96,7 @@ public Optional getEdgeIdBySetupPassword(String setupPassword) { Map read = OdooUtils.readOne(this.credentials, Field.EdgeDevice.ODOO_MODEL, search[0], Field.EdgeDevice.NAME); - String name = (String) read.get(Field.EdgeDevice.NAME.id()); + var name = (String) read.get(Field.EdgeDevice.NAME.id()); if (name == null) { return Optional.empty(); } @@ -112,7 +112,7 @@ public Optional getEdgeIdBySetupPassword(String setupPassword) { /** * Assigns the given user with given {@link OdooUserRole} to the Edge. If Edge * already assigned to user exit method. - * + * * @param user the Odoo user * @param edge the Odoo edge * @param userRole the Odoo user role @@ -126,7 +126,7 @@ public void assignEdgeToUser(MyUser user, MyEdge edge, OdooUserRole userRole) th /** * Assigns the given user with given {@link OdooUserRole} to the Edge. If Edge * already assigned to user exit method. - * + * * @param userId the Odoo user id * @param edgeId the Odoo edge * @param userRole the Odoo user role @@ -142,14 +142,14 @@ private void assignEdgeToUser(int userId, int edgeId, OdooUserRole userRole) thr } OdooUtils.create(this.credentials, Field.EdgeDeviceUserRole.ODOO_MODEL, // - new FieldValue(Field.EdgeDeviceUserRole.USER_ID, userId), // - new FieldValue(Field.EdgeDeviceUserRole.DEVICE_ID, edgeId), // - new FieldValue(Field.EdgeDeviceUserRole.ROLE, userRole.getOdooRole())); + new FieldValue<>(Field.EdgeDeviceUserRole.USER_ID, userId), // + new FieldValue<>(Field.EdgeDeviceUserRole.DEVICE_ID, edgeId), // + new FieldValue<>(Field.EdgeDeviceUserRole.ROLE, userRole.getOdooRole())); } /** * Authenticates a user using Username and Password. - * + * * @param username the Username * @param password the Password * @return the session_id @@ -161,7 +161,7 @@ public String authenticate(String username, String password) throws OpenemsNamed /** * Authenticates a user using a Session-ID. - * + * * @param sessionId the Odoo Session-ID * @return the {@link JsonObject} received from /openems_backend/info. * @throws OpenemsNamedException on error @@ -174,7 +174,7 @@ public JsonObject authenticateSession(String sessionId) throws OpenemsNamedExcep /** * Logout a User. - * + * * @param sessionId the Session-ID * @throws OpenemsNamedException on error */ @@ -189,12 +189,12 @@ public void logout(String sessionId) { /** * Get field from the 'Set-Cookie' field in HTTP headers. - * + * *

* Per specification * all variants of 'cookie' are accepted. - * + * * @param headers the HTTP headers * @param fieldname the field name * @return value as optional @@ -220,13 +220,13 @@ public static Optional getFieldFromSetCookieHeader(Map getUserInformation(MyUser user) throws OpenemsNamedException { - int partnerId = this.getOdooPartnerId(user); + var partnerId = this.getOdooPartnerId(user); Map odooPartner = OdooUtils.readOne(this.credentials, Field.Partner.ODOO_MODEL, partnerId, Field.Partner.FIRSTNAME, // @@ -244,8 +244,8 @@ public Map getUserInformation(MyUser user) throws OpenemsNamedEx Map countryCode = OdooUtils.readOne(this.credentials, Field.Country.ODOO_MODEL, (Integer) odooCountryId[0], Field.Country.CODE); - Optional optCode = ObjectUtils.getAsOptionalString(countryCode.get("code")); - if (optCode.isPresent()) { + var codeOpt = ObjectUtils.getAsOptionalString(countryCode.get("code")); + if (codeOpt.isPresent()) { Object[] countryElement = Arrays.copyOf(odooCountryId, odooCountryId.length + 1); countryElement[2] = countryCode.get("code"); @@ -258,7 +258,7 @@ public Map getUserInformation(MyUser user) throws OpenemsNamedEx /** * Update the given {@link MyUser} with information from {@link JsonObject}. - * + * * @param user the {@link MyUser} to update * @param userJson the {@link JsonObject} information to update * @throws OpenemsException on error @@ -277,23 +277,23 @@ public void setUserInformation(MyUser user, JsonObject userJson) throws OpenemsN JsonUtils.getAsOptionalString(userJson, "phone") // .ifPresent(phone -> fieldValues.put(Field.Partner.PHONE.id(), phone)); - int odooPartnerId = this.getOdooPartnerId(user.getOdooId()); + var odooPartnerId = this.getOdooPartnerId(user.getOdooId()); OdooUtils.write(this.credentials, Field.Partner.ODOO_MODEL, new Integer[] { odooPartnerId }, fieldValues); } /** * Get address to update for an Odoo user. - * + * * @param addressJson {@link JsonObject} to get the fields to update * @return Fields to update * @throws OpenemsException on error */ private Map updateAddress(JsonObject addressJson) throws OpenemsException { - Optional optAddress = JsonUtils.getAsOptionalJsonObject(addressJson, "address"); - if (!optAddress.isPresent()) { + var addressOpt = JsonUtils.getAsOptionalJsonObject(addressJson, "address"); + if (!addressOpt.isPresent()) { return new HashMap<>(); } - JsonObject address = optAddress.get(); + var address = addressOpt.get(); Map addressFields = new HashMap<>(); addressFields.put("type", "private"); @@ -304,9 +304,9 @@ private Map updateAddress(JsonObject addressJson) throws Openems JsonUtils.getAsOptionalString(address, "city") // .ifPresent(city -> addressFields.put(Field.Partner.CITY.id(), city)); - Optional optCountryCode = JsonUtils.getAsOptionalString(address, "country"); - if (optCountryCode.isPresent()) { - String countryCode = optCountryCode.get().toUpperCase(); + var countryCodeOpt = JsonUtils.getAsOptionalString(address, "country"); + if (countryCodeOpt.isPresent()) { + var countryCode = countryCodeOpt.get().toUpperCase(); int[] countryFound = OdooUtils.search(this.credentials, Field.Country.ODOO_MODEL, // new Domain(Field.Country.CODE, "=", countryCode)); @@ -324,7 +324,7 @@ private Map updateAddress(JsonObject addressJson) throws Openems * Get company to update for an Odoo user. Checks if the given company exits in * Odoo and assign the company to the Odoo user. Otherwise a new company will be * created in Odoo. - * + * * @param companyJson {@link JsonObject} to get the fields to update * @return Fields to update * @throws OpenemsException on error @@ -338,32 +338,32 @@ private Map updateCompany(JsonObject companyJson) throws Openems * users company with the new company name for equality. Both are equal nothing * to update. Otherwise the new company will be assigned to the user or the new * company will be created in Odoo. - * + * * @param user {@link MyUser} to check company name * @param companyJson {@link JsonObject} to get the fields to update * @return Fields to update * @throws OpenemsException on error */ private Map updateCompany(MyUser user, JsonObject companyJson) throws OpenemsException { - Optional optCompany = JsonUtils.getAsOptionalJsonObject(companyJson, "company"); - if (!optCompany.isPresent()) { + var companyOpt = JsonUtils.getAsOptionalJsonObject(companyJson, "company"); + if (!companyOpt.isPresent()) { return new HashMap<>(); } - Optional optCompanyName = JsonUtils.getAsOptionalString(optCompany.get(), "name"); - if (!optCompanyName.isPresent()) { + var companyNameOpt = JsonUtils.getAsOptionalString(companyOpt.get(), "name"); + if (!companyNameOpt.isPresent()) { return new HashMap<>(); } - String jsonCompanyName = optCompanyName.get(); + var jCompanyName = companyNameOpt.get(); if (user != null) { Map odooPartner = OdooUtils.readOne(this.credentials, Field.Partner.ODOO_MODEL, // this.getOdooPartnerId(user.getOdooId()), // Field.Partner.COMPANY_NAME); - Optional optPartnerCompanyName = ObjectUtils + var partnerCompanyNameOpt = ObjectUtils .getAsOptionalString(odooPartner.get(Field.Partner.COMPANY_NAME.id())); - if (optPartnerCompanyName.isPresent()) { - if (jsonCompanyName.equals(optPartnerCompanyName.get())) { + if (partnerCompanyNameOpt.isPresent()) { + if (jCompanyName.equals(partnerCompanyNameOpt.get())) { return new HashMap<>(); } } @@ -371,7 +371,7 @@ private Map updateCompany(MyUser user, JsonObject companyJson) t int[] companyFound = OdooUtils.search(this.credentials, Field.Partner.ODOO_MODEL, // new Domain(Field.Partner.IS_COMPANY, "=", true), - new Domain(Field.Partner.COMPANY_NAME, "=", jsonCompanyName)); + new Domain(Field.Partner.COMPANY_NAME, "=", jCompanyName)); Map companyFields = new HashMap<>(); if (companyFound.length > 0) { @@ -379,7 +379,7 @@ private Map updateCompany(MyUser user, JsonObject companyJson) t } else { int createdCompany = OdooUtils.create(this.credentials, Field.Partner.ODOO_MODEL, // new FieldValue<>(Field.Partner.IS_COMPANY, true), - new FieldValue<>(Field.Partner.NAME, jsonCompanyName)); + new FieldValue<>(Field.Partner.NAME, jCompanyName)); companyFields.put(Field.Partner.PARENT.id(), createdCompany); } @@ -388,7 +388,7 @@ private Map updateCompany(MyUser user, JsonObject companyJson) t /** * Returns the Odoo report for a setup protocol. - * + * * @param setupProtocolId the Odoo setup protocol id * @return report as a byte array * @throws OpenemsNamedException on error @@ -399,31 +399,31 @@ public byte[] getOdooSetupProtocolReport(int setupProtocolId) throws OpenemsName /** * Save the Setup Protocol to Odoo. - * + * * @param user {@link MyUser} current user * @param setupProtocolJson {@link SetupProtocol} the setup protocol * @return the Setup Protocol ID * @throws OpenemsNamedException on error */ public int submitSetupProtocol(MyUser user, JsonObject setupProtocolJson) throws OpenemsNamedException { - JsonObject userJson = JsonUtils.getAsJsonObject(setupProtocolJson, "customer"); - JsonObject edgeJson = JsonUtils.getAsJsonObject(setupProtocolJson, "edge"); + var userJson = JsonUtils.getAsJsonObject(setupProtocolJson, "customer"); + var edgeJson = JsonUtils.getAsJsonObject(setupProtocolJson, "edge"); - String edgeId = JsonUtils.getAsString(edgeJson, "id"); + var edgeId = JsonUtils.getAsString(edgeJson, "id"); int[] foundEdge = OdooUtils.search(this.credentials, Field.EdgeDevice.ODOO_MODEL, new Domain(Field.EdgeDevice.NAME, "=", edgeId)); if (foundEdge.length != 1) { throw new OpenemsException("Edge not found for id [" + edgeId + "]"); } - String password = PasswordUtils.generateRandomPassword(24); - int odooUserId = this.createOdooUser(userJson, password); + var password = PasswordUtils.generateRandomPassword(24); + var odooUserId = this.createOdooUser(userJson, password); - int customerId = this.getOdooPartnerId(odooUserId); - int installerId = this.getOdooPartnerId(user); + var customerId = this.getOdooPartnerId(odooUserId); + var installerId = this.getOdooPartnerId(user); this.assignEdgeToUser(odooUserId, foundEdge[0], OdooUserRole.OWNER); - int protocolId = this.createSetupProtocol(setupProtocolJson, foundEdge[0], customerId, installerId); + var protocolId = this.createSetupProtocol(setupProtocolJson, foundEdge[0], customerId, installerId); try { this.sendSetupProtocolMail(user, protocolId, edgeId); @@ -436,7 +436,7 @@ public int submitSetupProtocol(MyUser user, JsonObject setupProtocolJson) throws /** * Call Odoo api to send mail via Odoo. - * + * * @param user the Odoo user * @param protocolId the Odoo setup protocol id * @param edgeId the Odoo edge @@ -455,7 +455,7 @@ private void sendSetupProtocolMail(MyUser user, int protocolId, String edgeId) t /** * Create an Odoo user and return thats id. If user already exists the user will * be updated and return the user id. - * + * * @param userJson the {@link Partner} to create user * @param password the password to set for the new user * @return the Odoo user id @@ -471,7 +471,7 @@ private int createOdooUser(JsonObject userJson, String password) throws OpenemsN JsonUtils.getAsOptionalString(userJson, "lastname") // .ifPresent(lastname -> customerFields.put(Field.Partner.LASTNAME.id(), lastname)); - String email = JsonUtils.getAsString(userJson, "email"); + var email = JsonUtils.getAsString(userJson, "email"); JsonUtils.getAsOptionalString(userJson, "email") // .ifPresent(mail -> customerFields.put(Field.Partner.EMAIL.id(), mail)); JsonUtils.getAsOptionalString(userJson, "phone") // @@ -481,24 +481,23 @@ private int createOdooUser(JsonObject userJson, String password) throws OpenemsN new Domain(Field.User.LOGIN, "=", email)); if (userFound.length == 1) { - int userId = userFound[0]; + var userId = userFound[0]; OdooUtils.write(this.credentials, Field.User.ODOO_MODEL, new Integer[] { userId }, customerFields); return userId; - } else { - customerFields.put(Field.User.LOGIN.id(), email); - customerFields.put(Field.User.PASSWORD.id(), password); - customerFields.put(Field.User.GLOBAL_ROLE.id(), OdooUserRole.OWNER.getOdooRole()); - customerFields.put(Field.User.GROUPS.id(), OdooUserRole.OWNER.toOdooIds()); - int createdUserId = OdooUtils.create(this.credentials, Field.User.ODOO_MODEL, customerFields); - - this.sendRegistrationMail(createdUserId, password); - return createdUserId; } + customerFields.put(Field.User.LOGIN.id(), email); + customerFields.put(Field.User.PASSWORD.id(), password); + customerFields.put(Field.User.GLOBAL_ROLE.id(), OdooUserRole.OWNER.getOdooRole()); + customerFields.put(Field.User.GROUPS.id(), OdooUserRole.OWNER.toOdooIds()); + var createdUserId = OdooUtils.create(this.credentials, Field.User.ODOO_MODEL, customerFields); + + this.sendRegistrationMail(createdUserId, password); + return createdUserId; } /** * Create a setup protocol in Odoo. - * + * * @param jsonObject {@link SetupProtocol} to create * @param edgeId the Edge-ID * @param customerId Odoo customer id to set @@ -510,9 +509,9 @@ private int createSetupProtocol(JsonObject jsonObject, int edgeId, int customerI throws OpenemsException { Integer locationId = null; - Optional jsonLocation = JsonUtils.getAsOptionalJsonObject(jsonObject, "location"); - if (jsonLocation.isPresent()) { - JsonObject location = jsonLocation.get(); + var jLocationOpt = JsonUtils.getAsOptionalJsonObject(jsonObject, "location"); + if (jLocationOpt.isPresent()) { + JsonObject location = jLocationOpt.get(); Map locationFields = new HashMap<>(); locationFields.putAll(this.updateAddress(location)); @@ -538,13 +537,13 @@ private int createSetupProtocol(JsonObject jsonObject, int edgeId, int customerI int setupProtocolId = OdooUtils.create(this.credentials, Field.SetupProtocol.ODOO_MODEL, setupProtocolFields); - Optional lots = JsonUtils.getAsOptionalJsonArray(jsonObject, "lots"); - if (lots.isPresent()) { - this.createSetupProtocolProductionLots(setupProtocolId, lots.get()); + var lotsOpt = JsonUtils.getAsOptionalJsonArray(jsonObject, "lots"); + if (lotsOpt.isPresent()) { + this.createSetupProtocolProductionLots(setupProtocolId, lotsOpt.get()); } - Optional items = JsonUtils.getAsOptionalJsonArray(jsonObject, "items"); - if (items.isPresent()) { - this.createSetupProtocolItems(setupProtocolId, items.get()); + var itemsOpt = JsonUtils.getAsOptionalJsonArray(jsonObject, "items"); + if (itemsOpt.isPresent()) { + this.createSetupProtocolItems(setupProtocolId, itemsOpt.get()); } return setupProtocolId; @@ -552,7 +551,7 @@ private int createSetupProtocol(JsonObject jsonObject, int edgeId, int customerI /** * Create production lots for the given setup protocol id. - * + * * @param setupProtocolId assign to the lots * @param lots list of setup protocol production lots to create * @throws OpenemsException on error @@ -571,10 +570,10 @@ private void createSetupProtocolProductionLots(int setupProtocolId, JsonArray lo JsonUtils.getAsOptionalString(lot, "name") // .ifPresent(name -> lotFields.put("name", name)); - Optional optSerialNumber = JsonUtils.getAsOptionalString(lot, "serialNumber"); - if (optSerialNumber.isPresent()) { + var serialNumberOpt = JsonUtils.getAsOptionalString(lot, "serialNumber"); + if (serialNumberOpt.isPresent()) { int[] lotId = OdooUtils.search(this.credentials, Field.StockProductionLot.ODOO_MODEL, // - new Domain(Field.StockProductionLot.SERIAL_NUMBER, "=", optSerialNumber.get())); + new Domain(Field.StockProductionLot.SERIAL_NUMBER, "=", serialNumberOpt.get())); if (lotId.length > 0) { lotFields.put(Field.SetupProtocolProductionLot.LOT.id(), lotId[0]); @@ -592,7 +591,7 @@ private void createSetupProtocolProductionLots(int setupProtocolId, JsonArray lo /** * Create for the given serial numbers that were not found a * {@link SetupProtocolItem}. - * + * * @param setupProtocolId the protocol id * @param serialNumbers not found serial numbers * @throws OpenemsException on error @@ -617,7 +616,7 @@ private void createNotFoundSerialNumbers(int setupProtocolId, List /** * Create items for the given setup protocol id. - * + * * @param setupProtocolId assign to the items * @param items list of setup protocol items to create * @throws OpenemsException on error @@ -643,7 +642,7 @@ private void createSetupProtocolItems(int setupProtocolId, JsonArray items) thro /** * Gets the referenced Odoo partner id for an Odoo user. - * + * * @param user the Odoo user * @return the Odoo partner id * @throws OpenemsException on error @@ -654,7 +653,7 @@ private int getOdooPartnerId(MyUser user) throws OpenemsException { /** * Gets the referenced Odoo partner id for an Odoo user id. - * + * * @param odooUserId of the Odoo user * @return the Odoo partner id * @throws OpenemsException on error @@ -663,28 +662,28 @@ private int getOdooPartnerId(int odooUserId) throws OpenemsException { Map odooUser = OdooUtils.readOne(this.credentials, Field.User.ODOO_MODEL, odooUserId, Field.User.PARTNER); - Optional odooPartnerId = OdooUtils.getOdooRefernceId(odooUser.get(Field.User.PARTNER.id())); + var odooPartnerIdOpt = OdooUtils.getOdooReferenceId(odooUser.get(Field.User.PARTNER.id())); - if (!odooPartnerId.isPresent()) { + if (!odooPartnerIdOpt.isPresent()) { throw new OpenemsException("Odoo partner not found for user ['" + odooUserId + "']"); } - return odooPartnerId.get(); + return odooPartnerIdOpt.get(); } /** * Register an user in Odoo with the given {@link OdooUserRole}. - * + * * @param jsonObject {@link JsonObject} that represents an user * @param role {@link OdooUserRole} to set for the user * @throws OpenemsNamedException on error */ public void registerUser(JsonObject jsonObject, OdooUserRole role) throws OpenemsNamedException { - Optional optEmail = JsonUtils.getAsOptionalString(jsonObject, "email"); - if (!optEmail.isPresent()) { + var emailOpt = JsonUtils.getAsOptionalString(jsonObject, "email"); + if (!emailOpt.isPresent()) { throw new OpenemsException("No email specified"); } - String email = optEmail.get(); + var email = emailOpt.get(); int[] userFound = OdooUtils.search(this.credentials, Field.User.ODOO_MODEL, // new Domain(Field.User.LOGIN, "=", email)); @@ -715,7 +714,7 @@ public void registerUser(JsonObject jsonObject, OdooUserRole role) throws Openem /** * Call Odoo api to send registration mail via Odoo. - * + * * @param odooUserId Odoo user id to send the mail * @throws OpenemsNamedException error */ @@ -725,7 +724,7 @@ private void sendRegistrationMail(int odooUserId) throws OpenemsNamedException { /** * Call Odoo api to send registration mail via Odoo. - * + * * @param odooUserId Odoo user id to send the mail * @param password password for the user * @throws OpenemsNamedException error @@ -742,7 +741,7 @@ private void sendRegistrationMail(int odooUserId, String password) throws Openem /** * Update language for the given user. - * + * * @param user {@link MyUser} the current user * @param language to set * @throws OpenemsException on error @@ -750,7 +749,7 @@ private void sendRegistrationMail(int odooUserId, String password) throws Openem public void updateUserLanguage(MyUser user, Language language) throws OpenemsException { try { OdooUtils.write(this.credentials, Field.User.ODOO_MODEL, new Integer[] { user.getOdooId() }, // - new FieldValue(Field.User.OPENEMS_LANGUAGE, language.name())); + new FieldValue<>(Field.User.OPENEMS_LANGUAGE, language.name())); } catch (OpenemsNamedException ex) { throw new OpenemsException("Unable to set language [" + language.name() + "] for current user", ex); } diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUserRole.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUserRole.java index dc683d84f1c..d1fb5dcd359 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUserRole.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUserRole.java @@ -23,7 +23,7 @@ public enum OdooUserRole { /** * Get the Odoo role. - * + * * @return Odoo role */ public String getOdooRole() { @@ -32,7 +32,7 @@ public String getOdooRole() { /** * Get the specified Odoo groups for the role. - * + * * @return Groups for an Odoo role */ public OdooUserGroup[] getOdooGroups() { @@ -41,7 +41,7 @@ public OdooUserGroup[] getOdooGroups() { /** * Transform the specified Odoo group objects to a list of IDs. - * + * * @return The Odoo groups as a list of IDs. */ public List toOdooIds() { @@ -52,7 +52,7 @@ public List toOdooIds() { /** * Get the {@link OdooUserRole} for the given role as {@link String}. - * + * * @param role as {@link String} to parse * @return The Odoo role * @throws OpenemsException if role does not exist diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUtils.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUtils.java index 0507bd8449d..62e7b451a1a 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUtils.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/odoo/OdooUtils.java @@ -14,7 +14,6 @@ import java.util.Optional; import com.google.common.io.ByteStreams; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; @@ -33,11 +32,11 @@ private OdooUtils() { public static final String DEFAULT_SERVER_DATE_FORMAT = "yyyy-MM-dd"; public static final String DEFAULT_SERVER_TIME_FORMAT = "HH:mm:ss"; - public static final String DEFAULT_SERVER_DATETIME_FORMAT = DEFAULT_SERVER_DATE_FORMAT + " " - + DEFAULT_SERVER_TIME_FORMAT; + public static final String DEFAULT_SERVER_DATETIME_FORMAT = OdooUtils.DEFAULT_SERVER_DATE_FORMAT + " " + + OdooUtils.DEFAULT_SERVER_TIME_FORMAT; public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter - .ofPattern(DEFAULT_SERVER_DATETIME_FORMAT); + .ofPattern(OdooUtils.DEFAULT_SERVER_DATETIME_FORMAT); /** * Wrapper for the reply of a call to @@ -55,7 +54,7 @@ public SuccessResponseAndHeaders(JsonElement result, Map> h /** * Sends a JSON-RPC Request to an Odoo server - without Cookie header. - * + * * @param url the URL * @param request the JSON-RPC Request as {@link JsonObject} * @return the {@link JsonObject} response and HTTP connection headers on @@ -69,7 +68,7 @@ public static SuccessResponseAndHeaders sendJsonrpcRequest(String url, JsonObjec /** * Sends a JSON-RPC Request to an Odoo server. - * + * * @param url the URL * @param cookie a Cookie string * @param request the JSON-RPC Request as {@link JsonObject} @@ -94,39 +93,39 @@ public static SuccessResponseAndHeaders sendJsonrpcRequest(String url, String co } // send JSON-RPC request - try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) { + try (var out = new OutputStreamWriter(connection.getOutputStream())) { out.write(request.toString()); out.flush(); } // read JSON-RPC response - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); String line = null; - try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + try (var br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { while ((line = br.readLine()) != null) { sb.append(line); } } - JsonObject json = JsonUtils.parseToJsonObject(sb.toString()); + var json = JsonUtils.parseToJsonObject(sb.toString()); // Handle Success or Error if (json.has("error")) { - JsonObject error = JsonUtils.getAsJsonObject(json, "error"); + var error = JsonUtils.getAsJsonObject(json, "error"); // "code":200", - int code = JsonUtils.getAsInt(error, "code"); + var code = JsonUtils.getAsInt(error, "code"); // "message":"Odoo Server Error", - String message = JsonUtils.getAsString(error, "message"); - JsonObject data = JsonUtils.getAsJsonObject(error, "data"); + var message = JsonUtils.getAsString(error, "message"); + var data = JsonUtils.getAsJsonObject(error, "data"); // "name":"odoo.exceptions.AccessDenied", - String dataName = JsonUtils.getAsString(data, "name"); + var dataName = JsonUtils.getAsString(data, "name"); // "debug":"Traceback (most recent call last):\n...", - String dataDebug = JsonUtils.getAsString(data, "debug"); + var dataDebug = JsonUtils.getAsString(data, "debug"); // "message":"Access denied", - String dataMessage = JsonUtils.getAsString(data, "message"); + var dataMessage = JsonUtils.getAsString(data, "message"); // "arguments":["Access denied"], - JsonArray dataArguments = JsonUtils.getAsJsonArray(data, "arguments"); + var dataArguments = JsonUtils.getAsJsonArray(data, "arguments"); // "exception_type":"access_denied" - String dataExceptionType = JsonUtils.getAsString(data, "exception_type"); + var dataExceptionType = JsonUtils.getAsString(data, "exception_type"); switch (dataName) { case "odoo.exceptions.AccessDenied": throw new OpenemsException( @@ -134,7 +133,7 @@ public static SuccessResponseAndHeaders sendJsonrpcRequest(String url, String co case "odoo.http.SessionExpiredException": throw new OpenemsException("Session Expired for Request to URL [" + url + "]"); default: - String exception = "Exception for Request [" + request.toString() + "] to URL [" + url + "]: " // + var exception = "Exception for Request [" + request.toString() + "] to URL [" + url + "]: " // + dataMessage + ";" // + " Code [" + code + "]" // + " Code [" + code + "]" // @@ -167,7 +166,7 @@ public static SuccessResponseAndHeaders sendJsonrpcRequest(String url, String co /** * Sends a request with admin privileges. - * + * * @param credentials the Odoo credentials * @param url to send the request * @param request to send @@ -175,13 +174,13 @@ public static SuccessResponseAndHeaders sendJsonrpcRequest(String url, String co */ protected static void sendAdminJsonrpcRequest(Credentials credentials, String url, JsonObject request) throws OpenemsNamedException { - String session = login(credentials, "admin", credentials.getPassword()); - sendJsonrpcRequest(credentials.getUrl() + url, "session_id=" + session, request); + var session = OdooUtils.login(credentials, "admin", credentials.getPassword()); + OdooUtils.sendJsonrpcRequest(credentials.getUrl() + url, "session_id=" + session, request); } /** * Authenticates a user using Username and Password. - * + * * @param credentials used to get Odoo url * @param username the Username * @param password the Password @@ -190,7 +189,7 @@ protected static void sendAdminJsonrpcRequest(Credentials credentials, String ur */ protected static String login(Credentials credentials, String username, String password) throws OpenemsNamedException { - JsonObject request = JsonUtils.buildJsonObject() // + var request = JsonUtils.buildJsonObject() // .addProperty("jsonrpc", "2.0") // .addProperty("method", "call") // .add("params", JsonUtils.buildJsonObject() // @@ -201,24 +200,22 @@ protected static String login(Credentials credentials, String username, String p .build(); SuccessResponseAndHeaders response = OdooUtils .sendJsonrpcRequest(credentials.getUrl() + "/web/session/authenticate", request); - Optional sessionId = OdooHandler.getFieldFromSetCookieHeader(response.headers, "session_id"); - if (!sessionId.isPresent()) { + var sessionIdOpt = OdooHandler.getFieldFromSetCookieHeader(response.headers, "session_id"); + if (!sessionIdOpt.isPresent()) { throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception(); - } else { - return sessionId.get(); } + return sessionIdOpt.get(); } private static Object executeKw(String url, Object[] params) throws MalformedURLException, XMLRPCException { - XMLRPCClient client = new XMLRPCClient(new URL(String.format("%s/xmlrpc/2/object", url)), - XMLRPCClient.FLAGS_NIL); + var client = new XMLRPCClient(new URL(String.format("%s/xmlrpc/2/object", url)), XMLRPCClient.FLAGS_NIL); client.setTimeout(60 /* seconds */); return client.call("execute_kw", params); } /** * Executes a search on Odoo. - * + * * @param credentials the Odoo credentials * @param model Odoo model to query (e.g. 'res.partner') * @param domains Odoo domain filters @@ -232,15 +229,15 @@ protected static int[] search(Credentials credentials, String model, Domain... d Domain filter = domains[i]; domain[i] = new Object[] { filter.field, filter.operator, filter.value }; } - Object[] paramsDomain = new Object[] { domain }; + Object[] paramsDomain = { domain }; // Create request params HashMap paramsRules = new HashMap(); String action = "search"; - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, action, paramsDomain, paramsRules }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, action, + paramsDomain, paramsRules }; try { // Execute XML request - Object[] resultObjs = (Object[]) executeKw(credentials.getUrl(), params); + var resultObjs = (Object[]) OdooUtils.executeKw(credentials.getUrl(), params); // Parse results int[] results = new int[resultObjs.length]; for (int i = 0; i < resultObjs.length; i++) { @@ -254,7 +251,7 @@ protected static int[] search(Credentials credentials, String model, Domain... d /** * Reads a record from Odoo. - * + * * @param credentials the Odoo credentials * @param model Odoo model to query (e.g. 'res.partner') * @param id id of model to read @@ -266,25 +263,25 @@ protected static Map readOne(Credentials credentials, String mod throws OpenemsException { // Create request params // Add ids - Object[] paramsIds = new Object[1]; + var paramsIds = new Object[1]; paramsIds[0] = id; // Add fields - String[] fieldStrings = new String[fields.length]; + var fieldStrings = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldStrings[i] = fields[i].id(); } Map paramsFields = new HashMap<>(); paramsFields.put("fields", fieldStrings); // Create request params - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, "read", paramsIds, paramsFields }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, "read", + paramsIds, paramsFields }; try { // Execute XML request - Object[] resultObjs = (Object[]) executeKw(credentials.getUrl(), params); + var resultObjs = (Object[]) OdooUtils.executeKw(credentials.getUrl(), params); // Parse results - for (int i = 0; i < resultObjs.length;) { + for (var resultObj : resultObjs) { @SuppressWarnings("unchecked") - Map result = (Map) resultObjs[i]; + var result = (Map) resultObj; return result; } throw new OpenemsException("No matching entry found for id [" + id + "]"); @@ -295,11 +292,11 @@ protected static Map readOne(Credentials credentials, String mod /** * Executes a Search and read on Odoo. - * + * * @see Odoo API * Integration - * + * * @param credentials the Odoo credentials * @param model Odoo model to query (e.g. 'res.partner') * @param domains Odoo domain filters @@ -311,26 +308,26 @@ protected static Map readOne(Credentials credentials, String mod protected static Map[] searchAndRead(Credentials credentials, String model, Domain[] domains, Field[] fields) throws OpenemsException { // Add domain filter - Object[] domain = new Object[domains.length]; + var domain = new Object[domains.length]; for (int i = 0; i < domains.length; i++) { Domain filter = domains[i]; domain[i] = new Object[] { filter.field, filter.operator, filter.value }; } - Object[] paramsDomain = new Object[] { domain }; + Object[] paramsDomain = { domain }; // Add fields - String[] fieldStrings = new String[fields.length]; + var fieldStrings = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldStrings[i] = fields[i].id(); } Map paramsFields = new HashMap<>(); paramsFields.put("fields", fieldStrings); // Create request params - String action = "search_read"; - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, action, paramsDomain, paramsFields }; + var action = "search_read"; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, action, + paramsDomain, paramsFields }; try { // Execute XML request - executeKw(credentials.getUrl(), params); + OdooUtils.executeKw(credentials.getUrl(), params); // Object[] resultObjs = (Object[]) executeKw(url, params); // Parse results // int[] results = new int[resultObjs.length]; @@ -345,7 +342,7 @@ protected static Map[] searchAndRead(Credentials credentials, St /** * Reads multiple records from Odoo. - * + * * @param credentials the Odoo credentials * @param model Odoo model to query (e.g. 'res.partner') * @param ids ids of model to read @@ -356,7 +353,7 @@ protected static Map[] searchAndRead(Credentials credentials, St protected static Map[] readMany(Credentials credentials, String model, Integer[] ids, Field... fields) throws OpenemsException { // Create request params - String action = "read"; + var action = "read"; // Add ids // Object[] paramsIds = Arrays.stream(ids).mapToObj(id -> (Integer) // id).toArray(); @@ -364,24 +361,24 @@ protected static Map[] readMany(Credentials credentials, String // paramsIds[0] = ids[0]; // paramsIds[1] = ids[1]; // Add fields - String[] fieldStrings = new String[fields.length]; + var fieldStrings = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldStrings[i] = fields[i].id(); } // Map paramsFields = new HashMap<>(); // paramsFields.put("fields", fieldStrings); // Create request params - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, action, new Object[] { ids, fieldStrings } }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, action, + new Object[] { ids, fieldStrings } }; try { // Execute XML request - Object[] resultObjs = (Object[]) executeKw(credentials.getUrl(), params); + var resultObjs = (Object[]) OdooUtils.executeKw(credentials.getUrl(), params); // Parse results @SuppressWarnings("unchecked") - Map[] results = (Map[]) new Map[resultObjs.length]; + Map[] results = new Map[resultObjs.length]; for (int i = 0; i < resultObjs.length; i++) { @SuppressWarnings("unchecked") - Map result = (Map) resultObjs[i]; + var result = (Map) resultObjs[i]; results[i] = result; } return results; @@ -392,7 +389,7 @@ protected static Map[] readMany(Credentials credentials, String /** * Search-Reads multiple records from Odoo. - * + * * @param credentials the Odoo credentials * @param model Odoo model to query (e.g. 'res.partner') * @param fields fields that should be read @@ -404,32 +401,32 @@ protected static Map[] searchRead(Credentials credentials, Strin Domain... domains) throws OpenemsException { // Create request params // Add domain filter - Object[] domain = new Object[domains.length]; + var domain = new Object[domains.length]; for (int i = 0; i < domains.length; i++) { - Domain filter = domains[i]; + var filter = domains[i]; domain[i] = new Object[] { filter.field, filter.operator, filter.value }; } - Object[] paramsDomain = new Object[] { domain }; + Object[] paramsDomain = { domain }; // Add fields - String[] fieldStrings = new String[fields.length]; + var fieldStrings = new String[fields.length]; for (int i = 0; i < fields.length; i++) { fieldStrings[i] = fields[i].toString(); } Map paramsFields = new HashMap<>(); paramsFields.put("fields", fieldStrings); // Create request params - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, "search_read", paramsDomain, paramsFields }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, + "search_read", paramsDomain, paramsFields }; try { // Execute XML request - Object[] resultObjs = (Object[]) executeKw(credentials.getUrl(), params); + var resultObjs = (Object[]) OdooUtils.executeKw(credentials.getUrl(), params); // Parse results @SuppressWarnings("unchecked") - Map[] results = (Map[]) new Map[resultObjs.length]; + Map[] results = new Map[resultObjs.length]; for (int i = 0; i < resultObjs.length; i++) { @SuppressWarnings("unchecked") - Map result = (Map) resultObjs[i]; - results[0] = result; + var result = (Map) resultObjs[i]; + results[i] = result; } return results; } catch (Throwable e) { @@ -439,7 +436,7 @@ protected static Map[] searchRead(Credentials credentials, Strin /** * Adds a message in Odoo Chatter ('mail.thread'). - * + * * @param credentials the Odoo credentials * @param model Odoo model (e.g. 'res.partner') * @param id id of model @@ -449,8 +446,8 @@ protected static Map[] searchRead(Credentials credentials, Strin protected static void addChatterMessage(Credentials credentials, String model, int id, String message) throws OpenemsException { // Create request params - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, "message_post", new Object[] { id, message } }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, + "message_post", new Object[] { id, message } }; try { // Execute XML request Object resultObj = executeKw(credentials.getUrl(), params); @@ -464,7 +461,7 @@ protected static void addChatterMessage(Credentials credentials, String model, i /** * Create a record in Odoo. - * + * * @param credentials the Odoo credentials * @param model the Oddo model * @param fieldValues fields and values that should be written @@ -478,12 +475,12 @@ protected static int create(Credentials credentials, String model, FieldValue paramsFieldValues.put(fieldValue.getField().id(), fieldValue.getValue()); } - return create(credentials, model, paramsFieldValues); + return OdooUtils.create(credentials, model, paramsFieldValues); } /** * Create a record in Odoo. - * + * * @param credentials the Odoo credentials * @param model the Oddo model * @param fieldValues fields and values that should be written @@ -492,10 +489,10 @@ protected static int create(Credentials credentials, String model, FieldValue */ protected static int create(Credentials credentials, String model, Map fieldValues) throws OpenemsException { - String action = "create"; + var action = "create"; - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, action, new Object[] { fieldValues } }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, action, + new Object[] { fieldValues } }; try { Object resultObj = (Object) executeKw(credentials.getUrl(), params); @@ -511,7 +508,7 @@ protected static int create(Credentials credentials, String model, Map fieldValues) throws OpenemsException { // Create request params - String action = "write"; + var action = "write"; // Create request params - Object[] params = new Object[] { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), - model, action, new Object[] { ids, fieldValues } }; + Object[] params = { credentials.getDatabase(), credentials.getUid(), credentials.getPassword(), model, action, + new Object[] { ids, fieldValues } }; try { // Execute XML request - Boolean resultObj = (Boolean) executeKw(credentials.getUrl(), params); + var resultObj = (Boolean) OdooUtils.executeKw(credentials.getUrl(), params); if (!resultObj) { throw new OpenemsException("Returned False."); } @@ -570,45 +567,43 @@ protected static void write(Credentials credentials, String model, Integer[] ids /** * Return the Object type-safe as a String; or otherwise as an empty String. - * + * * @param object the value as object * @return the value as String */ protected static String getAsString(Object object) { - if (object != null && object instanceof String) { + if (object instanceof String) { return (String) object; - } else { - return ""; } + return ""; } /** * Return the Object type-safe as a Integer; or otherwise null. - * + * * @param object the value as object * @return the value as Integer */ protected static Integer getAsInteger(Object object) { - if (object != null && object instanceof Integer) { + if (object instanceof Integer) { return (Integer) object; - } else { - return null; } + return null; } /** * Return the odoo reference id as a {@link Integer}, otherwise empty * {@link Optional}. - * + * * @param object the odoo reference to extract * @return the odoo reference id or empty {@link Optional} */ - protected static Optional getOdooRefernceId(Object object) { - if (object != null && object instanceof Object[]) { - Object[] odooRefernce = (Object[]) object; + protected static Optional getOdooReferenceId(Object object) { + if (object instanceof Object[]) { + var odooReference = (Object[]) object; - if (odooRefernce[0] != null && odooRefernce[0] instanceof Integer) { - return Optional.of((Integer) odooRefernce[0]); + if (odooReference.length > 0 && odooReference[0] instanceof Integer) { + return Optional.of((Integer) odooReference[0]); } } @@ -618,7 +613,7 @@ protected static Optional getOdooRefernceId(Object object) { /** * Returns a Odoo report as a byte array. Search for the given template id in * combination with the concrete report id. - * + * * @param credentials the Odoo credentialss * @param report the Odoo template id * @param id the Odoo report id @@ -626,7 +621,7 @@ protected static Optional getOdooRefernceId(Object object) { * @throws OpenemsNamedException on error */ protected static byte[] getOdooReport(Credentials credentials, String report, int id) throws OpenemsNamedException { - String session = login(credentials, "admin", credentials.getPassword()); + var session = OdooUtils.login(credentials, "admin", credentials.getPassword()); HttpURLConnection connection = null; try { diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/Credentials.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/Credentials.java index fbd179c493b..55edcafa294 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/Credentials.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/Credentials.java @@ -9,7 +9,7 @@ public class Credentials { /** * Creates {@link Credentials} from a {@link Config}uration. - * + * * @param config the configuration * @return a new {@link Credentials} object */ diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/InitializeEdgesWorker.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/InitializeEdgesWorker.java index 8f0690f8fcd..9531bdbc180 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/InitializeEdgesWorker.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/InitializeEdgesWorker.java @@ -50,7 +50,7 @@ public synchronized void stop() { ThreadPoolUtils.shutdownAndAwaitTermination(this.executor, 5); } - private Consumer task = (self) -> { + private final Consumer task = self -> { /* * First: mark all Edges as offline */ @@ -97,7 +97,7 @@ public synchronized void stop() { /** * SELECT {} FROM {edge.device};. - * + * * @param connection the {@link Connection} * @return the {@link PreparedStatement} * @throws SQLException on error @@ -111,7 +111,7 @@ private PreparedStatement psQueryAllEdges(Connection connection) throws SQLExcep /** * UPDATE {} SET openems_is_connected = FALSE;. - * + * * @param connection the {@link Connection} * @return the {@link PreparedStatement} * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PeriodicWriteWorker.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PeriodicWriteWorker.java index 5b144eada1b..7c2f23663f3 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PeriodicWriteWorker.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PeriodicWriteWorker.java @@ -1,6 +1,5 @@ package io.openems.backend.metadata.odoo.postgres; -import java.sql.Connection; import java.sql.SQLException; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; @@ -63,7 +62,8 @@ public PeriodicWriteWorker(PostgresHandler parent, HikariDataSource dataSource) public synchronized void start() { this.future = this.executor.scheduleWithFixedDelay(// () -> this.task.accept(this.dataSource), // - UPDATE_INTERVAL_IN_SECONDS, UPDATE_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); + PeriodicWriteWorker.UPDATE_INTERVAL_IN_SECONDS, PeriodicWriteWorker.UPDATE_INTERVAL_IN_SECONDS, + TimeUnit.SECONDS); } /** @@ -78,9 +78,9 @@ public synchronized void stop() { ThreadPoolUtils.shutdownAndAwaitTermination(this.executor, 5); } - private Consumer task = (dataSource) -> { + private final Consumer task = dataSource -> { try { - if (DEBUG_MODE) { + if (PeriodicWriteWorker.DEBUG_MODE) { this.debugLog(); } @@ -101,7 +101,7 @@ public synchronized void stop() { /** * Called on Edge onSetLastMessage event. - * + * * @param edge the {@link MyEdge}. */ public void onLastMessage(MyEdge edge) { @@ -112,7 +112,7 @@ public void onLastMessage(MyEdge edge) { /** * Called on Edge onSetLastUpdate event. - * + * * @param edge the {@link MyEdge}. */ public void onLastUpdate(MyEdge edge) { @@ -123,7 +123,7 @@ public void onLastUpdate(MyEdge edge) { /** * Called on Edge isOnline event. - * + * * @param edge the {@link MyEdge}. */ public void isOnline(MyEdge edge) { @@ -138,7 +138,7 @@ public void isOnline(MyEdge edge) { /** * Called on Edge isOffline event. - * + * * @param edge the {@link MyEdge}. */ public void isOffline(MyEdge edge) { @@ -154,7 +154,7 @@ public void isOffline(MyEdge edge) { private void writeIsOffline(HikariDataSource dataSource) throws SQLException { synchronized (this.isOfflineOdooIds) { if (!this.isOfflineOdooIds.isEmpty()) { - StringBuilder sql = new StringBuilder(// + var sql = new StringBuilder(// "UPDATE " + EdgeDevice.ODOO_TABLE // + " SET " + Field.EdgeDevice.OPENEMS_IS_CONNECTED.id() + " = FALSE" // + " WHERE id IN ("); @@ -172,7 +172,7 @@ private void writeIsOffline(HikariDataSource dataSource) throws SQLException { private void writeIsOnline(HikariDataSource dataSource) throws SQLException { synchronized (this.isOnlineOdooIds) { if (!this.isOnlineOdooIds.isEmpty()) { - StringBuilder sql = new StringBuilder(// + var sql = new StringBuilder(// "UPDATE " + EdgeDevice.ODOO_TABLE // + " SET " + Field.EdgeDevice.OPENEMS_IS_CONNECTED.id() + " = TRUE" // + " WHERE id IN ("); @@ -190,7 +190,7 @@ private void writeIsOnline(HikariDataSource dataSource) throws SQLException { private void writeLastUpdate(HikariDataSource dataSource) throws SQLException { synchronized (this.lastUpdateOdooIds) { if (!this.lastUpdateOdooIds.isEmpty()) { - StringBuilder sql = new StringBuilder(// + var sql = new StringBuilder(// "UPDATE " + EdgeDevice.ODOO_TABLE // + " SET " + Field.EdgeDevice.LAST_UPDATE.id() + " = (now() at time zone 'UTC')" // + " WHERE id IN ("); @@ -208,7 +208,7 @@ private void writeLastUpdate(HikariDataSource dataSource) throws SQLException { private void writeLastMessage(HikariDataSource dataSource) throws SQLException { synchronized (this.lastMessageOdooIds) { if (!this.lastMessageOdooIds.isEmpty()) { - StringBuilder sql = new StringBuilder(// + var sql = new StringBuilder(// "UPDATE " + EdgeDevice.ODOO_TABLE // + " SET " + Field.EdgeDevice.LAST_MESSAGE.id() + " = (now() at time zone 'UTC')" // + " WHERE id IN ("); @@ -224,8 +224,7 @@ private void writeLastMessage(HikariDataSource dataSource) throws SQLException { } private void executeSql(HikariDataSource dataSource, String sql) throws SQLException { - try (Connection con = dataSource.getConnection(); // - ) { + try (var con = dataSource.getConnection()) { con.createStatement().executeUpdate(sql); } } @@ -236,7 +235,7 @@ private void executeSql(HikariDataSource dataSource, String sql) throws SQLExcep private LocalDateTime lastExecute = null; private synchronized void debugLog() { - LocalDateTime now = LocalDateTime.now(); + var now = LocalDateTime.now(); if (this.lastExecute != null) { this.parent.logInfo(this.log, "PeriodicWriteWorker. " // + "Time since last run: [" + ChronoUnit.SECONDS.between(this.lastExecute, now) + "s]" // diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PgUtils.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PgUtils.java index bfd223e7602..9eb6f819b49 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PgUtils.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PgUtils.java @@ -12,7 +12,7 @@ public class PgUtils { /** * Adds a message in Odoo Chatter ('mail.thread'). - * + * * @param credentials the Odoo credentials * @param model Odoo model (e.g. 'res.partner') * @param id id of model @@ -25,7 +25,7 @@ protected static void addChatterMessage(Credentials credentials, String model, i /** * Update a record in Odoo. - * + * * @param credentials the Odoo credentials * @param model the Odoo model * @param ids ids of model to update @@ -38,7 +38,7 @@ public static void write(Credentials credentials, String model, Integer[] ids, F /** * Return the Field of the ResultSet. - * + * * @param rs the ResultSet * @param field the EdgeDevice * @return the value as String @@ -46,17 +46,16 @@ public static void write(Credentials credentials, String model, Integer[] ids, F * @throws OpenemsException on null */ public static String getAsString(ResultSet rs, Field field) throws SQLException, OpenemsException { - String result = rs.getString(field.index()); + var result = rs.getString(field.index()); if (result != null) { return result; - } else { - throw new OpenemsException("Value of field [" + field.name() + "] is null."); } + throw new OpenemsException("Value of field [" + field.name() + "] is null."); } /** * Return the Field of the ResultSet; or default value on error. - * + * * @param rs the ResultSet * @param field the EdgeDevice field * @param other the default value @@ -72,7 +71,7 @@ public static String getAsStringOrElse(ResultSet rs, EdgeDevice field, String ot /** * Return the Field of the ResultSet. - * + * * @param rs the ResultSet * @param field the EdgeDevice * @return the value as Integer @@ -84,7 +83,7 @@ public static int getAsInt(ResultSet rs, EdgeDevice field) throws SQLException { /** * Return the Field of the ResultSet; or default value on error. - * + * * @param rs the ResultSet * @param field the EdgeDevice field * @param other the default value diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PostgresHandler.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PostgresHandler.java index ed0e6e6b417..9009d685459 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PostgresHandler.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/PostgresHandler.java @@ -50,7 +50,7 @@ public void deactivate() { /** * Gets the Edge for an API-Key, i.e. authenticates the API-Key. - * + * * @param apikey the API-Key * @return the Edge or Empty */ @@ -68,7 +68,7 @@ public QueueWriteWorker getQueueWriteWorker() { /** * Creates a {@link HikariDataSource} connection pool. - * + * * @param config the configuration * @return the HikariDataSource * @throws SQLException on error @@ -77,7 +77,7 @@ private HikariDataSource getDataSource(Config config) throws SQLException { if (!Driver.isRegistered()) { Driver.register(); } - PGSimpleDataSource pgds = new PGSimpleDataSource(); + var pgds = new PGSimpleDataSource(); pgds.setServerNames(new String[] { config.pgHost() }); pgds.setPortNumbers(new int[] { config.pgPort() }); pgds.setDatabaseName(config.database()); @@ -85,7 +85,7 @@ private HikariDataSource getDataSource(Config config) throws SQLException { if (config.pgPassword() != null) { pgds.setPassword(config.pgPassword()); } - HikariDataSource result = new HikariDataSource(); + var result = new HikariDataSource(); result.setDataSource(pgds); return result; } diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/QueueWriteWorker.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/QueueWriteWorker.java index 6f1061010fa..3d3fa505a0f 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/QueueWriteWorker.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/QueueWriteWorker.java @@ -47,7 +47,7 @@ public QueueWriteWorker(PostgresHandler parent, HikariDataSource dataSource) { this.parent = parent; this.dataSource = dataSource; - if (DEBUG_MODE) { + if (QueueWriteWorker.DEBUG_MODE) { this.debugLogExecutor = Executors.newSingleThreadScheduledExecutor(); } else { this.debugLogExecutor = null; @@ -58,7 +58,7 @@ public QueueWriteWorker(PostgresHandler parent, HikariDataSource dataSource) { * Starts the {@link QueueWriteWorker}. */ public synchronized void start() { - if (DEBUG_MODE) { + if (QueueWriteWorker.DEBUG_MODE) { this.initializeDebugLog(); } } @@ -74,16 +74,16 @@ public synchronized void stop() { /** * Adds a {@link DatabaseTask} to the queue. - * + * * @param task the {@link DatabaseTask} */ public void addTask(DatabaseTask task) { - if (DEBUG_MODE) { + if (QueueWriteWorker.DEBUG_MODE) { this.count(task, true); } this.executor.execute(() -> { - if (DEBUG_MODE) { + if (QueueWriteWorker.DEBUG_MODE) { this.count(task, false); } @@ -103,16 +103,16 @@ public void addTask(DatabaseTask task) { private void initializeDebugLog() { this.debugLogExecutor.scheduleWithFixedDelay(() -> { - long totalTasks = this.executor.getTaskCount(); - long completedTasks = this.executor.getCompletedTaskCount(); - int countInsertEdgeConfigUpdateUp = this.countInsertEdgeConfigUpdateUp.get(); - int countInsertEdgeConfigUpdateDown = this.countInsertEdgeConfigUpdateDown.get(); - int countInsertOrUpdateDeviceStateUp = this.countInsertOrUpdateDeviceStateUp.get(); - int countInsertOrUpdateDeviceStateDown = this.countInsertOrUpdateDeviceStateDown.get(); - int countUpdateEdgeConfigUp = this.countUpdateEdgeConfigUp.get(); - int countUpdateEdgeConfigDown = this.countUpdateEdgeConfigDown.get(); - int countUpdateEdgeProducttypeUp = this.countUpdateEdgeProducttypeUp.get(); - int countUpdateEdgeProducttypeDown = this.countUpdateEdgeProducttypeDown.get(); + var totalTasks = this.executor.getTaskCount(); + var completedTasks = this.executor.getCompletedTaskCount(); + var countInsertEdgeConfigUpdateUp = this.countInsertEdgeConfigUpdateUp.get(); + var countInsertEdgeConfigUpdateDown = this.countInsertEdgeConfigUpdateDown.get(); + var countInsertOrUpdateDeviceStateUp = this.countInsertOrUpdateDeviceStateUp.get(); + var countInsertOrUpdateDeviceStateDown = this.countInsertOrUpdateDeviceStateDown.get(); + var countUpdateEdgeConfigUp = this.countUpdateEdgeConfigUp.get(); + var countUpdateEdgeConfigDown = this.countUpdateEdgeConfigDown.get(); + var countUpdateEdgeProducttypeUp = this.countUpdateEdgeProducttypeUp.get(); + var countUpdateEdgeProducttypeDown = this.countUpdateEdgeProducttypeDown.get(); this.parent.logInfo(this.log, "QueueWriteWorker. " // + "Total tasks [" + totalTasks + "|" + completedTasks + "|" + (totalTasks - completedTasks) + "] " // diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/DatabaseTask.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/DatabaseTask.java index 29907774f9b..621574373df 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/DatabaseTask.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/DatabaseTask.java @@ -10,12 +10,12 @@ public abstract class DatabaseTask { /** * Execute the Task, making sure the Connection handle is released properly on * exception. - * + * * @param dataSource the {@link HikariDataSource} * @throws SQLException on error */ public void execute(HikariDataSource dataSource) throws SQLException { - try (Connection con = dataSource.getConnection()) { + try (var con = dataSource.getConnection()) { this._execute(con); } } diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertEdgeConfigUpdate.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertEdgeConfigUpdate.java index b6988c55065..5df6c451d3f 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertEdgeConfigUpdate.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertEdgeConfigUpdate.java @@ -26,7 +26,7 @@ public InsertEdgeConfigUpdate(int odooId, EdgeConfigDiff diff) { @Override protected void _execute(Connection connection) throws SQLException { - PreparedStatement ps = this.psInsertEdgeConfigUpdate(connection); + var ps = this.psInsertEdgeConfigUpdate(connection); ps.setTimestamp(1, this.createDate); ps.setInt(2, this.odooId); ps.setString(3, this.teaser); @@ -37,7 +37,7 @@ protected void _execute(Connection connection) throws SQLException { /** * UPDATE {} SET openems_config = {}, openems_config_components = {} WHERE id = * {};. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertOrUpdateDeviceStates.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertOrUpdateDeviceStates.java index 951b5a024de..0e7983b96fa 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertOrUpdateDeviceStates.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/InsertOrUpdateDeviceStates.java @@ -36,7 +36,7 @@ public InsertOrUpdateDeviceStates(int odooId, Timestamp timestamp, List * Be careful to synchronize access to the resulting PreparedStatement. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeConfig.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeConfig.java index 5ea5e46bc34..84daf22d53e 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeConfig.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeConfig.java @@ -26,7 +26,7 @@ public UpdateEdgeConfig(int odooId, EdgeConfig config) { @Override protected void _execute(Connection connection) throws SQLException { - PreparedStatement ps = this.psUpdateEdgeConfig(connection); + var ps = this.psUpdateEdgeConfig(connection); ps.setString(1, this.fullConfig); ps.setString(2, this.componentsConfig); ps.setInt(3, this.odooId); @@ -36,7 +36,7 @@ protected void _execute(Connection connection) throws SQLException { /** * UPDATE {} SET openems_config = {}, openems_config_components = {} WHERE id = * {};. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeProducttype.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeProducttype.java index 52f00285088..08390a92d60 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeProducttype.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeProducttype.java @@ -18,7 +18,7 @@ public UpdateEdgeProducttype(int odooId, String producttype) { @Override protected void _execute(Connection connection) throws SQLException { - PreparedStatement ps = this.psUpdateProductType(connection); + var ps = this.psUpdateProductType(connection); ps.setString(1, this.producttype); ps.setInt(2, this.odooId); ps.execute(); @@ -26,7 +26,7 @@ protected void _execute(Connection connection) throws SQLException { /** * UPDATE {} SET version = {} WHERE id = {};. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeStateActive.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeStateActive.java index beec53d2307..9eb62671d00 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeStateActive.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateEdgeStateActive.java @@ -16,14 +16,14 @@ public UpdateEdgeStateActive(int odooId) { @Override protected void _execute(Connection connection) throws SQLException { - PreparedStatement ps = this.psUpdateEdgeStateActive(connection); + var ps = this.psUpdateEdgeStateActive(connection); ps.setInt(1, this.odooId); ps.execute(); } /** * UPDATE {} SET state = 'active' WHERE id = {};. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateSumState.java b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateSumState.java index f2ef1487f40..a577e966a99 100644 --- a/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateSumState.java +++ b/io.openems.backend.metadata.odoo/src/io/openems/backend/metadata/odoo/postgres/task/UpdateSumState.java @@ -19,7 +19,7 @@ public UpdateSumState(int odooId, Level sumState) { @Override protected void _execute(Connection connection) throws SQLException { - PreparedStatement ps = this.psUpdateSumState(connection); + var ps = this.psUpdateSumState(connection); final String sumStateString; if (this.sumState != null) { sumStateString = this.sumState.getName().toLowerCase(); @@ -33,7 +33,7 @@ protected void _execute(Connection connection) throws SQLException { /** * UPDATE {} SET openems_sum_state_level = {} WHERE id = {};. - * + * * @param connection the {@link Connection} * @return the PreparedStatement * @throws SQLException on error diff --git a/io.openems.backend.timedata.dummy/src/io/openems/backend/timedata/dummy/TimedataDummy.java b/io.openems.backend.timedata.dummy/src/io/openems/backend/timedata/dummy/TimedataDummy.java index 3e0d41e2c0e..85f6d788ef9 100644 --- a/io.openems.backend.timedata.dummy/src/io/openems/backend/timedata/dummy/TimedataDummy.java +++ b/io.openems.backend.timedata.dummy/src/io/openems/backend/timedata/dummy/TimedataDummy.java @@ -38,22 +38,22 @@ public TimedataDummy() { } @Activate - void activate(Config config) throws OpenemsException { + private void activate(Config config) throws OpenemsException { this.logInfo(this.log, "Activate"); } @Deactivate - void deactivate() { + private void deactivate() { this.logInfo(this.log, "Deactivate"); } + @Override public Optional getChannelValue(String edgeId, ChannelAddress channelAddress) { EdgeCache edgeCache = this.edgeCacheMap.get(edgeId); if (edgeCache != null) { return edgeCache.getChannelValue(channelAddress); - } else { - return Optional.empty(); } + return Optional.empty(); } @Override diff --git a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/ChannelFormula.java b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/ChannelFormula.java index c65be3342fd..808c585368b 100644 --- a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/ChannelFormula.java +++ b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/ChannelFormula.java @@ -26,6 +26,12 @@ public ChannelFormula(Function function, int staticValue) { this.staticValue = Optional.of(staticValue); } + /** + * Gets the Channel value. + * + * @param cache an {@link EdgeCache} + * @return the value + */ public int getValue(EdgeCache cache) { if (this.address.isPresent()) { return cache.getChannelValue(this.address.get()).orElse(new JsonPrimitive(0)).getAsInt(); @@ -37,7 +43,7 @@ public int getValue(EdgeCache cache) { } public Function getFunction() { - return function; + return this.function; } } diff --git a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/FieldTypeConflictHandler.java b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/FieldTypeConflictHandler.java index d227e5e6dcc..8f2d237524e 100644 --- a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/FieldTypeConflictHandler.java +++ b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/FieldTypeConflictHandler.java @@ -2,7 +2,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiConsumer; -import java.util.regex.Matcher; import java.util.regex.Pattern; import org.influxdb.InfluxDBException.FieldTypeConflictException; @@ -18,7 +17,7 @@ */ public class FieldTypeConflictHandler { - private final static Pattern FIELD_TYPE_CONFLICT_EXCEPTION_PATTERN = Pattern.compile( + private static final Pattern FIELD_TYPE_CONFLICT_EXCEPTION_PATTERN = Pattern.compile( "^partial write: field type conflict: input field \"(?.*)\" on measurement \"data\" is type (?\\w+), already exists as type (?\\w+) dropped=\\d+$"); private final Logger log = LoggerFactory.getLogger(FieldTypeConflictHandler.class); @@ -32,19 +31,18 @@ public FieldTypeConflictHandler(Influx parent) { /** * Handles a {@link FieldTypeConflictException}; adds special handling for * fields that already exist in the database. - * - * @param failedPoints the failed points - * @param e the {@link FieldTypeConflictException} + * + * @param e the {@link FieldTypeConflictException} */ public synchronized void handleException(FieldTypeConflictException e) { - Matcher matcher = FIELD_TYPE_CONFLICT_EXCEPTION_PATTERN.matcher(e.getMessage()); + var matcher = FieldTypeConflictHandler.FIELD_TYPE_CONFLICT_EXCEPTION_PATTERN.matcher(e.getMessage()); if (!matcher.find()) { this.parent.logWarn(this.log, "Unable to add special field handler for message [" + e.getMessage() + "]"); return; } - String field = matcher.group("channel"); - String thisType = matcher.group("thisType"); - String requiredType = matcher.group("requiredType"); + var field = matcher.group("channel"); + var thisType = matcher.group("thisType"); + var requiredType = matcher.group("requiredType"); if (this.specialCaseFieldHandlers.containsKey(field)) { // Special handling had already been added. @@ -55,7 +53,7 @@ public synchronized void handleException(FieldTypeConflictException e) { switch (requiredType) { case "string": handler = (builder, jValue) -> { - String value = this.getAsFieldTypeString(jValue); + var value = this.getAsFieldTypeString(jValue); if (value != null) { builder.addField(field, value); } @@ -65,14 +63,14 @@ public synchronized void handleException(FieldTypeConflictException e) { case "integer": handler = (builder, jValue) -> { try { - Number value = this.getAsFieldTypeNumber(jValue); + var value = this.getAsFieldTypeNumber(jValue); if (value != null) { builder.addField(field, value); } } catch (NumberFormatException e1) { try { // Failed -> try conversion to float and then to int - Float value = this.getAsFieldTypeFloat(jValue); + var value = this.getAsFieldTypeFloat(jValue); if (value != null) { builder.addField(field, Math.round(value)); } @@ -87,7 +85,7 @@ public synchronized void handleException(FieldTypeConflictException e) { case "float": handler = (builder, jValue) -> { try { - Float value = this.getAsFieldTypeFloat(jValue); + var value = this.getAsFieldTypeFloat(jValue); if (value != null) { builder.addField(field, value); } @@ -102,17 +100,15 @@ public synchronized void handleException(FieldTypeConflictException e) { if (handler == null) { this.parent.logWarn(this.log, "Unable to add special field handler for [" + field + "] from [" + thisType + "] to [" + requiredType + "]"); - return; - } else { - this.parent.logInfo(this.log, - "Add special field handler for [" + field + "] from [" + thisType + "] to [" + requiredType + "]"); - this.specialCaseFieldHandlers.put(field, handler); } + this.parent.logInfo(this.log, + "Add special field handler for [" + field + "] from [" + thisType + "] to [" + requiredType + "]"); + this.specialCaseFieldHandlers.put(field, handler); } /** - * Convert JsonElement to String - * + * Convert JsonElement to String. + * * @param jValue the value * @return the value as String; null if value represents null */ @@ -124,8 +120,8 @@ private String getAsFieldTypeString(JsonElement jValue) { } /** - * Convert JsonElement to Number - * + * Convert JsonElement to Number. + * * @param jValue the value * @return the value as Number; null if value represents null * @throws NumberFormatException on error @@ -134,7 +130,7 @@ private Number getAsFieldTypeNumber(JsonElement jValue) throws NumberFormatExcep if (jValue.isJsonNull()) { return null; } - String value = jValue.toString().replace("\"", ""); + var value = jValue.toString().replace("\"", ""); if (value.isEmpty()) { return null; } @@ -142,9 +138,9 @@ private Number getAsFieldTypeNumber(JsonElement jValue) throws NumberFormatExcep return Long.parseLong(value); } catch (NumberFormatException e1) { if (value.equalsIgnoreCase("false")) { - return 0l; + return 0L; } else if (value.equalsIgnoreCase("true")) { - return 1l; + return 1L; } else { throw e1; } @@ -152,8 +148,8 @@ private Number getAsFieldTypeNumber(JsonElement jValue) throws NumberFormatExcep } /** - * Convert JsonElement to Float - * + * Convert JsonElement to Float. + * * @param jValue the value * @return the value as Float; null if value represents null * @throws NumberFormatException on error @@ -162,7 +158,7 @@ private Float getAsFieldTypeFloat(JsonElement jValue) throws NumberFormatExcepti if (jValue.isJsonNull()) { return null; } - String value = jValue.toString().replace("\"", ""); + var value = jValue.toString().replace("\"", ""); if (value.isEmpty()) { return null; } @@ -171,7 +167,7 @@ private Float getAsFieldTypeFloat(JsonElement jValue) throws NumberFormatExcepti /** * Gets the handler for the given Field. - * + * * @param field the Field * @return the handler or null */ diff --git a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/Influx.java b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/Influx.java index 281f49a789c..826bed38c64 100644 --- a/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/Influx.java +++ b/io.openems.backend.timedata.influx/src/io/openems/backend/timedata/influx/Influx.java @@ -9,8 +9,6 @@ import java.util.Set; import java.util.SortedMap; import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.regex.Matcher; import java.util.regex.Pattern; import org.influxdb.InfluxDBException.FieldTypeConflictException; @@ -39,7 +37,6 @@ import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; import io.openems.common.exceptions.OpenemsException; import io.openems.common.types.ChannelAddress; -import io.openems.common.types.EdgeConfig; import io.openems.common.types.SemanticVersion; import io.openems.common.utils.StringUtils; import io.openems.shared.influxdb.InfluxConnector; @@ -68,17 +65,17 @@ public Influx() { protected volatile Metadata metadata; @Activate - void activate(Config config) throws OpenemsException { - this.logInfo(this.log, "Activate [" + // - "url=" + config.url() + // - ";port=" + config.port() + // - ";database=" + config.database() + // - ";retentionPolicy=" + config.retentionPolicy() + // - ";username=" + config.username() + // - ";password=" + (config.password() != null ? "ok" : "NOT_SET") + // - ";measurement=" + config.measurement() + // - (config.isReadOnly() ? ";READ_ONLY_MODE" : "") + // - "]"); + private void activate(Config config) throws OpenemsException { + this.logInfo(this.log, "Activate [" // + + "url=" + config.url() + ";"// + + "port=" + config.port() + ";" // + + "database=" + config.database() + ";"// + + "retentionPolicy=" + config.retentionPolicy() + ";"// + + "username=" + config.username() + ";"// + + "password=" + (config.password() != null ? "ok" : "NOT_SET") + ";"// + + "measurement=" + config.measurement() // + + (config.isReadOnly() ? ";READ_ONLY_MODE" : "") // + + "]"); this.influxConnector = new InfluxConnector(config.url(), config.port(), config.username(), config.password(), config.database(), config.retentionPolicy(), config.isReadOnly(), // @@ -95,7 +92,7 @@ void activate(Config config) throws OpenemsException { } @Deactivate - void deactivate() { + private void deactivate() { this.logInfo(this.log, "Deactivate"); if (this.influxConnector != null) { this.influxConnector.deactivate(); @@ -108,7 +105,7 @@ public void write(String edgeId, TreeBasedTable + * e.g. translates "edge0" to "0". + * + * @param name the edge name + * @return the number + * @throws OpenemsException on error + */ public static Integer parseNumberFromName(String name) throws OpenemsException { try { - Matcher matcher = NAME_NUMBER_PATTERN.matcher(name); + var matcher = Influx.NAME_NUMBER_PATTERN.matcher(name); if (matcher.find()) { - String nameNumberString = matcher.group(1); + var nameNumberString = matcher.group(1); return Integer.parseInt(nameNumberString); } } catch (NullPointerException e) { @@ -206,7 +213,6 @@ public SortedMap> queryHis * @param builder the Influx PointBuilder * @param field the field name * @param element the value - * @return */ private void addValue(Builder builder, String field, JsonElement element) { if (element == null || element.isJsonNull()) { @@ -218,7 +224,7 @@ private void addValue(Builder builder, String field, JsonElement element) { return; } if (element.isJsonPrimitive()) { - JsonPrimitive value = element.getAsJsonPrimitive(); + var value = element.getAsJsonPrimitive(); if (value.isNumber()) { try { builder.addField(field, Long.parseLong(value.toString())); @@ -243,18 +249,18 @@ private void addValue(Builder builder, String field, JsonElement element) { /** * Handles some special cases for fields. - * + * *

* E.g. to avoid errors like "field type conflict: input field XYZ on * measurement "data" is type integer, already exists as type string" - * + * * @param builder the InfluxDB Builder * @param field the fieldName, i.e. the ChannelAddress * @param value the value, guaranteed to be not-null and not JsonNull. * @return true if field was handled; false otherwise */ private boolean specialCaseFieldHandling(Builder builder, String field, JsonElement value) { - BiConsumer handler = this.fieldTypeConflictHandler.getHandler(field); + var handler = this.fieldTypeConflictHandler.getHandler(field); if (handler == null) { // no special handling exists for this field return false; @@ -266,35 +272,34 @@ private boolean specialCaseFieldHandling(Builder builder, String field, JsonElem @Override public Optional getChannelValue(String edgeId, ChannelAddress address) { - EdgeCache cache = this.edgeCacheMap.get(edgeId); - if (cache != null) { - Optional value = cache.getChannelValue(address); - if (value.isPresent()) { - return value; - } - Optional edge = this.metadata.getEdge(edgeId); - if (!edge.isPresent()) { - return Optional.empty(); - } - if (edge.get().getVersion().isAtLeast(new SemanticVersion(2018, 11, 0))) { - return Optional.empty(); - } - // Old version: start compatibility mode - ChannelFormula[] compatibility = this.getCompatibilityFormula(edge.get(), address); - if (compatibility.length == 0) { - return Optional.empty(); - } - // handle compatibility with elder OpenEMS Edge version - return this.getCompatibilityChannelValue(compatibility, cache); - } else { + var cache = this.edgeCacheMap.get(edgeId); + if (cache == null) { + return Optional.empty(); + } + var value = cache.getChannelValue(address); + if (value.isPresent()) { + return value; + } + var edge = this.metadata.getEdge(edgeId); + if (!edge.isPresent()) { + return Optional.empty(); + } + if (edge.get().getVersion().isAtLeast(new SemanticVersion(2018, 11, 0))) { + return Optional.empty(); + } + // Old version: start compatibility mode + var compatibility = this.getCompatibilityFormula(edge.get(), address); + if (compatibility.length == 0) { return Optional.empty(); } + // handle compatibility with elder OpenEMS Edge version + return this.getCompatibilityChannelValue(compatibility, cache); } /** * Handles compatibility with elder OpenEMS Edge version, e.g. calculate the * '_sum' Channels. - * + * * @param compatibility the formula to calculate the channel value * @param cache the EdgeCache * @return the value as an Optional @@ -313,14 +318,14 @@ private Optional getCompatibilityChannelValue(ChannelFormula[] comp /** * Gets the formula to calculate a '_sum' Channel value. - * + * * @param edge the Edge * @param address the ChannelAddress * @return the formula to calculate the channel value */ @Deprecated private ChannelFormula[] getCompatibilityFormula(Edge edge, ChannelAddress address) { - EdgeConfig config = edge.getConfig(); + var config = edge.getConfig(); if (address.getComponentId().equals("_sum")) { switch (address.getChannelId()) { @@ -331,16 +336,15 @@ private ChannelFormula[] getCompatibilityFormula(Edge edge, ChannelAddress addre // take first result return new ChannelFormula[] { new ChannelFormula(Function.PLUS, new ChannelAddress(ids.get(0), "Soc")) }; - } else { - return new ChannelFormula[0]; } + return new ChannelFormula[0]; } case "EssActivePower": { List asymmetricIds = config.getComponentsImplementingNature("AsymmetricEssNature"); List symmetricIds = config.getComponentsImplementingNature("SymmetricEssNature"); symmetricIds.removeAll(asymmetricIds); - ChannelFormula[] result = new ChannelFormula[asymmetricIds.size() * 3 + symmetricIds.size()]; + var result = new ChannelFormula[asymmetricIds.size() * 3 + symmetricIds.size()]; int i = 0; for (String id : asymmetricIds) { result[i++] = new ChannelFormula(Function.PLUS, new ChannelAddress(id, "ActivePowerL1")); @@ -419,7 +423,7 @@ private ChannelFormula[] getCompatibilityFormula(Edge edge, ChannelAddress addre symmetricIds.removeAll(ignoreIds); symmetricIds.removeAll(asymmetricIds); - ChannelFormula[] result = new ChannelFormula[asymmetricIds.size() * 3 + symmetricIds.size()]; + var result = new ChannelFormula[asymmetricIds.size() * 3 + symmetricIds.size()]; int i = 0; for (String id : asymmetricIds) { result[i++] = new ChannelFormula(Function.PLUS, new ChannelAddress(id, "ActivePowerL1")); @@ -434,7 +438,7 @@ private ChannelFormula[] getCompatibilityFormula(Edge edge, ChannelAddress addre case "ProductionDcActualPower": { List ids = config.getComponentsImplementingNature("ChargerNature"); - ChannelFormula[] result = new ChannelFormula[ids.size()]; + var result = new ChannelFormula[ids.size()]; for (int i = 0; i < ids.size(); i++) { result[i] = new ChannelFormula(Function.PLUS, new ChannelAddress(ids.get(i), "ActualPower")); } diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnClose.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnClose.java index bacb873c0e7..7bbea9319e3 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnClose.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnClose.java @@ -1,12 +1,9 @@ package io.openems.backend.uiwebsocket.impl; -import java.util.Optional; - import org.java_websocket.WebSocket; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsException; public class OnClose implements io.openems.common.websocket.OnClose { @@ -22,9 +19,9 @@ public OnClose(UiWebsocketImpl parent) { public void run(WebSocket ws, int code, String reason, boolean remote) throws OpenemsException { // get current User WsData wsData = ws.getAttachment(); - Optional userOpt = wsData.getUser(this.parent.metadata); + var userOpt = wsData.getUser(this.parent.metadata); if (userOpt.isPresent()) { - User user = userOpt.get(); + var user = userOpt.get(); this.parent.logInfo(this.log, "User [" + user.getId() + ":" + user.getName() + "] disconnected."); } else { this.parent.logInfo(this.log, "User [" + wsData.getUserId().orElse("UNKNOWN") + "] disconnected."); diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnRequest.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnRequest.java index 841c55f8375..0bb168fa346 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnRequest.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/OnRequest.java @@ -1,7 +1,5 @@ package io.openems.backend.uiwebsocket.impl; -import java.util.Map; -import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; @@ -9,8 +7,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.google.gson.JsonObject; - import io.openems.backend.common.jsonrpc.request.AddEdgeToUserRequest; import io.openems.backend.common.jsonrpc.request.GetSetupProtocolRequest; import io.openems.backend.common.jsonrpc.request.GetUserInformationRequest; @@ -19,7 +15,6 @@ import io.openems.backend.common.jsonrpc.request.SubmitSetupProtocolRequest; import io.openems.backend.common.jsonrpc.response.AddEdgeToUserResponse; import io.openems.backend.common.jsonrpc.response.GetUserInformationResponse; -import io.openems.backend.common.metadata.Edge; import io.openems.backend.common.metadata.User; import io.openems.common.exceptions.OpenemsError; import io.openems.common.exceptions.OpenemsError.OpenemsNamedException; @@ -67,7 +62,7 @@ public CompletableFuture run(WebSocket ws, Jso } // should be authenticated - User user = this.assertUser(wsData, request); + var user = this.assertUser(wsData, request); switch (request.getMethod()) { case LogoutRequest.METHOD: @@ -107,7 +102,7 @@ public CompletableFuture run(WebSocket ws, Jso /** * Handles a {@link AuthenticateWithTokenRequest}. - * + * * @param wsData the WebSocket attachment * @param request the {@link AuthenticateWithTokenRequest} * @return the JSON-RPC Success Response Future @@ -121,7 +116,7 @@ private CompletableFuture handleAuthenticateWithTokenReq /** * Handles a {@link AuthenticateWithPasswordRequest}. - * + * * @param wsData the WebSocket attachment * @param request the {@link AuthenticateWithPasswordRequest} * @return the JSON-RPC Success Response Future @@ -132,16 +127,15 @@ private CompletableFuture handleAuthenticateWithPassword if (request.getUsername().isPresent()) { return this.handleAuthentication(wsData, request.getId(), this.parent.metadata.authenticate(request.getUsername().get(), request.getPassword())); - } else { - return this.handleAuthentication(wsData, request.getId(), - this.parent.metadata.authenticate(request.getPassword())); } + return this.handleAuthentication(wsData, request.getId(), + this.parent.metadata.authenticate(request.getPassword())); } /** * Common handler for {@link AuthenticateWithTokenRequest} and * {@link AuthenticateWithPasswordRequest}. - * + * * @param wsData the WebSocket attachment * @param requestId the ID of the original {@link JsonrpcRequest} * @param user the authenticated {@link User} @@ -160,7 +154,7 @@ private CompletableFuture handleAuthentication(WsData ws /** * Handles a {@link RegisterUserRequest}. - * + * * @param wsData the WebSocket attachment * @param request the {@link RegisterUserRequest} * @return the JSON-RPC Success Response Future @@ -175,7 +169,7 @@ private CompletableFuture handleRegisterUserReuqest(WsDa /** * Handles a {@link LogoutRequest}. - * + * * @param wsData the WebSocket attachment * @param user the authenticated {@link User} * @param request the {@link LogoutRequest} @@ -192,19 +186,19 @@ private CompletableFuture handleLogoutRequest(WsData wsD /** * Gets the authenticated User or throws an Exception if User is not * authenticated. - * + * * @param wsData the WebSocket attachment * @param request the JsonrpcRequest * @return the {@link User} * @throws OpenemsNamedException if User is not authenticated */ private User assertUser(WsData wsData, JsonrpcRequest request) throws OpenemsNamedException { - Optional userIdOpt = wsData.getUserId(); + var userIdOpt = wsData.getUserId(); if (!userIdOpt.isPresent()) { throw OpenemsError.COMMON_USER_NOT_AUTHENTICATED .exception("User-ID is empty. Ignoring request [" + request.getMethod() + "]"); } - Optional userOpt = this.parent.metadata.getUser(userIdOpt.get()); + var userOpt = this.parent.metadata.getUser(userIdOpt.get()); if (!userOpt.isPresent()) { throw OpenemsError.COMMON_USER_NOT_AUTHENTICATED.exception("User with ID [" + userIdOpt.get() + "] is unknown. Ignoring request [" + request.getMethod() + "]"); @@ -214,7 +208,7 @@ private User assertUser(WsData wsData, JsonrpcRequest request) throws OpenemsNam /** * Handles an {@link EdgeRpcRequest}. - * + * * @param wsData the WebSocket attachment * @param user the authenticated {@link User} * @param edgeRpcRequest the {@link EdgeRpcRequest} @@ -223,8 +217,8 @@ private User assertUser(WsData wsData, JsonrpcRequest request) throws OpenemsNam */ private CompletableFuture handleEdgeRpcRequest(WsData wsData, User user, EdgeRpcRequest edgeRpcRequest) throws OpenemsNamedException { - String edgeId = edgeRpcRequest.getEdgeId(); - JsonrpcRequest request = edgeRpcRequest.getPayload(); + var edgeId = edgeRpcRequest.getEdgeId(); + var request = edgeRpcRequest.getPayload(); user.assertEdgeRoleIsAtLeast(EdgeRpcRequest.METHOD, edgeId, Role.GUEST); CompletableFuture resultFuture; @@ -246,7 +240,7 @@ private CompletableFuture handleEdgeRpcRequest(WsData wsData, U } // Wrap reply in EdgeRpcResponse - CompletableFuture result = new CompletableFuture(); + var result = new CompletableFuture(); resultFuture.whenComplete((r, ex) -> { if (ex != null) { result.completeExceptionally(ex); @@ -262,7 +256,7 @@ private CompletableFuture handleEdgeRpcRequest(WsData wsData, U /** * Handles a {@link SubscribeChannelsRequest}. - * + * * @param wsData the WebSocket attachment * @param edgeId the Edge-ID * @param user the {@link User} - no specific level required @@ -273,7 +267,7 @@ private CompletableFuture handleEdgeRpcRequest(WsData wsData, U private CompletableFuture handleSubscribeChannelsRequest(WsData wsData, String edgeId, User user, SubscribeChannelsRequest request) throws OpenemsNamedException { // activate SubscribedChannelsWorker - SubscribedChannelsWorker worker = wsData.getSubscribedChannelsWorker(edgeId); + var worker = wsData.getSubscribedChannelsWorker(edgeId); worker.handleSubscribeChannelsRequest(user.getRole(edgeId).orElse(Role.GUEST), request); // JSON-RPC response @@ -282,7 +276,7 @@ private CompletableFuture handleSubscribeChannelsRequest /** * Handles a {@link SubscribeSystemLogRequest}. - * + * * @param wsData the WebSocket attachment * @param edgeId the Edge-ID * @param user the {@link User} @@ -293,7 +287,7 @@ private CompletableFuture handleSubscribeChannelsRequest private CompletableFuture handleSubscribeSystemLogRequest(WsData wsData, String edgeId, User user, SubscribeSystemLogRequest request) throws OpenemsNamedException { user.assertEdgeRoleIsAtLeast(SubscribeSystemLogRequest.METHOD, edgeId, Role.OWNER); - String token = wsData.assertToken(); + var token = wsData.assertToken(); // Forward to Edge return this.parent.edgeWebsocket.handleSubscribeSystemLogRequest(edgeId, user, token, request); @@ -301,7 +295,7 @@ private CompletableFuture handleSubscribeSystemLogReques /** * Handles an {@link AddEdgeToUserRequest}. - * + * * @param user the {@link User} * @param request the {@link AddEdgeToUserRequest} * @return the JSON-RPC Success Response Future @@ -309,14 +303,14 @@ private CompletableFuture handleSubscribeSystemLogReques */ private CompletableFuture handleAddEdgeToUserRequest(User user, AddEdgeToUserRequest request) throws OpenemsNamedException { - Edge edge = this.parent.metadata.addEdgeToUser(user, request.getSetupPassword()); + var edge = this.parent.metadata.addEdgeToUser(user, request.getSetupPassword()); return CompletableFuture.completedFuture(new AddEdgeToUserResponse(request.getId(), edge)); } /** * Handles a {@link GetUserInformationRequest}. - * + * * @param user the {@link User} * @param request the {@link GetUserInformationRequest} * @return the JSON-RPC Success Response Future @@ -324,14 +318,14 @@ private CompletableFuture handleAddEdgeToUserRequest(User */ private CompletableFuture handleGetUserInformationRequest(User user, GetUserInformationRequest request) throws OpenemsNamedException { - Map userInformation = this.parent.metadata.getUserInformation(user); + var userInformation = this.parent.metadata.getUserInformation(user); return CompletableFuture.completedFuture(new GetUserInformationResponse(request.getId(), userInformation)); } /** * Handles a {@link SetUserInformationRequest}. - * + * * @param user the {@link User}r * @param request the {@link SetUserInformationRequest} * @return the JSON-RPC Success Response Future @@ -346,7 +340,7 @@ private CompletableFuture handleSetUserInformatio /** * Handles a {@link SubmitSetupProtocolRequest}. - * + * * @param user the {@link User}r * @param request the {@link SubmitSetupProtocolRequest} * @return the JSON-RPC Success Response Future @@ -356,7 +350,7 @@ private CompletableFuture handleSubmitSetupProtoc SubmitSetupProtocolRequest request) throws OpenemsNamedException { int protocolId = this.parent.metadata.submitSetupProtocol(user, request.getJsonObject()); - JsonObject response = JsonUtils.buildJsonObject() // + var response = JsonUtils.buildJsonObject() // .addProperty("setupProtocolId", protocolId) // .build(); @@ -365,7 +359,7 @@ private CompletableFuture handleSubmitSetupProtoc /** * Handles a {@link GetSetupProtocolRequest}. - * + * * @param user the {@link User}r * @param request the {@link GetSetupProtocolRequest} * @return the JSON-RPC Success Response Future @@ -373,14 +367,14 @@ private CompletableFuture handleSubmitSetupProtoc */ private CompletableFuture handleGetSetupProtocolRequest(User user, GetSetupProtocolRequest request) throws OpenemsNamedException { - byte[] protocol = this.parent.metadata.getSetupProtocol(user, request.getSetupProtocolId()); + var protocol = this.parent.metadata.getSetupProtocol(user, request.getSetupProtocolId()); return CompletableFuture.completedFuture(new Base64PayloadResponse(request.getId(), protocol)); } /** * Handles a {@link UpdateUserLanguageRequest}. - * + * * @param user the {@link User}r * @param request the {@link UpdateUserLanguageRequest} * @return the JSON-RPC Success Response Future diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/SubscribedChannelsWorker.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/SubscribedChannelsWorker.java index 5775876d818..f796773f6f0 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/SubscribedChannelsWorker.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/SubscribedChannelsWorker.java @@ -1,7 +1,5 @@ package io.openems.backend.uiwebsocket.impl; -import java.util.Optional; - import com.google.gson.JsonElement; import com.google.gson.JsonNull; @@ -27,8 +25,8 @@ protected JsonElement getChannelValue(ChannelAddress channelAddress) { return JsonNull.INSTANCE; } - Optional channelCacheValue = this.parent.timeData.getChannelValue(this.edgeId, channelAddress); - return channelCacheValue.orElse(JsonNull.INSTANCE); + var channelCacheValueOpt = this.parent.timeData.getChannelValue(this.edgeId, channelAddress); + return channelCacheValueOpt.orElse(JsonNull.INSTANCE); } @Override diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/UiWebsocketImpl.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/UiWebsocketImpl.java index 0b495964c45..d2ddc354036 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/UiWebsocketImpl.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/UiWebsocketImpl.java @@ -1,10 +1,8 @@ package io.openems.backend.uiwebsocket.impl; import java.util.ArrayList; -import java.util.Collection; import java.util.Iterator; import java.util.List; -import java.util.Optional; import java.util.concurrent.CompletableFuture; import org.java_websocket.WebSocket; @@ -20,7 +18,6 @@ import io.openems.backend.common.edgewebsocket.EdgeWebsocket; import io.openems.backend.common.jsonrpc.JsonRpcRequestHandler; import io.openems.backend.common.metadata.Metadata; -import io.openems.backend.common.metadata.User; import io.openems.backend.common.timedata.Timedata; import io.openems.backend.common.uiwebsocket.UiWebsocket; import io.openems.common.exceptions.OpenemsError; @@ -28,7 +25,6 @@ import io.openems.common.jsonrpc.base.JsonrpcNotification; import io.openems.common.jsonrpc.base.JsonrpcRequest; import io.openems.common.jsonrpc.base.JsonrpcResponseSuccess; -import io.openems.common.session.Role; @Designate(ocd = Config.class, factory = false) @Component(// @@ -61,24 +57,24 @@ public UiWebsocketImpl() { private Config config; private final Runnable startServerWhenMetadataIsInitialized = () -> { - this.startServer(config.port(), config.poolSize(), config.debugMode()); + this.startServer(this.config.port(), this.config.poolSize(), this.config.debugMode()); }; @Activate - void activate(Config config) { + private void activate(Config config) { this.config = config; this.metadata.addOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); } @Deactivate - void deactivate() { + private void deactivate() { this.metadata.removeOnIsInitializedListener(this.startServerWhenMetadataIsInitialized); this.stopServer(); } /** * Create and start new server. - * + * * @param port the port * @param poolSize number of threads dedicated to handle the tasks * @param debugMode activate a regular debug log about the state of the tasks @@ -109,20 +105,20 @@ protected void logWarn(Logger log, String message) { @Override public void send(String token, JsonrpcNotification notification) throws OpenemsNamedException { - WsData wsData = this.getWsDataForTokenOrError(token); + var wsData = this.getWsDataForTokenOrError(token); wsData.send(notification); } @Override public CompletableFuture send(String token, JsonrpcRequest request) throws OpenemsNamedException { - WsData wsData = this.getWsDataForTokenOrError(token); + var wsData = this.getWsDataForTokenOrError(token); return wsData.send(request); } @Override public void sendBroadcast(String edgeId, JsonrpcNotification notification) throws OpenemsNamedException { - List wsDatas = this.getWsDatasForEdgeId(edgeId); + var wsDatas = this.getWsDatasForEdgeId(edgeId); OpenemsNamedException exception = null; for (WsData wsData : wsDatas) { try { @@ -138,17 +134,17 @@ public void sendBroadcast(String edgeId, JsonrpcNotification notification) throw /** * Gets the WebSocket connection attachment for a UI token. - * + * * @param token the UI token * @return the WsData * @throws OpenemsNamedException if there is no connection with this token */ private WsData getWsDataForTokenOrError(String token) throws OpenemsNamedException { - Collection connections = this.server.getConnections(); + var connections = this.server.getConnections(); for (Iterator iter = connections.iterator(); iter.hasNext();) { - WebSocket websocket = iter.next(); + var websocket = iter.next(); WsData wsData = websocket.getAttachment(); - Optional thisToken = wsData.getToken(); + var thisToken = wsData.getToken(); if (thisToken.isPresent() && thisToken.get().equals(token)) { return wsData; } @@ -159,25 +155,25 @@ private WsData getWsDataForTokenOrError(String token) throws OpenemsNamedExcepti /** * Gets the WebSocket connection attachments of all connections accessing an * Edge-ID. - * + * * @param edgeId the Edge-ID * @return the WsDatas; empty list if there are none */ private List getWsDatasForEdgeId(String edgeId) { - List result = new ArrayList<>(); - Collection connections = this.server.getConnections(); + var result = new ArrayList(); + var connections = this.server.getConnections(); for (Iterator iter = connections.iterator(); iter.hasNext();) { - WebSocket websocket = iter.next(); + var websocket = iter.next(); WsData wsData = websocket.getAttachment(); // get attachment User-ID - Optional userIdOpt = wsData.getUserId(); + var userIdOpt = wsData.getUserId(); if (userIdOpt.isPresent()) { - String userId = userIdOpt.get(); + var userId = userIdOpt.get(); // get User for User-ID - Optional userOpt = this.metadata.getUser(userId); + var userOpt = this.metadata.getUser(userId); if (userOpt.isPresent()) { - User user = userOpt.get(); - Optional edgeRoleOpt = user.getRole(edgeId); + var user = userOpt.get(); + var edgeRoleOpt = user.getRole(edgeId); if (edgeRoleOpt.isPresent()) { // User has access to this Edge-ID result.add(wsData); diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WebsocketServer.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WebsocketServer.java index 0399ee91943..6911661174c 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WebsocketServer.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WebsocketServer.java @@ -49,7 +49,7 @@ protected OnRequest getOnRequest() { @Override public OnNotification getOnNotification() { - return onNotification; + return this.onNotification; } @Override @@ -65,7 +65,7 @@ protected OnClose getOnClose() { @Override protected JsonrpcMessage handleNonJsonrpcMessage(String stringMessage, OpenemsNamedException lastException) throws OpenemsNamedException { - log.info("UiWs. handleNonJsonrpcMessage: " + stringMessage); + this.log.info("UiWs. handleNonJsonrpcMessage: " + stringMessage); throw new OpenemsException("UiWs. handleNonJsonrpcMessage", lastException); } diff --git a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WsData.java b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WsData.java index 318a3e0370d..649cd089586 100644 --- a/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WsData.java +++ b/io.openems.backend.uiwebsocket/src/io/openems/backend/uiwebsocket/impl/WsData.java @@ -51,7 +51,7 @@ public synchronized void unsetUserId() { /** * Gets the authenticated User-ID. - * + * * @return the User-ID or Optional.Empty if the User was not authenticated. */ public synchronized Optional getUserId() { @@ -60,16 +60,15 @@ public synchronized Optional getUserId() { /** * Gets the authenticated User. - * + * * @param metadata the Metadata service * @return the User or Optional.Empty if the User was not authenticated or it is * not available from Metadata service */ public synchronized Optional getUser(Metadata metadata) { - Optional userId = this.getUserId(); - if (userId.isPresent()) { - Optional user = metadata.getUser(userId.get()); - return user; + var userIdOpt = this.getUserId(); + if (userIdOpt.isPresent()) { + return metadata.getUser(userIdOpt.get()); } return Optional.empty(); } @@ -80,7 +79,7 @@ public synchronized void setToken(String token) { /** * Gets the Login-Token. - * + * * @return the Login-Token */ public Optional getToken() { @@ -96,26 +95,26 @@ public void unsetToken() { /** * Gets the token or throws an error if no token was set. - * + * * @return the token * @throws OpenemsNamedException if no token has been set */ public String assertToken() throws OpenemsNamedException { - Optional token = this.token; - if (token.isPresent()) { - return token.get(); + var tokenOpt = this.token; + if (tokenOpt.isPresent()) { + return tokenOpt.get(); } throw OpenemsError.BACKEND_UI_TOKEN_MISSING.exception(); } /** * Gets the SubscribedChannelsWorker to take care of subscribe to CurrentData. - * + * * @param edgeId the Edge-ID * @return the SubscribedChannelsWorker */ public synchronized SubscribedChannelsWorker getSubscribedChannelsWorker(String edgeId) { - SubscribedChannelsWorker result = this.subscribedChannelsWorkers.get(edgeId); + var result = this.subscribedChannelsWorkers.get(edgeId); if (result == null) { result = new SubscribedChannelsWorker(this.parent.parent, edgeId, this); this.subscribedChannelsWorkers.put(edgeId, result);