Skip to content

Commit

Permalink
build: migrate to Java 17 (#410)
Browse files Browse the repository at this point in the history
* feat: set Java 17 as source/target language level
* refactor: use pattern matching for instanceof #java17
* ci: upgrade spotbugs-maven-plugin, don't execute analysis in parallel
* refactor: use Stream.toList() #java17
* refactor: use switch expressions #java17
* refactor: use record for some inner classes #java17
* refactor: use text blocks #java17
* ci: update docker image for builds on eclipse CI
* refactor: use pattern matching for instanceof and Stream.toList #java17
* build: use JDK 17 in github action
* clean(sns): remove unnecessary default case
  • Loading branch information
kschrab authored Sep 24, 2024
1 parent b7616c2 commit b12b3e1
Show file tree
Hide file tree
Showing 95 changed files with 448 additions and 687 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ jobs:

steps:
- uses: actions/checkout@v2
- name: Set up JDK 11
- name: Set up JDK 17
uses: actions/setup-java@v1
with:
java-version: 11
java-version: 17
- name: Build with Maven
run: mvn -B package --file pom.xml
4 changes: 2 additions & 2 deletions Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ kind: Pod
spec:
containers:
- name: maven-sumo
image: eclipsemosaic/mosaic-ci:jdk11-sumo-1.20.0
image: eclipsemosaic/mosaic-ci:jdk17-sumo-1.20.0
command:
- cat
tty: true
Expand Down Expand Up @@ -112,7 +112,7 @@ spec:
stage('Analysis') {
steps {
container('maven-sumo') {
sh 'mvn site -T 4'
sh 'mvn site'
}
}

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ For further questions we are available via [email protected]
For a successful build you need the following software to be installed:

* **Maven 3.1.x** or higher.
* **Java 11**, 17, or 21 - We recommend using the [Adoptium OpenJDK (aka Eclipse Temurin)](https://adoptium.net/?variant=openjdk11).
* **Java 17**, or 21 - We recommend using the [Adoptium OpenJDK (aka Eclipse Temurin)](https://adoptium.net/?variant=openjdk17).
* **SUMO 1.20.0** - Older versions > 1.2.0 are most probably supported, but not tested. The environment variable `SUMO_HOME` should be configured properly.

## Build
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ private void driveBack(DriveBackEvent event) {
*/
@Override
public void processEvent(Event event) {
if (event instanceof DriveBackEvent) {
driveBack((DriveBackEvent) event);
if (event instanceof DriveBackEvent driveBackEvent) {
driveBack(driveBackEvent);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ public void onStartup() {
public void onMessageReceived(ReceivedV2xMessage receivedV2xMessage) {
V2xMessage msg = receivedV2xMessage.getMessage();

if (msg instanceof Cam) {
if (msg instanceof Cam cam) {
try {
getLog().infoSimTime(this, "CAM message arrived, userTaggedValue: {}",
CamSendingApp.DEFAULT_OBJECT_SERIALIZATION
.fromBytes(((Cam) msg).getUserTaggedValue(), this.getClass().getClassLoader())
.fromBytes(cam.getUserTaggedValue(), this.getClass().getClassLoader())
);
} catch (IOException | ClassNotFoundException e) {
getLog().error("An error occurred", e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@ public void onShutdown() {
@Override
public void processEvent(Event event) throws Exception {
Object resource = event.getResource();
if (resource instanceof String) {
String message = (String) resource;
if (resource instanceof String message) {
getLog().infoSimTime(this, "Received message: \"{}\"", message);
}
getLog().info("Wanted speed from config equals " + this.config.fooInteger);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ public void onStartup() {
public void processEvent(final Event event) throws Exception {
getLog().infoSimTime(this, "Event has been triggered and is being processed by the processEvent method that is declared in EventProcessor interface!");

if (event.getResource() instanceof String) {
String message = (String)event.getResource();
if (event.getResource() instanceof String message) {
getLog().infoSimTime(this, "Received message: \"{}\"", message);
}
}
Expand All @@ -59,8 +58,7 @@ public void onShutdown() {
public void mySpecificMethod(Event event) {
getLog().infoSimTime(this, "Event has been triggered and is being processed by a specific method!");

if (event.getResource() instanceof String) {
String message = (String)event.getResource();
if (event.getResource() instanceof String message) {
getLog().infoSimTime(this, "Received message: \"{}\"", message);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ private void sample() {
@Override
public void processEvent(final Event event) throws Exception {
Object resource = event.getResource();
if (resource instanceof String) {
String command = (String) resource;

if (resource instanceof String command) {
switch (command) {
case "start":
startThread();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ public class AdditionalProcessingApp extends AbstractApplication<VehicleOperatin
@Override
public void processEvent(final Event event) {
Object resource = event.getResource();
if (resource instanceof String) {
String myMessage = (String) resource;
if (resource instanceof String myMessage) {
getLog().infoSimTime(this, "Received message: \"{}\"", myMessage);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@ public void onVehicleUpdated(@Nullable VehicleData previousVehicleData, @Nonnull
@Override
public void processEvent(final Event event) {
Object resource = event.getResource();
if (resource instanceof String) {
String myMessage = (String) resource;
if (resource instanceof String myMessage) {
getLog().infoSimTime(this, "Received message: \"{}\"", myMessage);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ public class AdditionalReceivingApp extends AbstractApplication<VehicleOperating

@Override
public void onInteractionReceived(ApplicationInteraction applicationInteraction) {
if (applicationInteraction instanceof MyInteraction) {
final MyInteraction myMessage = (MyInteraction) applicationInteraction;
getLog().infoSimTime(this, "AdditionalReceivingApp received MyInteraction: {}", myMessage.getContent());
if (applicationInteraction instanceof MyInteraction myInteraction) {
getLog().infoSimTime(this, "AdditionalReceivingApp received MyInteraction: {}", myInteraction.getContent());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,8 @@ public void onVehicleUpdated(@Nullable VehicleData previousVehicleData, @Nonnull

@Override
public void onInteractionReceived(ApplicationInteraction applicationInteraction) {
if (applicationInteraction instanceof MyInteraction) {
final MyInteraction myMessage = (MyInteraction) applicationInteraction;
getLog().infoSimTime(this, "MosaicInteractionHandlingApp received MyInteraction: {}", myMessage.getContent());
if (applicationInteraction instanceof MyInteraction myInteraction) {
getLog().infoSimTime(this, "MosaicInteractionHandlingApp received MyInteraction: {}", myInteraction.getContent());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,7 @@ public class SumoTraciInteractionApp extends AbstractApplication<VehicleOperatin
/**
* Convenience container to retrieve info from sumo speed response.
*/
static class SpeedResponse {
protected final String vehicleId;
protected final double speed;

public SpeedResponse(String vehicleId, double speed) {
this.vehicleId = vehicleId;
this.speed = speed;
}
}
record SpeedResponse(String vehicleId, double speed) {}

/**
* The "meat" of this application. Here a byte array is assembled
Expand Down Expand Up @@ -107,8 +99,8 @@ public void onSumoTraciResponded(SumoTraciResult sumoTraciResult) {
getLog().infoSimTime(
this,
"Received TraCI message from Sumo. Speed of vehicle {} is {} m/s",
speedResponse.vehicleId,
speedResponse.speed
speedResponse.vehicleId(),
speedResponse.speed()
);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

Expand Down Expand Up @@ -102,7 +101,7 @@ public void processEvent(Event event) throws Exception {
private void perceiveVehicles() {
List<VehicleObject> perceivedVehicles = getOs().getPerceptionModule().getPerceivedVehicles();
getLog().infoSimTime(this, "Perceived vehicles: {}",
perceivedVehicles.stream().map(VehicleObject::getId).collect(Collectors.toList()));
perceivedVehicles.stream().map(VehicleObject::getId).toList());

colorVehicles(perceivedVehicles, previouslyPerceivedVehicles, Color.GREEN); // set color to perceived
colorVehicles(previouslyPerceivedVehicles, perceivedVehicles, Color.YELLOW); // reset color of no longer perceived
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ public class EventProcessingApp extends AbstractApplication<VehicleOperatingSyst
public void processEvent(Event event) {
Object resource = event.getResource();
if (resource != null) {
if (resource instanceof IntraVehicleMsg) {
final IntraVehicleMsg message = (IntraVehicleMsg) resource;
if (resource instanceof IntraVehicleMsg message) {
// message was passed from another app on the same vehicle
if (message.getOrigin().equals(getOs().getId())) {
getLog().infoSimTime(this, "Received message from another application: {}", message.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,19 @@ private void setRed() {

@Override
public void onMessageReceived(ReceivedV2xMessage receivedV2xMessage) {
if (!(receivedV2xMessage.getMessage() instanceof GreenWaveMsg)) {
if (!(receivedV2xMessage.getMessage() instanceof GreenWaveMsg greenWaveMsg)) {
return;
}
getLog().infoSimTime(this, "Received GreenWaveMsg");

if (!((GreenWaveMsg) receivedV2xMessage.getMessage()).getMessage().equals(SECRET)) {
if (!greenWaveMsg.getMessage().equals(SECRET)) {
return;
}
getLog().infoSimTime(this, "Received correct passphrase: {}", SECRET);

Validate.notNull(receivedV2xMessage.getMessage().getRouting().getSource().getSourcePosition(),
Validate.notNull(greenWaveMsg.getRouting().getSource().getSourcePosition(),
"The source position of the sender cannot be null");
if (!(receivedV2xMessage.getMessage().getRouting().getSource().getSourcePosition()
if (!(greenWaveMsg.getRouting().getSource().getSourcePosition()
.distanceTo(getOs().getPosition()) <= MIN_DISTANCE)) {
getLog().infoSimTime(this, "Vehicle that sent message is too far away.");
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public void onMessageReceived(ReceivedV2xMessage receivedV2xMessage) {
final V2xMessage msg = receivedV2xMessage.getMessage();

// Only DEN Messages are handled
if (!(msg instanceof Denm)) {
if (!(msg instanceof Denm denm)) {
getLog().infoSimTime(this, "Ignoring message of type: {}", msg.getSimpleClassName());
return;
}
Expand All @@ -113,7 +113,6 @@ public void onMessageReceived(ReceivedV2xMessage receivedV2xMessage) {
getLog().infoSimTime(this, "Received message from cell from WeatherServer");
}

final Denm denm = (Denm) msg;
getLog().infoSimTime(this, "Processing DEN message");

getLog().debug("Handle Environment Warning Message. Processing...");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;

/**
Expand Down Expand Up @@ -539,11 +538,11 @@ private void process(final TrafficDetectorUpdates trafficDetectorUpdates) {
for (TrafficManagementCenterUnit tmc : UnitSimulator.UnitSimulator.getTmcs().values()) {
final List<InductionLoopInfo> relevantInductionLoops = trafficDetectorUpdates.getUpdatedInductionLoops().stream()
.filter(i -> tmc.getInductionLoopIds().contains(i.getName()))
.collect(Collectors.toList());
.toList();

final List<LaneAreaDetectorInfo> relevantLaneAreaDetectors = trafficDetectorUpdates.getUpdatedLaneAreaDetectors().stream()
.filter(i -> tmc.getLaneAreaIds().contains(i.getName()))
.collect(Collectors.toList());
.toList();

if (!relevantInductionLoops.isEmpty() || !relevantLaneAreaDetectors.isEmpty()) {
// Create new TrafficDetectorUpdates interaction containing only relevant updates
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,8 +335,7 @@ public Path getMainLogDirectory() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
for (Logger logger : context.getLoggerList()) {
Appender<ILoggingEvent> appender = logger.getAppender("ApplicationLog");
if (appender instanceof FileAppender) {
FileAppender<?> fileAppender = ((FileAppender<?>) appender);
if (appender instanceof FileAppender<?> fileAppender) {
return new File(fileAppender.getFile()).toPath().getParent();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,18 +174,18 @@ private void addSimulationUnit(final AbstractSimulationUnit unit) {
allUnits.put(unit.getId(), unit);

// second, put the simulation unit in the specific map
if (unit instanceof ChargingStationUnit) {
chargingStations.put(unit.getId(), (ChargingStationUnit) unit);
} else if (unit instanceof RoadSideUnit) {
roadSideUnits.put(unit.getId(), (RoadSideUnit) unit);
} else if (unit instanceof TrafficLightGroupUnit) {
trafficLights.put(unit.getId(), (TrafficLightGroupUnit) unit);
} else if (unit instanceof TrafficManagementCenterUnit) {
tmcs.put(unit.getId(), (TrafficManagementCenterUnit) unit);
} else if (unit instanceof ServerUnit) {
servers.put(unit.getId(), (ServerUnit) unit);
} else if (unit instanceof VehicleUnit) {
vehicles.put(unit.getId(), (VehicleUnit) unit);
if (unit instanceof ChargingStationUnit chargingStation) {
chargingStations.put(unit.getId(), chargingStation);
} else if (unit instanceof RoadSideUnit roadSideUnit) {
roadSideUnits.put(unit.getId(), roadSideUnit);
} else if (unit instanceof TrafficLightGroupUnit trafficLightGroup) {
trafficLights.put(unit.getId(), trafficLightGroup);
} else if (unit instanceof TrafficManagementCenterUnit tmc) {
tmcs.put(unit.getId(), tmc);
} else if (unit instanceof ServerUnit server) {
servers.put(unit.getId(), server);
} else if (unit instanceof VehicleUnit vehicle) {
vehicles.put(unit.getId(), vehicle);
} else {
throw new RuntimeException(ErrorRegister.UNIT_SIMULATOR_UnknownSimulationUnitToPutInMap.toString());
}
Expand Down Expand Up @@ -459,10 +459,10 @@ private void doSensorRegistration(final long time, final String id) {
public void processEvent(Event event) {
final Object resource = event.getResource();

if (resource instanceof RemoveVehicles) {
removeVehicles((RemoveVehicles) resource);
} else if (resource instanceof StartApplications) {
startApplications((StartApplications) resource);
if (resource instanceof RemoveVehicles removeVehicles) {
removeVehicles(removeVehicles);
} else if (resource instanceof StartApplications startApplications) {
startApplications(startApplications);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,11 @@ public final boolean preProcessEvent(final Event event) {
return false;
}

if (event instanceof InterceptedEvent) {
/*
* This should be an intercepted event from an application of this simulation unit.
* The operating system intercept all events from the applications and can watch into the events and maybe forward the event.
*/
final InterceptedEvent interceptedEvent = (InterceptedEvent) event;
/*
* This should be an intercepted event from an application of this simulation unit.
* The operating system intercept all events from the applications and can watch into the events and maybe forward the event.
*/
if (event instanceof InterceptedEvent interceptedEvent) {
// cast the resource of the intercepted event, it must be an event
final Event originalEvent = interceptedEvent.getOriginalEvent();
if (osLog.isTraceEnabled()) {
Expand Down Expand Up @@ -198,11 +197,11 @@ public final boolean preProcessEvent(final Event event) {

return true;
} else {
if (resource instanceof ReceivedV2xMessage) {
processReceivedV2xMessage((ReceivedV2xMessage) resource);
if (resource instanceof ReceivedV2xMessage receivedMessage) {
processReceivedV2xMessage(receivedMessage);
return true;
} else if (resource instanceof V2xMessageAcknowledgement) {
processV2xMessageAcknowledgement((V2xMessageAcknowledgement) resource);
} else if (resource instanceof V2xMessageAcknowledgement v2xAck) {
processV2xMessageAcknowledgement(v2xAck);
return true;
} else {
return false;
Expand Down Expand Up @@ -284,8 +283,8 @@ public final void loadApplications(List<String> applicationClassNames) {
try {
// check if defined operating system is matching
Type mySuperclass = newApplication.getClass().getGenericSuperclass();
if (mySuperclass instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) mySuperclass).getActualTypeArguments();
if (mySuperclass instanceof ParameterizedType parameterizedType) {
Type[] typeArgs = parameterizedType.getActualTypeArguments();
Type type = typeArgs[typeArgs.length - 1];
boolean typeAssignableFromOs = Class.forName(StringUtils.substringAfter(type.toString(), "interface").trim())
.isAssignableFrom(operatingSystemCheck);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ public void processEvent(@Nonnull final Event event) throws Exception {
throw new RuntimeException(ErrorRegister.CHARGING_STATION_NoEventResource.toString());
}

if (resource instanceof ChargingStationData) {
updateChargingStation((ChargingStationData) resource);
if (resource instanceof ChargingStationData data) {
updateChargingStation(data);
} else {
getOsLog().error("Unknown event resource: {}", event);
throw new RuntimeException(ErrorRegister.CHARGING_STATION_UnknownEvent.toString());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ private void onVehicleChargingDenial(final VehicleChargingDenial vehicleCharging

@Override
protected boolean handleEventResource(Object resource, long eventType) {
if (resource instanceof BatteryData) {
updateBatteryData((BatteryData) resource);
if (resource instanceof BatteryData data) {
updateBatteryData(data);
return true;
}

if (resource instanceof VehicleChargingDenial) {
onVehicleChargingDenial((VehicleChargingDenial) resource);
if (resource instanceof VehicleChargingDenial chargingDenial) {
onVehicleChargingDenial(chargingDenial);
return true;
}

Expand Down
Loading

0 comments on commit b12b3e1

Please sign in to comment.