Skip to content

Commit

Permalink
Code Cleanup for Java 21
Browse files Browse the repository at this point in the history
- Migrate Switch-Case-Expressions to Switch-Case-Statements
- UI: Fix FactoryId `Controller.IO.Heating.Room`
- General code cleanup (using Eclipse "Clean up" tool)

Co-authored-by: Michael Grill <[email protected]>
Reviewed-by: Michael Grill <[email protected]>
  • Loading branch information
sfeilmeier and michaelgrill committed Jan 20, 2025
1 parent 3666813 commit 7f3de2a
Show file tree
Hide file tree
Showing 200 changed files with 1,993 additions and 2,855 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -197,11 +197,9 @@ private void handleJsonRpc(User user, Request baseRequest, HttpServletRequest ht
}
// parse JSON-RPC Request
var message = JsonrpcMessage.from(json);
if (!(message instanceof JsonrpcRequest)) {
if (!(message instanceof JsonrpcRequest request)) {
throw new OpenemsException("Only JSON-RPC Request is supported here.");
}
var request = (JsonrpcRequest) message;

// handle the request
CompletableFuture<? extends JsonrpcResponseSuccess> responseFuture = this.parent.jsonRpcRequestHandler
.handleRequest(this.parent.getName(), user, request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,8 @@ public static String activeStateChannelsToString(
var states = new HashMap<Level, HashMultimap<String, Channel>>();
for (Entry<ChannelAddress, Channel> entry : activeStateChannels.entrySet()) {
var detail = entry.getValue().getDetail();
if (detail instanceof ChannelDetailState) {
var level = ((ChannelDetailState) detail).getLevel();
if (detail instanceof ChannelDetailState cds) {
var level = cds.getLevel();
var channelsByComponent = states.get(level);
if (channelsByComponent == null) {
channelsByComponent = HashMultimap.create();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,26 +98,21 @@ private void updateConfig(Config config) {
@Override
public CompletableFuture<? extends JsonrpcResponseSuccess> handleRequest(String context, User user,
JsonrpcRequest request) throws OpenemsNamedException {
switch (request.getMethod()) {

case EdgeRpcRequest.METHOD:
return this.edgeRpcRequestHandler.handleRequest(user, request.getId(), EdgeRpcRequest.from(request));

case GetEdgesStatusRequest.METHOD:
return this.handleGetEdgesStatusRequest(user, request.getId(), GetEdgesStatusRequest.from(request));

case GetEdgesChannelsValuesRequest.METHOD:
return this.handleGetEdgesChannelsValuesRequest(user, request.getId(),
return switch (request.getMethod()) {
case EdgeRpcRequest.METHOD //
-> this.edgeRpcRequestHandler.handleRequest(user, request.getId(), EdgeRpcRequest.from(request));
case GetEdgesStatusRequest.METHOD //
-> this.handleGetEdgesStatusRequest(user, request.getId(), GetEdgesStatusRequest.from(request));
case GetEdgesChannelsValuesRequest.METHOD //
-> this.handleGetEdgesChannelsValuesRequest(user, request.getId(),
GetEdgesChannelsValuesRequest.from(request));

case SetGridConnScheduleRequest.METHOD:
return this.handleSetGridConnScheduleRequest(user, request.getId(),
SetGridConnScheduleRequest.from(request));

default:
case SetGridConnScheduleRequest.METHOD //
-> this.handleSetGridConnScheduleRequest(user, request.getId(), SetGridConnScheduleRequest.from(request));
default -> {
this.logWarn(context, "Unhandled Request: " + request);
throw OpenemsError.JSONRPC_UNHANDLED_METHOD.exception(request.getMethod());
}
};
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.openems.backend.edgewebsocket;

import static io.openems.common.utils.FunctionUtils.doNothing;

import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

Expand Down Expand Up @@ -118,14 +120,17 @@ private void handleDataNotification(AbstractDataNotification message, WsData wsD
var edgeId = wsData.assertEdgeId(message);

try {
// TODO java 21 switch case with type
if (message instanceof TimestampedDataNotification timestampNotification) {
switch (message) {
case TimestampedDataNotification timestampNotification -> {
wsData.edgeCache.updateCurrentData(timestampNotification);
this.parent.timedataManager.write(edgeId, timestampNotification);
} else if (message instanceof AggregatedDataNotification aggregatedNotification) {
}
case AggregatedDataNotification aggregatedNotification -> {
wsData.edgeCache.updateAggregatedData(aggregatedNotification);
this.parent.timedataManager.write(edgeId, aggregatedNotification);
}
case ResendDataNotification resendNotification -> doNothing(); // handled in handleResendDataNotification()
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,50 +320,45 @@ public void handleEvent(Event event) {
var reader = new EventReader(event);

switch (event.getTopic()) {
case Edge.Events.ON_SET_ONLINE: {
case Edge.Events.ON_SET_ONLINE -> {
var edgeId = reader.getString(Edge.Events.OnSetOnline.EDGE_ID);
var isOnline = reader.getBoolean(Edge.Events.OnSetOnline.IS_ONLINE);

this.getEdge(edgeId).ifPresent(edge -> {
if (edge instanceof MyEdge) {
if (edge instanceof MyEdge myEdge) {
// Set OpenEMS Is Connected in Odoo/Postgres
this.postgresHandler.getPeriodicWriteWorker().onSetOnline((MyEdge) edge, isOnline);
this.postgresHandler.getPeriodicWriteWorker().onSetOnline(myEdge, isOnline);
}
});
}
break;

case Edge.Events.ON_SET_CONFIG:
this.onSetConfigEvent(reader);
break;
case Edge.Events.ON_SET_CONFIG //
-> this.onSetConfigEvent(reader);

case Edge.Events.ON_SET_VERSION: {
case Edge.Events.ON_SET_VERSION -> {
var edge = (MyEdge) reader.getProperty(Edge.Events.OnSetVersion.EDGE);
var version = (SemanticVersion) reader.getProperty(Edge.Events.OnSetVersion.VERSION);

// Set Version in Odoo
this.odooHandler.writeEdge(edge, new FieldValue<>(Field.EdgeDevice.OPENEMS_VERSION, version.toString()));
}
break;

case Edge.Events.ON_SET_LASTMESSAGE: {
case Edge.Events.ON_SET_LASTMESSAGE -> {
var edge = (MyEdge) reader.getProperty(Edge.Events.OnSetLastmessage.EDGE);
// Set LastMessage timestamp in Odoo/Postgres
this.postgresHandler.getPeriodicWriteWorker().onLastMessage(edge);
}
break;

case Edge.Events.ON_SET_SUM_STATE: {
case Edge.Events.ON_SET_SUM_STATE -> {
var edgeId = reader.getString(Edge.Events.OnSetSumState.EDGE_ID);
var sumState = (Level) reader.getProperty(Edge.Events.OnSetSumState.SUM_STATE);

var edge = this.edgeCache.getEdgeFromEdgeId(edgeId);
// Set Sum-State in Odoo/Postgres
this.postgresHandler.getPeriodicWriteWorker().onSetSumState(edge, sumState);
}
break;

case Edge.Events.ON_SET_PRODUCTTYPE: {
case Edge.Events.ON_SET_PRODUCTTYPE -> {
var edge = (MyEdge) reader.getProperty(Edge.Events.OnSetProducttype.EDGE);
var producttype = reader.getString(Edge.Events.OnSetProducttype.PRODUCTTYPE);
// Set Producttype in Odoo/Postgres
Expand All @@ -376,8 +371,6 @@ public void handleEvent(Event event) {
}
});
}
break;

}
}

Expand Down Expand Up @@ -568,10 +561,11 @@ public List<SumStateAlertingSetting> getSumStateAlertingSettings(String edgeId)
@Override
public void setUserAlertingSettings(User user, String edgeId, List<UserAlertingSettings> settings)
throws OpenemsException {
if (user instanceof MyUser odooUser) {
this.odooHandler.setUserAlertingSettings(odooUser, edgeId, settings);
} else {
throw new OpenemsException("User information is from foreign source!!");
switch (user) {
case MyUser odooUser //
-> this.odooHandler.setUserAlertingSettings(odooUser, edgeId, settings);
default //
-> throw new OpenemsException("User information is from foreign source!!");
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package io.openems.backend.metadata.odoo.odoo;

import static io.openems.common.utils.StringUtils.toShortString;

import com.google.gson.JsonElement;

import io.openems.backend.metadata.odoo.Field;
import io.openems.common.utils.StringUtils;

public class FieldValue<T> {
private final Field field;
Expand All @@ -24,14 +25,14 @@ public T getValue() {

@Override
public String toString() {
String string;
if (this.value instanceof JsonElement) {
string = StringUtils.toShortString((JsonElement) this.value, 100);
} else if (this.value instanceof String) {
string = StringUtils.toShortString((String) this.value, 100);
} else {
string = this.value.toString();
}
var string = switch (this.value) {
case JsonElement je //
-> toShortString(je, 100);
case String s //
-> toShortString(s, 100);
default //
-> this.value.toString();
};
string = string.replace("\n", "");
return this.field.id() + ":" + string;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -925,8 +925,8 @@ public Optional<String> getSerialNumberForEdge(Edge edge) {
Field.EdgeDevice.STOCK_PRODUCTION_LOT_ID);

var serialNumber = serialNumberField.get(Field.EdgeDevice.STOCK_PRODUCTION_LOT_ID.id());
if (serialNumber instanceof Object[] && ((Object[]) serialNumber).length > 1) {
return getAsOptional(((Object[]) serialNumber)[1], String.class);
if (serialNumber instanceof Object[] sns && sns.length > 1) {
return getAsOptional(sns[1], String.class);
}
return Optional.empty();
} catch (OpenemsException ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,10 +536,10 @@ protected static <T extends Object> Optional<T> getAsOptional(Object object, Cla
* @return the odoo reference id or empty {@link Optional}
*/
protected static Optional<Integer> getOdooReferenceId(Object object) {
if (object instanceof Object[] odooReference) {
if (odooReference.length > 0 && odooReference[0] instanceof Integer) {
return Optional.of((Integer) odooReference[0]);
}
if (object instanceof Object[] odooReference //
&& odooReference.length > 0 //
&& odooReference[0] instanceof Integer i) {
return Optional.of(i);
}

return Optional.empty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
* @see <a href="https://www.jsonrpc.org/specification">JSON-RPC
* specification</a>
*/
public abstract class AbstractJsonrpcRequest extends JsonrpcMessage {
public abstract sealed class AbstractJsonrpcRequest extends JsonrpcMessage permits JsonrpcRequest, JsonrpcNotification {

private final String method;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
* @see <a href="https://www.jsonrpc.org/specification">JSON-RPC
* specification</a>
*/
public abstract class JsonrpcMessage {
public abstract sealed class JsonrpcMessage permits AbstractJsonrpcRequest, JsonrpcResponse {

public static final String JSONRPC_VERSION = "2.0";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* @see <a href="https://www.jsonrpc.org/specification#notification">JSON-RPC
* specification</a>
*/
public abstract class JsonrpcNotification extends AbstractJsonrpcRequest {
public abstract non-sealed class JsonrpcNotification extends AbstractJsonrpcRequest {

public JsonrpcNotification(String method) {
super(method);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
* @see <a href="https://www.jsonrpc.org/specification#request_object">JSON-RPC
* specification</a>
*/
public abstract class JsonrpcRequest extends AbstractJsonrpcRequest {
public abstract non-sealed class JsonrpcRequest extends AbstractJsonrpcRequest {

public static final int DEFAULT_TIMEOUT_SECONDS = 60;
public static final int NO_TIMEOUT = -1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
* @see <a href="https://www.jsonrpc.org/specification#response_object">JSON-RPC
* specification</a>
*/
public abstract class JsonrpcResponse extends JsonrpcMessage {
public abstract non-sealed class JsonrpcResponse extends JsonrpcMessage {

/**
* Parses a JSON String to a {@link JsonrpcResponse}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,10 @@ public abstract class JsonrpcResponseSuccess extends JsonrpcResponse {
* @throws OpenemsNamedException if it was not a Success Response
*/
public static JsonrpcResponseSuccess from(JsonObject j) throws OpenemsNamedException {
var response = JsonrpcResponse.from(j);
if (!(response instanceof JsonrpcResponseSuccess)) {
throw OpenemsError.GENERIC.exception("Expected a JSON-RPC Success Response");
}
return (JsonrpcResponseSuccess) response;
return switch (JsonrpcResponse.from(j)) {
case JsonrpcResponseSuccess r -> r;
default -> throw OpenemsError.GENERIC.exception("Expected a JSON-RPC Success Response");
};
}

public JsonrpcResponseSuccess(UUID id) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
* }
* </pre>
*/
// TODO change to sealed class
public abstract class AbstractDataNotification extends JsonrpcNotification {
public abstract sealed class AbstractDataNotification extends JsonrpcNotification
permits TimestampedDataNotification, AggregatedDataNotification, ResendDataNotification {

private final TreeBasedTable<Long, String, JsonElement> data;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
* }
* </pre>
*/
public class AggregatedDataNotification extends AbstractDataNotification {
public final class AggregatedDataNotification extends AbstractDataNotification {

public static final String METHOD = "aggregatedData";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
* }
* </pre>
*/
public class ResendDataNotification extends AbstractDataNotification {
public final class ResendDataNotification extends AbstractDataNotification {

public static final String METHOD = "resendData";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
* }
* </pre>
*/
public class TimestampedDataNotification extends AbstractDataNotification {
public final class TimestampedDataNotification extends AbstractDataNotification {

public static final String METHOD = "timestampedData";

Expand Down
18 changes: 7 additions & 11 deletions io.openems.common/src/io/openems/common/session/Role.java
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,13 @@ public int getLevel() {
* @return the Role
*/
public static Role getRole(String name) {
switch (name.toLowerCase()) {
case "admin":
return ADMIN;
case "installer":
return INSTALLER;
case "owner":
return OWNER;
case "guest":
default:
return GUEST;
}
return switch (name.toLowerCase()) {
case "admin" -> ADMIN;
case "installer" -> INSTALLER;
case "owner" -> OWNER;
case "guest" -> GUEST;
default -> GUEST;
};
}

/**
Expand Down
15 changes: 6 additions & 9 deletions io.openems.common/src/io/openems/common/timedata/Resolution.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,12 @@ public ChronoUnit getUnit() {
* @return Date without offset
*/
public ZonedDateTime revertInfluxDbOffset(ZonedDateTime date) {
switch (this.unit) {
case DAYS:
case MONTHS:
return date.minus(this.value, this.unit);
case MINUTES:
case HOURS:
default:
return date;
}
return switch (this.unit) {
case DAYS, MONTHS //
-> date.minus(this.value, this.unit);
default // MINUTES, HOURS, etc.
-> date;
};
}

/**
Expand Down
Loading

0 comments on commit 7f3de2a

Please sign in to comment.