* { * "jsonrpc": "2.0", @@ -34,20 +34,27 @@ public class EdgesCurrentDataNotification extends JsonrpcNotification { private final Tablevalues = 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 TreeSetchannels = 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 TreeSetchannels = 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, MapedgeInfos) { @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, MapuserInformation) @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 extends JsonrpcResponseSuccess> handleRequest(String context, User user, JsonrpcRequest request) throws OpenemsNamedException { switch (request.getMethod()) { @@ -99,7 +97,7 @@ public CompletableFuture extends JsonrpcResponseSuccess> 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