Skip to content

Commit

Permalink
Backend-Code clean-up and modernization for Java 11 (#1692)
Browse files Browse the repository at this point in the history
- Clean-up code using Eclipse IDE
- Apply checkstyle
- Use Java 11 features - mainly the `var` keyword, where appropriate
  • Loading branch information
sfeilmeier authored Jan 7, 2022
1 parent edb287e commit b7a03f7
Show file tree
Hide file tree
Showing 82 changed files with 1,027 additions and 955 deletions.
2 changes: 1 addition & 1 deletion cnf/checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
<message key="name.invalidPattern" value="Parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="LambdaParameterName">
<property name="format" value="^[a-z]([a-z0-9][a-zA-Z0-9]*)?$"/>
<property name="format" value="^[a-z][a-zA-Z0-9]*?$"/>
<message key="name.invalidPattern" value="Lambda parameter name ''{0}'' must match pattern ''{1}''."/>
</module>
<module name="CatchParameterName">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package io.openems.backend.application;

import java.io.IOException;
import java.util.Dictionary;
import java.util.Hashtable;

import org.osgi.service.cm.Configuration;
Expand All @@ -23,22 +22,22 @@ public class BackendApp {
private final Logger log = LoggerFactory.getLogger(BackendApp.class);

@Reference
ConfigurationAdmin cm;
private ConfigurationAdmin cm;

@Activate
void activate() {
String message = "OpenEMS Backend version [" + OpenemsConstants.VERSION + "] started";
String line = Strings.repeat("=", message.length());
log.info(line);
log.info(message);
log.info(line);
private void activate() {
final var message = "OpenEMS Backend version [" + OpenemsConstants.VERSION + "] started";
final var line = Strings.repeat("=", message.length());
this.log.info(line);
this.log.info(message);
this.log.info(line);

Configuration config;
try {
config = cm.getConfiguration("org.ops4j.pax.logging", null);
Dictionary<String, Object> properties = config.getProperties();
config = this.cm.getConfiguration("org.ops4j.pax.logging", null);
final var properties = config.getProperties();
if (properties == null || properties.isEmpty() || properties.get("log4j2.rootLogger.level") == null) {
Hashtable<String, Object> log4j = new Hashtable<>();
final var log4j = new Hashtable<String, Object>();
log4j.put("log4j2.appender.console.type", "Console");
log4j.put("log4j2.appender.console.name", "console");
log4j.put("log4j2.appender.console.layout.type", "PatternLayout");
Expand All @@ -58,8 +57,8 @@ void activate() {
}

@Deactivate
void deactivate() {
log.info("Deactivate BackendApp");
private void deactivate() {
this.log.info("Deactivate BackendApp");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@ public B2bRest() {
}

@Activate
void activate(Config config) throws OpenemsException {
private void activate(Config config) throws OpenemsException {
this.startServer(config.port());
}

@Deactivate
void deactivate() {
private void deactivate() {
this.stopServer();
}

/**
* Create and start new server.
*
*
* @param port the port
* @throws OpenemsException on error
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,15 @@ public void handle(String target, Request baseRequest, HttpServletRequest reques

/**
* Authenticate a user.
*
*
* @param request the HttpServletRequest
* @return the {@link User}
* @throws OpenemsNamedException on error
*/
private User authenticate(HttpServletRequest request) throws OpenemsNamedException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
StringTokenizer st = new StringTokenizer(authHeader);
var st = new StringTokenizer(authHeader);
if (st.hasMoreTokens()) {
String basic = st.nextToken();
if (basic.equalsIgnoreCase("Basic")) {
Expand All @@ -92,8 +92,8 @@ private User authenticate(HttpServletRequest request) throws OpenemsNamedExcepti
}
int p = credentials.indexOf(":");
if (p != -1) {
String username = credentials.substring(0, p).trim();
String password = credentials.substring(p + 1).trim();
var username = credentials.substring(0, p).trim();
var password = credentials.substring(p + 1).trim();
// authenticate using username & password
return this.parent.metadata.authenticate(username, password);
}
Expand Down Expand Up @@ -140,7 +140,7 @@ private void sendErrorResponse(Request baseRequest, HttpServletResponse response

/**
* Parses a Request to JSON.
*
*
* @param baseRequest the Request
* @return the {@link JsonObject}
* @throws OpenemsException on error
Expand All @@ -159,15 +159,15 @@ private static JsonObject parseJson(Request baseRequest) throws OpenemsException

/**
* Handles an http request to 'jsonrpc' endpoint.
*
*
* @param user the {@link User}
* @param baseRequest the {@link Request}
* @param httpRequest the {@link HttpServletRequest}
* @param httpResponse the {@link HttpServletResponse}
*/
private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
UUID requestId = new UUID(0L, 0L); /* dummy UUID */
var requestId = new UUID(0L, 0L); /* dummy UUID */
try {
// call handler methods
if (!httpRequest.getMethod().equals("POST")) {
Expand All @@ -176,17 +176,17 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht
}

// parse json and add "jsonrpc" and "id" properties if missing
JsonObject json = RestHandler.parseJson(baseRequest);
var json = RestHandler.parseJson(baseRequest);
if (!json.has("jsonrpc")) {
json.addProperty("jsonrpc", "2.0");
}
if (!json.has("id")) {
json.addProperty("id", UUID.randomUUID().toString());
}
if (json.has("params")) {
JsonObject params = JsonUtils.getAsJsonObject(json, "params");
var params = JsonUtils.getAsJsonObject(json, "params");
if (params.has("payload")) {
JsonObject payload = JsonUtils.getAsJsonObject(params, "payload");
var payload = JsonUtils.getAsJsonObject(params, "payload");
if (!payload.has("jsonrpc")) {
payload.addProperty("jsonrpc", "2.0");
}
Expand All @@ -198,11 +198,11 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht
json.add("params", params);
}
// parse JSON-RPC Request
JsonrpcMessage message = JsonrpcMessage.from(json);
var message = JsonrpcMessage.from(json);
if (!(message instanceof JsonrpcRequest)) {
throw new OpenemsException("Only JSON-RPC Request is supported here.");
}
JsonrpcRequest request = (JsonrpcRequest) message;
var request = (JsonrpcRequest) message;

// handle the request
CompletableFuture<? extends JsonrpcResponseSuccess> responseFuture = this.parent.jsonRpcRequestHandler
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,25 +52,25 @@ public B2bWebsocket() {
private Config config;

private final Runnable startServerWhenMetadataIsInitialized = () -> {
this.startServer(config.port(), config.poolSize(), config.debugMode());
this.startServer(this.config.port(), this.config.poolSize(), this.config.debugMode());
};

@Activate
void activate(Config config) {
private void activate(Config config) {
this.config = config;
this.metadata.addOnIsInitializedListener(this.startServerWhenMetadataIsInitialized);
}

@Deactivate
void deactivate() {
private void deactivate() {
ThreadPoolUtils.shutdownAndAwaitTermination(this.executor, 5);
this.metadata.removeOnIsInitializedListener(this.startServerWhenMetadataIsInitialized);
this.stopServer();
}

/**
* 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
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package io.openems.backend.b2bwebsocket;

import java.util.Optional;

import org.java_websocket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.openems.backend.common.metadata.User;
import io.openems.common.exceptions.OpenemsException;

public class OnClose implements io.openems.common.websocket.OnClose {
Expand All @@ -21,7 +18,7 @@ public OnClose(B2bWebsocket parent) {
@Override
public void run(WebSocket ws, int code, String reason, boolean remote) throws OpenemsException {
WsData wsData = ws.getAttachment();
Optional<User> user = wsData.getUserOpt();
var user = wsData.getUserOpt();
if (user.isPresent()) {
this.parent.logInfo(this.log, "User [" + user.get().getName() + "] closed connection");
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,21 @@ public void run(WebSocket ws, JsonObject handshake) throws OpenemsNamedException
try {
// Read "Authorization" header for Simple HTTP authentication. Source:
// https://stackoverflow.com/questions/16000517/how-to-get-password-from-http-basic-authentication
final String authorization = JsonUtils.getAsString(handshake, "Authorization");
final var authorization = JsonUtils.getAsString(handshake, "Authorization");
if (authorization == null || !authorization.toLowerCase().startsWith("basic")) {
throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception();
}

String base64Credentials = authorization.substring("Basic".length()).trim();
byte[] credDecoded = Base64.getDecoder().decode(base64Credentials);
String credentials = new String(credDecoded, StandardCharsets.UTF_8);
var credentials = new String(credDecoded, StandardCharsets.UTF_8);
// credentials = username:password
final String[] values = credentials.split(":", 2);
final var values = credentials.split(":", 2);
if (values.length != 2) {
throw OpenemsError.COMMON_AUTHENTICATION_FAILED.exception();
}
String username = values[0];
String password = values[1];
var username = values[0];
var password = values[1];
User user = this.parent.metadata.authenticate(username, password);

WsData wsData = ws.getAttachment();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public OnRequest(B2bWebsocket parent) {
public CompletableFuture<? extends JsonrpcResponseSuccess> run(WebSocket ws, JsonrpcRequest request)
throws OpenemsException, OpenemsNamedException {
WsData wsData = ws.getAttachment();
User user = wsData.getUserWithTimeout(5, TimeUnit.SECONDS);
var user = wsData.getUserWithTimeout(5, TimeUnit.SECONDS);

switch (request.getMethod()) {

Expand All @@ -42,7 +42,7 @@ public CompletableFuture<? extends JsonrpcResponseSuccess> run(WebSocket ws, Jso

/**
* Handles a {@link SubscribeEdgesChannelsRequest}.
*
*
* @param wsData the WebSocket attachment
* @param user the {@link User}
* @param messageId the JSON-RPC Message-ID
Expand All @@ -58,7 +58,7 @@ private CompletableFuture<GenericJsonrpcResponseSuccess> handleSubscribeEdgesCha
}

// activate SubscribedChannelsWorker
SubscribedEdgesChannelsWorker worker = wsData.getSubscribedChannelsWorker();
var worker = wsData.getSubscribedChannelsWorker();
worker.handleSubscribeEdgesChannelsRequest(request);

// JSON-RPC response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.java_websocket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -15,7 +14,6 @@

import io.openems.backend.b2bwebsocket.jsonrpc.notification.EdgesCurrentDataNotification;
import io.openems.backend.b2bwebsocket.jsonrpc.request.SubscribeEdgesChannelsRequest;
import io.openems.backend.common.metadata.User;
import io.openems.common.exceptions.OpenemsError.OpenemsNamedException;
import io.openems.common.session.Role;
import io.openems.common.types.ChannelAddress;
Expand Down Expand Up @@ -54,7 +52,7 @@ public SubscribedEdgesChannelsWorker(B2bWebsocket parent, WsData wsData) {

/**
* Applies a SubscribeChannelsRequest.
*
*
* @param request the SubscribeEdgesChannelsRequest
*/
public synchronized void handleSubscribeEdgesChannelsRequest(SubscribeEdgesChannelsRequest request) {
Expand All @@ -66,7 +64,7 @@ public synchronized void handleSubscribeEdgesChannelsRequest(SubscribeEdgesChann

/**
* Updates the Subscription data.
*
*
* @param edgeIds Set of Edge-IDs
* @param channels Set of ChannelAddresses
*/
Expand All @@ -91,7 +89,7 @@ private synchronized void updateSubscription(Set<String> edgeIds, Set<ChannelAdd
/*
* This task is executed regularly. Sends data to Websocket.
*/
WebSocket ws = this.wsData.getWebsocket();
var ws = this.wsData.getWebsocket();
if (ws == null || !ws.isOpen()) {
// disconnected; stop worker
this.dispose();
Expand All @@ -104,14 +102,17 @@ private synchronized void updateSubscription(Set<String> edgeIds, Set<ChannelAdd
this.log.warn("Unable to send SubscribedChannels: " + e.getMessage());
}

}, 0, UPDATE_INTERVAL_IN_SECONDS, TimeUnit.SECONDS));
}, 0, SubscribedEdgesChannelsWorker.UPDATE_INTERVAL_IN_SECONDS, TimeUnit.SECONDS));
}
}

/**
* Dispose and deactivate this worker.
*/
public void dispose() {
// unsubscribe regular task
if (this.futureOpt.isPresent()) {
futureOpt.get().cancel(true);
this.futureOpt.get().cancel(true);
}
}

Expand All @@ -122,8 +123,8 @@ public void dispose() {
* @throws OpenemsNamedException on error
*/
private EdgesCurrentDataNotification getCurrentDataNotification() throws OpenemsNamedException {
EdgesCurrentDataNotification result = new EdgesCurrentDataNotification();
User user = this.wsData.getUserWithTimeout(5, TimeUnit.SECONDS);
var result = new EdgesCurrentDataNotification();
var user = this.wsData.getUserWithTimeout(5, TimeUnit.SECONDS);

for (String edgeId : this.edgeIds) {
// assure read permissions of this User for this Edge.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ protected OnRequest getOnRequest() {

@Override
public OnNotification getOnNotification() {
return onNotification;
return this.onNotification;
}

@Override
Expand Down
Loading

0 comments on commit b7a03f7

Please sign in to comment.