From f97e402ca6cb4c77b442619cc41e0e538ec0cd8c Mon Sep 17 00:00:00 2001 From: hantsy Date: Mon, 6 Jan 2025 16:59:59 +0800 Subject: [PATCH] chore: clean codes --- pom.xml | 17 -- .../internal/DefaultBookingService.java | 6 +- .../DefaultCargoInspectionService.java | 6 +- .../internal/DefaultHandlingEventService.java | 6 +- .../domain/model/cargo/Delivery.java | 2 +- .../domain/model/cargo/Itinerary.java | 160 ++++++----- .../model/cargo/RouteSpecification.java | 128 ++++++--- .../domain/model/cargo/TrackingId.java | 6 +- .../handling/UnknownVoyageException.java | 2 +- .../domain/model/voyage/VoyageNumber.java | 84 +++--- ...SResourcesSetup.java => JMSResources.java} | 15 +- .../messaging/jms/JmsApplicationEvents.java | 6 +- ...abaseSetup.java => DatabaseResources.java} | 10 +- .../persistence/jpa/JpaCargoRepository.java | 3 +- .../jpa/JpaHandlingEventRepository.java | 4 +- .../jpa/JpaLocationRepository.java | 3 +- .../persistence/jpa/JpaVoyageRepository.java | 3 +- .../routing/ExternalRoutingService.java | 7 - .../client/GraphTraversalResourceClient.java | 12 - .../assembler/CargoRouteDtoAssembler.java | 2 +- .../assembler/CargoStatusDtoAssembler.java | 2 +- .../ItineraryCandidateDtoAssembler.java | 2 +- .../assembler/TrackingEventsDtoAssembler.java | 2 +- .../booking/rest/CargoMonitoringService.java | 4 +- .../socket/RealtimeCargoTrackingService.java | 16 +- .../handling/file/EventItemWriter.java | 15 +- .../handling/mobile/EventLogger.java | 3 +- .../handling/rest/HandlingReportService.java | 4 +- .../web/CargoTrackingViewAdapter.java | 6 +- .../org/eclipse/cargotracker/Deployments.java | 8 +- .../application/ApplicationEventsTest.java | 3 +- .../domain/model/cargo/CargoTest.java | 4 +- .../persistence/jpa/CargoRepositoryTest.java | 272 +++++++++--------- .../jpa/CarrierMovementRepositoryTest.java | 5 +- .../jpa/HandlingEventRepositoryTest.java | 3 +- .../booking/socket/CargoInspectedStub.java | 47 +-- .../RealtimeCargoTrackingServiceTest.java | 6 +- .../interfaces/booking/socket/TestClient.java | 3 +- .../rest/HandlingReportServiceTest.java | 2 +- 39 files changed, 450 insertions(+), 439 deletions(-) rename src/main/java/org/eclipse/cargotracker/infrastructure/messaging/{JMSResourcesSetup.java => JMSResources.java} (83%) rename src/main/java/org/eclipse/cargotracker/infrastructure/persistence/{DatabaseSetup.java => DatabaseResources.java} (91%) diff --git a/pom.xml b/pom.xml index 6cb1d099b..ca46e72a4 100644 --- a/pom.xml +++ b/pom.xml @@ -321,23 +321,6 @@ - - com.spotify.fmt - fmt-maven-plugin - 2.25 - - true - - - - - validate - - check - - - - org.apache.maven.plugins maven-war-plugin diff --git a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultBookingService.java b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultBookingService.java index d4ac5f719..445ade594 100644 --- a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultBookingService.java +++ b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultBookingService.java @@ -1,7 +1,8 @@ package org.eclipse.cargotracker.application.internal; -import jakarta.ejb.Stateless; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import org.eclipse.cargotracker.application.BookingService; import org.eclipse.cargotracker.domain.model.cargo.*; @@ -16,7 +17,8 @@ import java.util.logging.Level; import java.util.logging.Logger; -@Stateless +@ApplicationScoped +@Transactional public class DefaultBookingService implements BookingService { @Inject private CargoRepository cargoRepository; diff --git a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultCargoInspectionService.java b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultCargoInspectionService.java index db50d00c9..080b3e7a5 100644 --- a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultCargoInspectionService.java +++ b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultCargoInspectionService.java @@ -1,8 +1,9 @@ package org.eclipse.cargotracker.application.internal; -import jakarta.ejb.Stateless; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Event; import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import org.eclipse.cargotracker.application.ApplicationEvents; import org.eclipse.cargotracker.application.CargoInspectionService; @@ -16,7 +17,8 @@ import java.util.logging.Level; import java.util.logging.Logger; -@Stateless +@ApplicationScoped +@Transactional public class DefaultCargoInspectionService implements CargoInspectionService { private static final Logger LOGGER = diff --git a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultHandlingEventService.java b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultHandlingEventService.java index 47ee32240..e276430ac 100644 --- a/src/main/java/org/eclipse/cargotracker/application/internal/DefaultHandlingEventService.java +++ b/src/main/java/org/eclipse/cargotracker/application/internal/DefaultHandlingEventService.java @@ -1,7 +1,8 @@ package org.eclipse.cargotracker.application.internal; -import jakarta.ejb.Stateless; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; +import jakarta.transaction.Transactional; import org.eclipse.cargotracker.application.ApplicationEvents; import org.eclipse.cargotracker.application.HandlingEventService; @@ -17,7 +18,8 @@ import java.util.logging.Level; import java.util.logging.Logger; -@Stateless +@ApplicationScoped +@Transactional public class DefaultHandlingEventService implements HandlingEventService { private static final Logger LOGGER = diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Delivery.java b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Delivery.java index 851462eee..2c462931c 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Delivery.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Delivery.java @@ -245,7 +245,7 @@ private boolean calculateMisdirectionStatus(Itinerary itinerary) { private LocalDateTime calculateEta(Itinerary itinerary) { if (onTrack()) { - return itinerary.getFinalArrivalDate(); + return itinerary.finalArrivalDate(); } else { return ETA_UNKOWN; } diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Itinerary.java b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Itinerary.java index 13ce4374c..3bf4d1948 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Itinerary.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/Itinerary.java @@ -1,7 +1,5 @@ package org.eclipse.cargotracker.domain.model.cargo; -import static java.util.Collections.*; - import jakarta.persistence.*; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.Size; @@ -10,52 +8,59 @@ import org.eclipse.cargotracker.domain.model.handling.HandlingEvent; import org.eclipse.cargotracker.domain.model.location.Location; +import java.io.Serializable; import java.time.LocalDateTime; +import java.util.Collections; import java.util.List; import java.util.Objects; @Embeddable -public record Itinerary( - // TODO [Clean Code] Look into why cascade delete doesn't work. - // Hibernate issue: - // Changes applied according to WildFly/Hibernate requirements. - // The `orphanRemoval = true` option will causes a `all-delete-orphan` exception under - // WildFly/Hibernate. - // (There is a famous lazy initialization exception you could encounter WildFly/Hibernate. - // The `fetch = FetchType.EAGER` fixes the Hibernate lazy initialization exception - // but maybe cause bad performance. A good practice is accessing the one-to-many relations - // in a session/tx boundary) - // - // @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "cargo_id") - // TODO [Clean Code] Index this is in leg_index - // Hibernate issue: - // Hibernate does not persist the order of the list element when saving into db. - // The `OrderColumn` will persist the position of list elements in db. - @OrderColumn(name = "leg_index") - // The `OrderBy` only ensures the order of list elements in memory. Only - // `@OrderBy("loadTime")` - // is added some tests are still failed under WildFly/Hibernate. - // @OrderBy("loadTime") - @Size(min = 1) - @NotEmpty(message = "Legs must not be empty") - List legs) { +public class Itinerary implements Serializable { // Null object pattern. - public static final Itinerary EMPTY_ITINERARY = new Itinerary(emptyList()); - - public Itinerary { + public static final Itinerary EMPTY_ITINERARY = new Itinerary(); + private static final long serialVersionUID = 1L; + + // TODO [Clean Code] Look into why cascade delete doesn't work. + // Hibernate issue: + // Changes applied according to WildFly/Hibernate requirements. + // The `orphanRemoval = true` option will causes a `all-delete-orphan` exception under + // WildFly/Hibernate. + // (There is a famous lazy initialization exception you could encounter WildFly/Hibernate. + // The `fetch = FetchType.EAGER` fixes the Hibernate lazy initialization exception + // but maybe cause bad performance. A good practice is accessing the one-to-many relations + // in a session/tx boundary) + // + // @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "cargo_id") + // TODO [Clean Code] Index this is in leg_index + // Hibernate issue: + // Hibernate does not persist the order of the list element when saving into db. + // The `OrderColumn` will persist the position of list elements in db. + @OrderColumn(name = "leg_index") + // The `OrderBy` only ensures the order of list elements in memory. Only `@OrderBy("loadTime")` + // is added some tests are still failed under WildFly/Hibernate. + // @OrderBy("loadTime") + @Size(min = 1) + @NotEmpty(message = "Legs must not be empty") + private List legs = Collections.emptyList(); + + public Itinerary() { // Nothing to initialize. + } + + public Itinerary(List legs) { Validate.notEmpty(legs); Validate.noNullElements(legs); + + this.legs = legs; } - // - // public List legs() { - // // this.legs.sort(Comparator.comparing(Leg::getLoadTime)); - // return Collections.unmodifiableList(this.legs); - // } + public List legs() { + // this.legs.sort(Comparator.comparing(Leg::getLoadTime)); + return Collections.unmodifiableList(this.legs); + } /** Test if the given handling event is expected when executing this itinerary. */ public boolean isExpected(HandlingEvent event) { @@ -86,7 +91,7 @@ public boolean isExpected(HandlingEvent event) { leg.getUnloadLocation().equals(event.getLocation()) && leg.getVoyage().equals(event.getVoyage())); case CLAIM -> { - Leg leg = getLastLeg(); + Leg leg = lastLeg(); yield leg.getUnloadLocation().equals(event.getLocation()); } case CUSTOMS -> true; @@ -94,7 +99,7 @@ public boolean isExpected(HandlingEvent event) { }; } - Location getInitialDepartureLocation() { + Location initialDepartureLocation() { if (legs.isEmpty()) { return Location.UNKNOWN; } else { @@ -102,19 +107,19 @@ Location getInitialDepartureLocation() { } } - Location getFinalArrivalLocation() { + Location finalArrivalLocation() { if (legs.isEmpty()) { return Location.UNKNOWN; } else { - return getLastLeg().getUnloadLocation(); + return lastLeg().getUnloadLocation(); } } /** * @return Date when cargo arrives at final destination. */ - LocalDateTime getFinalArrivalDate() { - Leg lastLeg = getLastLeg(); + LocalDateTime finalArrivalDate() { + Leg lastLeg = lastLeg(); if (lastLeg == null) { return LocalDateTime.MAX; @@ -126,7 +131,7 @@ LocalDateTime getFinalArrivalDate() { /** * @return The last leg on the itinerary. */ - Leg getLastLeg() { + Leg lastLeg() { if (legs.isEmpty()) { return null; } else { @@ -143,39 +148,38 @@ private boolean sameValueAs(Itinerary other) { return other != null && Objects.equals(List.copyOf(this.legs), List.copyOf(other.legs)); } - // @Override - // public boolean equals(Object o) { - // if (this == o) { - // return true; - // } - // - // // if (o == null || getClass() != o.getClass()) { - // // return false; - // // } - // // - // // - // https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java - // // Hibernate issue: - // // `getClass() != o.getClass()` will fail if comparing the objects in different - // // transactions/sessions. - // // The generated dynamic proxies are always different classes. - // if (o == null || !(o instanceof Itinerary)) { - // return false; - // } - // - // Itinerary itinerary = (Itinerary) o; - // - // return sameValueAs(itinerary); - // } - // - // @Override - // public int hashCode() { - // // return legs.hashCode(); - // return Objects.hashCode(List.copyOf(legs)); - // } - // - // @Override - // public String toString() { - // return "Itinerary{" + "legs=" + legs + '}'; - // }Itinerary + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + + // if (o == null || getClass() != o.getClass()) { + // return false; + // } + // + // https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java + // Hibernate issue: + // `getClass() != o.getClass()` will fail if comparing the objects in different + // transactions/sessions. + // The generated dynamic proxies are always different classes. + if (o == null || !(o instanceof Itinerary)) { + return false; + } + + Itinerary itinerary = (Itinerary) o; + + return sameValueAs(itinerary); + } + + @Override + public int hashCode() { + // return legs.hashCode(); + return Objects.hashCode(List.copyOf(legs)); + } + + @Override + public String toString() { + return "Itinerary{" + "legs=" + legs + '}'; + } } diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/RouteSpecification.java b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/RouteSpecification.java index a6b14e218..3318b6b8d 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/RouteSpecification.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/RouteSpecification.java @@ -8,40 +8,74 @@ import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; import org.eclipse.cargotracker.domain.model.location.Location; import org.eclipse.cargotracker.domain.shared.Specification; +import java.io.Serializable; import java.time.LocalDate; /** * Route specification. Describes where a cargo origin and destination is, and the arrival deadline. - * - * @param origin origin location - can't be the same as the destination - * @param destination destination location - can't be the same as the origin - * @param arrivalDeadline arrival deadline */ @Embeddable -public record RouteSpecification( - @ManyToOne @JoinColumn(name = "spec_origin_id") Location origin, - @ManyToOne @JoinColumn(name = "spec_destination_id") Location destination, - @Column(name = "spec_arrival_deadline") @NotNull LocalDate arrivalDeadline) - implements Specification { +public class RouteSpecification implements Specification, Serializable { - public RouteSpecification { + private static final long serialVersionUID = 1L; + + // private static final Logger LOGGER = Logger.getLogger(RouteSpecification.class.getName()); + + @ManyToOne + @JoinColumn(name = "spec_origin_id") + private Location origin; + + @ManyToOne + @JoinColumn(name = "spec_destination_id") + private Location destination; + + // @Temporal(TemporalType.DATE) + @Column(name = "spec_arrival_deadline") + @NotNull + private LocalDate arrivalDeadline; + + public RouteSpecification() {} + + /** + * @param origin origin location - can't be the same as the destination + * @param destination destination location - can't be the same as the origin + * @param arrivalDeadline arrival deadline + */ + public RouteSpecification(Location origin, Location destination, LocalDate arrivalDeadline) { Validate.notNull(origin, "Origin is required"); Validate.notNull(destination, "Destination is required"); Validate.notNull(arrivalDeadline, "Arrival deadline is required"); Validate.isTrue( !origin.sameIdentityAs(destination), "Origin and destination can't be the same: " + origin); + + this.origin = origin; + this.destination = destination; + this.arrivalDeadline = arrivalDeadline; + } + + public Location origin() { + return origin; + } + + public Location destination() { + return destination; + } + + public LocalDate arrivalDeadline() { + return arrivalDeadline; } @Override public boolean isSatisfiedBy(Itinerary itinerary) { return itinerary != null - && origin().sameIdentityAs(itinerary.getInitialDepartureLocation()) - && destination().sameIdentityAs(itinerary.getFinalArrivalLocation()) - && arrivalDeadline().isAfter(itinerary.getFinalArrivalDate().toLocalDate()); + && origin().sameIdentityAs(itinerary.initialDepartureLocation()) + && destination().sameIdentityAs(itinerary.finalArrivalLocation()) + && arrivalDeadline().isAfter(itinerary.finalArrivalDate().toLocalDate()); } private boolean sameValueAs(RouteSpecification other) { @@ -53,38 +87,38 @@ && new EqualsBuilder() .isEquals(); } - // @Override - // public boolean equals(Object o) { - // if (this == o) { - // return true; - // } - // if (o == null || getClass() != o.getClass()) { - // return false; - // } - // - // RouteSpecification that = (RouteSpecification) o; - // - // return sameValueAs(that); - // } - // - // @Override - // public int hashCode() { - // return new HashCodeBuilder() - // .append(this.origin) - // .append(this.destination) - // .append(this.arrivalDeadline) - // .toHashCode(); - // } - // - // @Override - // public String toString() { - // return "RouteSpecification{" - // + "origin=" - // + origin - // + ", destination=" - // + destination - // + ", arrivalDeadline=" - // + arrivalDeadline - // + '}'; - // } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + RouteSpecification that = (RouteSpecification) o; + + return sameValueAs(that); + } + + @Override + public int hashCode() { + return new HashCodeBuilder() + .append(this.origin) + .append(this.destination) + .append(this.arrivalDeadline) + .toHashCode(); + } + + @Override + public String toString() { + return "RouteSpecification{" + + "origin=" + + origin + + ", destination=" + + destination + + ", arrivalDeadline=" + + arrivalDeadline + + '}'; + } } diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/TrackingId.java b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/TrackingId.java index 5c1ca7f8d..5b645b5dd 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/cargo/TrackingId.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/cargo/TrackingId.java @@ -4,12 +4,16 @@ import jakarta.persistence.Embeddable; import jakarta.validation.constraints.NotEmpty; +import java.io.Serializable; + /** Uniquely identifies a particular cargo. Automatically generated by the application. */ @Embeddable public record TrackingId( @NotEmpty(message = "Tracking ID cannot be empty.") @Column(name = "tracking_id", unique = true, updatable = false) - String id) { + String id) + implements Serializable { + private static final long serialVersionUID = 1L; // @Override // public boolean equals(Object o) { diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/handling/UnknownVoyageException.java b/src/main/java/org/eclipse/cargotracker/domain/model/handling/UnknownVoyageException.java index 3e585bcc3..311dd3362 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/handling/UnknownVoyageException.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/handling/UnknownVoyageException.java @@ -14,6 +14,6 @@ public UnknownVoyageException(VoyageNumber voyageNumber) { @Override public String getMessage() { - return "No voyage with number " + voyageNumber.getIdString() + " exists in the system"; + return "No voyage with number " + voyageNumber.number() + " exists in the system"; } } diff --git a/src/main/java/org/eclipse/cargotracker/domain/model/voyage/VoyageNumber.java b/src/main/java/org/eclipse/cargotracker/domain/model/voyage/VoyageNumber.java index a9df4387d..1ccf720a3 100644 --- a/src/main/java/org/eclipse/cargotracker/domain/model/voyage/VoyageNumber.java +++ b/src/main/java/org/eclipse/cargotracker/domain/model/voyage/VoyageNumber.java @@ -2,63 +2,51 @@ import jakarta.persistence.Column; import jakarta.persistence.Embeddable; -import jakarta.validation.constraints.NotEmpty; - -import org.apache.commons.lang3.Validate; +import jakarta.validation.constraints.NotBlank; import java.io.Serializable; @Embeddable -public class VoyageNumber implements Serializable { - +public record VoyageNumber( + @Column(name = "voyage_number") @NotBlank(message = "Voyage number cannot be blank") + String number) + implements Serializable { private static final long serialVersionUID = 1L; - @Column(name = "voyage_number") - @NotEmpty(message = "Voyage number cannot be empty") - private String number; - - public VoyageNumber() { - // Nothing to initialize. - } - - public VoyageNumber(String number) { - Validate.notNull(number, "Voyage number is required"); - - this.number = number; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null) { - return false; - } - if (!(o instanceof VoyageNumber)) { - return false; - } - - VoyageNumber other = (VoyageNumber) o; - - return sameValueAs(other); - } - - @Override - public int hashCode() { - return number.hashCode(); - } + // public VoyageNumber { + // // Nothing to initialize. + // Validate.notNull(number, "Voyage number is required"); + // } + + // + // @Override + // public boolean equals(Object o) { + // if (this == o) { + // return true; + // } + // if (o == null) { + // return false; + // } + // if (!(o instanceof VoyageNumber)) { + // return false; + // } + // + // VoyageNumber other = (VoyageNumber) o; + // + // return sameValueAs(other); + // } + // + // @Override + // public int hashCode() { + // return number.hashCode(); + // } boolean sameValueAs(VoyageNumber other) { return other != null && this.number.equals(other.number); } - @Override - public String toString() { - return number; - } - - public String getIdString() { - return number; - } + // @Override + // public String toString() { + // return number; + // } } diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResourcesSetup.java b/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResources.java similarity index 83% rename from src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResourcesSetup.java rename to src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResources.java index 9d6dd66d6..73b52bb4f 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResourcesSetup.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/JMSResources.java @@ -2,8 +2,7 @@ import jakarta.annotation.PostConstruct; import jakarta.annotation.Resource; -import jakarta.ejb.Singleton; -import jakarta.ejb.Startup; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.jms.ConnectionFactory; import jakarta.jms.JMSDestinationDefinition; @@ -14,33 +13,27 @@ // @JMSConnectionFactoryDefinition(name = "java:comp/env/CargoTrackerCF") @JMSDestinationDefinition( name = "java:app/jms/CargoHandledQueue", - // resourceAdapter = "jmsra", interfaceName = "jakarta.jms.Queue", destinationName = "CargoHandledQueue") @JMSDestinationDefinition( name = "java:app/jms/MisdirectedCargoQueue", - // resourceAdapter = "jmsra", interfaceName = "jakarta.jms.Queue", destinationName = "MisdirectedCargoQueue") @JMSDestinationDefinition( name = "java:app/jms/DeliveredCargoQueue", - // resourceAdapter = "jmsra", interfaceName = "jakarta.jms.Queue", destinationName = "DeliveredCargoQueue") @JMSDestinationDefinition( name = "java:app/jms/RejectedRegistrationAttemptsQueue", - // resourceAdapter = "jmsra", interfaceName = "jakarta.jms.Queue", destinationName = "RejectedRegistrationAttemptsQueue") @JMSDestinationDefinition( name = "java:app/jms/HandlingEventRegistrationAttemptQueue", - // resourceAdapter = "jmsra", interfaceName = "jakarta.jms.Queue", destinationName = "HandlingEventRegistrationAttemptQueue") -@Startup -@Singleton -public class JMSResourcesSetup { - private static final Logger LOGGER = Logger.getLogger(JMSResourcesSetup.class.getName()); +@ApplicationScoped +public class JMSResources { + private static final Logger LOGGER = Logger.getLogger(JMSResources.class.getName()); @Resource(lookup = "java:comp/DefaultJMSConnectionFactory") private ConnectionFactory connectionFactory; diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/jms/JmsApplicationEvents.java b/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/jms/JmsApplicationEvents.java index 5f1452674..a334cda4e 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/jms/JmsApplicationEvents.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/messaging/jms/JmsApplicationEvents.java @@ -25,13 +25,13 @@ public class JmsApplicationEvents implements ApplicationEvents, Serializable { @Resource(lookup = "java:app/jms/CargoHandledQueue") private Destination cargoHandledQueue; - @jakarta.annotation.Resource(lookup = "java:app/jms/MisdirectedCargoQueue") + @Resource(lookup = "java:app/jms/MisdirectedCargoQueue") private Destination misdirectedCargoQueue; - @jakarta.annotation.Resource(lookup = "java:app/jms/DeliveredCargoQueue") + @Resource(lookup = "java:app/jms/DeliveredCargoQueue") private Destination deliveredCargoQueue; - @jakarta.annotation.Resource(lookup = "java:app/jms/HandlingEventRegistrationAttemptQueue") + @Resource(lookup = "java:app/jms/HandlingEventRegistrationAttemptQueue") private Destination handlingEventQueue; @Inject private Logger logger; diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseSetup.java b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseResources.java similarity index 91% rename from src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseSetup.java rename to src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseResources.java index efad7e45e..3749f6caa 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseSetup.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/DatabaseResources.java @@ -3,8 +3,7 @@ import jakarta.annotation.PostConstruct; import jakarta.annotation.Resource; import jakarta.annotation.sql.DataSourceDefinition; -import jakarta.ejb.Singleton; -import jakarta.ejb.Startup; +import jakarta.enterprise.context.ApplicationScoped; import java.sql.Connection; import java.sql.SQLException; @@ -19,10 +18,9 @@ url = "jdbc:postgresql://localhost:5432/cargotracker", user = "user", password = "password") -@Singleton -@Startup -public class DatabaseSetup { - private static final Logger LOGGER = Logger.getLogger(DatabaseSetup.class.getName()); +@ApplicationScoped +public class DatabaseResources { + private static final Logger LOGGER = Logger.getLogger(DatabaseResources.class.getName()); @Resource(lookup = "java:app/jdbc/CargoTrackerDatabase") DataSource dataSource; diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaCargoRepository.java b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaCargoRepository.java index 80df4a8bf..3727176ed 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaCargoRepository.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaCargoRepository.java @@ -4,7 +4,6 @@ import jakarta.inject.Inject; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; -import jakarta.persistence.PersistenceContext; import org.eclipse.cargotracker.domain.model.cargo.Cargo; import org.eclipse.cargotracker.domain.model.cargo.CargoRepository; @@ -23,7 +22,7 @@ public class JpaCargoRepository implements CargoRepository, Serializable { @Inject private Logger logger; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; @Override public Cargo find(TrackingId trackingId) { diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaHandlingEventRepository.java b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaHandlingEventRepository.java index 4a8b51cd9..38bc7d1b1 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaHandlingEventRepository.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaHandlingEventRepository.java @@ -1,8 +1,8 @@ package org.eclipse.cargotracker.infrastructure.persistence.jpa; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; import org.eclipse.cargotracker.domain.model.cargo.TrackingId; import org.eclipse.cargotracker.domain.model.handling.HandlingEvent; @@ -16,7 +16,7 @@ public class JpaHandlingEventRepository implements HandlingEventRepository, Seri private static final long serialVersionUID = 1L; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; @Override public void store(HandlingEvent event) { diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaLocationRepository.java b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaLocationRepository.java index 5f5c8a447..afff74bc9 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaLocationRepository.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaLocationRepository.java @@ -4,7 +4,6 @@ import jakarta.inject.Inject; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; -import jakarta.persistence.PersistenceContext; import org.eclipse.cargotracker.domain.model.location.Location; import org.eclipse.cargotracker.domain.model.location.LocationRepository; @@ -22,7 +21,7 @@ public class JpaLocationRepository implements LocationRepository, Serializable { @Inject Logger logger; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; @Override public Location find(UnLocode unLocode) { diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaVoyageRepository.java b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaVoyageRepository.java index 674d3e9c6..2268656ae 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaVoyageRepository.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/JpaVoyageRepository.java @@ -4,7 +4,6 @@ import jakarta.inject.Inject; import jakarta.persistence.EntityManager; import jakarta.persistence.NoResultException; -import jakarta.persistence.PersistenceContext; import org.eclipse.cargotracker.domain.model.voyage.Voyage; import org.eclipse.cargotracker.domain.model.voyage.VoyageNumber; @@ -22,7 +21,7 @@ public class JpaVoyageRepository implements VoyageRepository, Serializable { @Inject Logger logger; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; @Override public Voyage find(VoyageNumber voyageNumber) { diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/routing/ExternalRoutingService.java b/src/main/java/org/eclipse/cargotracker/infrastructure/routing/ExternalRoutingService.java index 0c8296e3b..8ba83303a 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/routing/ExternalRoutingService.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/routing/ExternalRoutingService.java @@ -49,13 +49,6 @@ public ExternalRoutingService( this.graphTraversalResource = graphTraversalResource; } - // @PostConstruct - // public void init() { - // // this.graphTraversalResource = new GraphTraversalResourceClient(); - // //graphTraversalResource.register(new MoxyJsonFeature()).register(new - // JsonMoxyConfigurationContextResolver()); - // } - @Override public List fetchRoutesForSpecification(RouteSpecification routeSpecification) { // The RouteSpecification is picked apart and adapted to the external API. diff --git a/src/main/java/org/eclipse/cargotracker/infrastructure/routing/client/GraphTraversalResourceClient.java b/src/main/java/org/eclipse/cargotracker/infrastructure/routing/client/GraphTraversalResourceClient.java index eba62fc21..fc4d87f57 100644 --- a/src/main/java/org/eclipse/cargotracker/infrastructure/routing/client/GraphTraversalResourceClient.java +++ b/src/main/java/org/eclipse/cargotracker/infrastructure/routing/client/GraphTraversalResourceClient.java @@ -29,18 +29,6 @@ public class GraphTraversalResourceClient { @PostConstruct public void init() { this.jaxrsClient = ClientBuilder.newClient(); - try { - Class clazz = - Class.forName( - "org.eclipse.cargotracker.infrastructure.routing.client.JacksonObjectMapperContextResolver"); - jaxrsClient.register(clazz); - } catch (ClassNotFoundException e) { - LOGGER.log( - Level.WARNING, - "registering JacksonObjectMapperContextResolver failed: {0}", - e.getMessage()); - LOGGER.log(Level.INFO, "Skip this error for non-WildFly application servers."); - } } @PreDestroy diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoRouteDtoAssembler.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoRouteDtoAssembler.java index 6ed407933..5f1c2661d 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoRouteDtoAssembler.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoRouteDtoAssembler.java @@ -25,7 +25,7 @@ public CargoRouteDto toDto(Cargo cargo) { .forEach( leg -> dto.addLeg( - leg.getVoyage().getVoyageNumber().getIdString(), + leg.getVoyage().getVoyageNumber().number(), locationDtoAssembler.toDto(leg.getLoadLocation()), locationDtoAssembler.toDto(leg.getUnloadLocation()), leg.getLoadTime(), diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoStatusDtoAssembler.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoStatusDtoAssembler.java index 82bcab4f2..6cef085cc 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoStatusDtoAssembler.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/CargoStatusDtoAssembler.java @@ -37,7 +37,7 @@ private String getCargoStatusText(Cargo cargo) { return switch (delivery.transportStatus()) { case IN_PORT -> "In port " + delivery.lastKnownLocation().getName(); case ONBOARD_CARRIER -> - "Onboard voyage " + delivery.currentVoyage().getVoyageNumber().getIdString(); + "Onboard voyage " + delivery.currentVoyage().getVoyageNumber().number(); case CLAIMED -> "Claimed"; case NOT_RECEIVED -> "Not received"; case UNKNOWN -> "Unknown"; diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/ItineraryCandidateDtoAssembler.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/ItineraryCandidateDtoAssembler.java index 71d35d1f6..eb9180a3c 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/ItineraryCandidateDtoAssembler.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/ItineraryCandidateDtoAssembler.java @@ -24,7 +24,7 @@ public RouteCandidateDto toDto(Itinerary itinerary) { protected LegDto toLegDto(Leg leg) { VoyageNumber voyageNumber = leg.getVoyage().getVoyageNumber(); return new LegDto( - voyageNumber.getIdString(), + voyageNumber.number(), locationDtoAssembler.toDto(leg.getLoadLocation()), locationDtoAssembler.toDto(leg.getUnloadLocation()), leg.getLoadTime(), diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/TrackingEventsDtoAssembler.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/TrackingEventsDtoAssembler.java index 2d0c55fb0..f340cd4c9 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/TrackingEventsDtoAssembler.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/facade/internal/assembler/TrackingEventsDtoAssembler.java @@ -35,7 +35,7 @@ private String descriptionFrom(HandlingEvent.Type type, String location, String private String voyageNumberFrom(HandlingEvent handlingEvent) { Voyage voyage = handlingEvent.getVoyage(); - return voyage.getVoyageNumber().getIdString(); + return voyage.getVoyageNumber().number(); } private String locationFrom(HandlingEvent handlingEvent) { diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/rest/CargoMonitoringService.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/rest/CargoMonitoringService.java index 4fe1e5d9b..730a3bad1 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/rest/CargoMonitoringService.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/rest/CargoMonitoringService.java @@ -1,6 +1,6 @@ package org.eclipse.cargotracker.interfaces.booking.rest; -import jakarta.ejb.Stateless; +import jakarta.enterprise.context.RequestScoped; import jakarta.inject.Inject; import jakarta.json.Json; import jakarta.json.JsonArray; @@ -16,7 +16,7 @@ import java.util.List; -@Stateless +@RequestScoped @Path("/cargo") public class CargoMonitoringService { diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingService.java b/src/main/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingService.java index 0fc4daecf..785d5859f 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingService.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingService.java @@ -1,6 +1,6 @@ package org.eclipse.cargotracker.interfaces.booking.socket; -import jakarta.ejb.Singleton; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Observes; import jakarta.inject.Inject; import jakarta.json.Json; @@ -22,26 +22,30 @@ import java.util.logging.Logger; /** WebSocket service for tracking all cargoes in real time. */ -@Singleton +@ApplicationScoped @ServerEndpoint("/tracking") public class RealtimeCargoTrackingService { + private static final Logger LOGGER = + Logger.getLogger(RealtimeCargoTrackingService.class.getName()); private final Set sessions = new HashSet<>(); - @Inject private Logger logger; @OnOpen public void onOpen(final Session session) { // Infinite by default on GlassFish. We need this principally for WebLogic. + LOGGER.log(Level.INFO, "open session: {0}", session.getId()); session.setMaxIdleTimeout(5L * 60 * 1000); sessions.add(session); } @OnClose public void onClose(final Session session) { + LOGGER.log(Level.INFO, "close session: {0}", session.getId()); sessions.remove(session); } public void onCargoInspected(@Observes @CargoInspected Cargo cargo) { + LOGGER.log(Level.INFO, "observers cargo inspected event of cargo: {0}", cargo.getTrackingId()); Writer writer = new StringWriter(); try (JsonGenerator generator = Json.createGenerator(writer)) { @@ -51,17 +55,17 @@ public void onCargoInspected(@Observes @CargoInspected Cargo cargo) { .write("origin", cargo.getOrigin().getName()) .write("destination", cargo.getRouteSpecification().destination().getName()) .write("lastKnownLocation", cargo.getDelivery().lastKnownLocation().getName()) - .write("transportStatus", cargo.getDelivery().transportStatus().toString()) + .write("transportStatus", cargo.getDelivery().transportStatus().name()) .writeEnd(); } String jsonValue = writer.toString(); - + LOGGER.log(Level.INFO, "sending message to client: {0}", jsonValue); for (Session session : sessions) { try { session.getBasicRemote().sendText(jsonValue); } catch (IOException ex) { - logger.log(Level.WARNING, "Unable to publish WebSocket message", ex); + LOGGER.log(Level.WARNING, "Unable to publish WebSocket message", ex); } } } diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/handling/file/EventItemWriter.java b/src/main/java/org/eclipse/cargotracker/interfaces/handling/file/EventItemWriter.java index 48b863866..51504f151 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/handling/file/EventItemWriter.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/handling/file/EventItemWriter.java @@ -43,15 +43,12 @@ public void writeItems(List items) throws Exception { new PrintWriter( new BufferedWriter( new FileWriter( - new File( - jobContext - .getProperties() - .getProperty(ARCHIVE_DIRECTORY) - + "/archive_" - + jobContext.getJobName() - + "_" - + jobContext.getInstanceId() - + ".csv"), + jobContext.getProperties().getProperty(ARCHIVE_DIRECTORY) + + "/archive_" + + jobContext.getJobName() + + "_" + + jobContext.getInstanceId() + + ".csv", true)))) { for (Object item : items) { HandlingEventRegistrationAttempt attempt = (HandlingEventRegistrationAttempt) item; diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/handling/mobile/EventLogger.java b/src/main/java/org/eclipse/cargotracker/interfaces/handling/mobile/EventLogger.java index 9d933af19..d2f68f143 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/handling/mobile/EventLogger.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/handling/mobile/EventLogger.java @@ -142,8 +142,7 @@ public void init() { for (Voyage voyage : voyages) { this.voyages.add( new SelectItem( - voyage.getVoyageNumber().getIdString(), - voyage.getVoyageNumber().getIdString())); + voyage.getVoyageNumber().number(), voyage.getVoyageNumber().number())); } } diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportService.java b/src/main/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportService.java index a87335aec..24e89caf6 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportService.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportService.java @@ -3,7 +3,6 @@ import static jakarta.ws.rs.core.Response.accepted; import static jakarta.ws.rs.core.Response.status; -import jakarta.ejb.Stateless; import jakarta.inject.Inject; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; @@ -32,11 +31,10 @@ * case of a valid registration attempt, sends an asynchronous message with the information to the * handling event registration system for proper registration. */ -@Stateless +@jakarta.enterprise.context.RequestScoped @Path("handling") public class HandlingReportService { public static final Logger LOGGER = Logger.getLogger(HandlingReportService.class.getName()); - // public static final String ISO_8601_FORMAT = "yyyy-MM-dd HH:mm"; @Inject private ApplicationEvents applicationEvents; diff --git a/src/main/java/org/eclipse/cargotracker/interfaces/tracking/web/CargoTrackingViewAdapter.java b/src/main/java/org/eclipse/cargotracker/interfaces/tracking/web/CargoTrackingViewAdapter.java index 6a7188b56..152e087b9 100644 --- a/src/main/java/org/eclipse/cargotracker/interfaces/tracking/web/CargoTrackingViewAdapter.java +++ b/src/main/java/org/eclipse/cargotracker/interfaces/tracking/web/CargoTrackingViewAdapter.java @@ -82,7 +82,7 @@ public String getStatusText() { return switch (delivery.transportStatus()) { case IN_PORT -> "In port " + cargo.getRouteSpecification().destination().getName(); case ONBOARD_CARRIER -> - "Onboard voyage " + delivery.currentVoyage().getVoyageNumber().getIdString(); + "Onboard voyage " + delivery.currentVoyage().getVoyageNumber().number(); case CLAIMED -> "Claimed"; case NOT_RECEIVED -> "Not received"; case UNKNOWN -> "Unknown"; @@ -175,12 +175,12 @@ public String getDescription() { switch (handlingEvent.getType()) { case LOAD: return "Loaded onto voyage " - + handlingEvent.getVoyage().getVoyageNumber().getIdString() + + handlingEvent.getVoyage().getVoyageNumber().number() + " in " + handlingEvent.getLocation().getName(); case UNLOAD: return "Unloaded off voyage " - + handlingEvent.getVoyage().getVoyageNumber().getIdString() + + handlingEvent.getVoyage().getVoyageNumber().number() + " in " + handlingEvent.getLocation().getName(); case RECEIVE: diff --git a/src/test/java/org/eclipse/cargotracker/Deployments.java b/src/test/java/org/eclipse/cargotracker/Deployments.java index 7dfee9661..1aa49f725 100644 --- a/src/test/java/org/eclipse/cargotracker/Deployments.java +++ b/src/test/java/org/eclipse/cargotracker/Deployments.java @@ -13,8 +13,6 @@ import org.eclipse.cargotracker.domain.shared.*; import org.eclipse.cargotracker.infrastructure.events.cdi.CargoInspected; import org.eclipse.cargotracker.infrastructure.logging.LoggerProducer; -import org.eclipse.cargotracker.infrastructure.messaging.JMSResourcesSetup; -import org.eclipse.cargotracker.infrastructure.persistence.DatabaseSetup; import org.eclipse.cargotracker.infrastructure.persistence.jpa.JpaCargoRepository; import org.eclipse.cargotracker.infrastructure.persistence.jpa.JpaHandlingEventRepository; import org.eclipse.cargotracker.infrastructure.persistence.jpa.JpaLocationRepository; @@ -58,7 +56,7 @@ public static void addInfraBase(WebArchive war) { // Infrastructure layer components. // Add persistence/JPA components. public static void addInfraPersistence(WebArchive war) { - war.addClass(DatabaseSetup.class) + war.addClass(org.eclipse.cargotracker.infrastructure.persistence.DatabaseResources.class) .addClass(JpaCargoRepository.class) .addClass(JpaVoyageRepository.class) .addClass(JpaHandlingEventRepository.class) @@ -75,7 +73,9 @@ public static void addApplicationService(WebArchive war) { } public static void addInfraMessaging(WebArchive war) { - war.addPackages(true, JMSResourcesSetup.class.getPackage()); + war.addPackages( + true, + org.eclipse.cargotracker.infrastructure.messaging.JMSResources.class.getPackage()); } public static void addInfraRouting(WebArchive war) { diff --git a/src/test/java/org/eclipse/cargotracker/application/ApplicationEventsTest.java b/src/test/java/org/eclipse/cargotracker/application/ApplicationEventsTest.java index cadad2aab..5e2373ca6 100644 --- a/src/test/java/org/eclipse/cargotracker/application/ApplicationEventsTest.java +++ b/src/test/java/org/eclipse/cargotracker/application/ApplicationEventsTest.java @@ -22,7 +22,6 @@ import org.eclipse.cargotracker.domain.model.location.UnLocode; import org.eclipse.cargotracker.domain.model.voyage.SampleVoyages; import org.eclipse.cargotracker.domain.model.voyage.VoyageNumber; -import org.eclipse.cargotracker.infrastructure.messaging.JMSResourcesSetup; import org.eclipse.cargotracker.infrastructure.messaging.jms.CargoHandledConsumer; import org.eclipse.cargotracker.infrastructure.messaging.jms.HandlingEventRegistrationAttemptConsumer; import org.eclipse.cargotracker.infrastructure.messaging.jms.JmsApplicationEvents; @@ -97,7 +96,7 @@ public static WebArchive createDeployment() { addInfraBase(war); // addInfraPersistence(war); // addInfraMessaging(war); - war.addClass(JMSResourcesSetup.class) + war.addClass(org.eclipse.cargotracker.infrastructure.messaging.JMSResources.class) .addClass(CargoHandledConsumer.class) .addClass(HandlingEventRegistrationAttemptConsumer.class); addApplicationBase(war); diff --git a/src/test/java/org/eclipse/cargotracker/domain/model/cargo/CargoTest.java b/src/test/java/org/eclipse/cargotracker/domain/model/cargo/CargoTest.java index a4447279b..bcfb30d0c 100644 --- a/src/test/java/org/eclipse/cargotracker/domain/model/cargo/CargoTest.java +++ b/src/test/java/org/eclipse/cargotracker/domain/model/cargo/CargoTest.java @@ -55,8 +55,8 @@ public void testRoutingStatus() { SampleLocations.MELBOURNE, LocalDate.now())); final Itinerary good = new Itinerary(); - Itinerary bad = new Itinerary(); - @SuppressWarnings("serial") + final Itinerary bad = new Itinerary(); + RouteSpecification acceptOnlyGood = new RouteSpecification( cargo.getOrigin(), diff --git a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CargoRepositoryTest.java b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CargoRepositoryTest.java index 799064101..ddeab65e2 100644 --- a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CargoRepositoryTest.java +++ b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CargoRepositoryTest.java @@ -4,9 +4,11 @@ import static org.eclipse.cargotracker.Deployments.*; import static org.eclipse.cargotracker.domain.model.handling.HandlingEvent.Type.LOAD; +import static java.util.List.*; + import jakarta.inject.Inject; import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; +import jakarta.persistence.EntityManagerFactory; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; @@ -29,7 +31,6 @@ import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; -import java.lang.reflect.Field; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Arrays; @@ -51,7 +52,9 @@ public class CargoRepositoryTest { @Inject private VoyageRepository voyageRepository; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; + + @Inject private EntityManagerFactory emf; @Deployment public static WebArchive createDeployment() { @@ -86,18 +89,28 @@ public static WebArchive createDeployment() { @BeforeEach public void setup() {} - public void startTransaction() throws Exception { + private void startTransaction() throws Exception { utx.begin(); entityManager.joinTransaction(); } - public void commitTransaction() throws Exception { + private void commitTransaction() throws Exception { LOGGER.log(Level.INFO, "UserTransaction status is: {0}", utx.getStatus()); if (utx.getStatus() == Status.STATUS_ACTIVE) { utx.commit(); } } + private void runInTx(Runnable runnable) throws Exception { + startTransaction(); + try { + runnable.run(); + } catch (Exception e) { + utx.rollback(); + } + commitTransaction(); + } + @Test @Order(1) public void testFindAll() { @@ -153,7 +166,7 @@ public void testFindByCargoId() throws Exception { HandlingEvent secondEvent = events.get(1); - Voyage hongkongTonNewYork = + Voyage hongkongToNewYork = new Voyage.Builder(new VoyageNumber("0100S"), SampleLocations.HONGKONG) .addMovement( SampleLocations.HANGZOU, LocalDateTime.now(), LocalDateTime.now()) @@ -166,7 +179,7 @@ public void testFindByCargoId() throws Exception { .build(); assertHandlingEvent( - cargo, secondEvent, LOAD, SampleLocations.HONGKONG, 150, 110, hongkongTonNewYork); + cargo, secondEvent, LOAD, SampleLocations.HONGKONG, 150, 110, hongkongToNewYork); List legs = cargo.getItinerary().legs(); assertThat(legs).hasSize(3); @@ -214,130 +227,141 @@ private void assertLeg(Leg firstLeg, String vn, Location expectedFrom, Location @Test @Order(6) public void testSave() throws Exception { - startTransaction(); - TrackingId trackingId = new TrackingId("AAA"); - Location origin = locationRepository.find(SampleLocations.DALLAS.getUnLocode()); - Location destination = locationRepository.find(SampleLocations.HELSINKI.getUnLocode()); - - Cargo cargo = - new Cargo(trackingId, new RouteSpecification(origin, destination, LocalDate.now())); - cargoRepository.store(cargo); - - cargo.assignToRoute( - new Itinerary( - Arrays.asList( - new Leg( - voyageRepository.find(new VoyageNumber("0300A")), - locationRepository.find( - SampleLocations.DALLAS.getUnLocode()), - locationRepository.find( - SampleLocations.HELSINKI.getUnLocode()), - LocalDateTime.now(), - LocalDateTime.now())))); - - this.entityManager.flush(); - commitTransaction(); - - // verify in new tx - startTransaction(); - - var result = - this.entityManager - .createQuery( - "select c from Cargo c where c.trackingId=:trackingId", Cargo.class) - .setParameter("trackingId", trackingId) - .getSingleResult(); - - assertThat(result.getTrackingId()).isEqualTo(trackingId); - assertThat(result.getRouteSpecification().origin()).isEqualTo(origin); - assertThat(result.getRouteSpecification().destination()).isEqualTo(destination); - assertThat(result.getItinerary().legs()).hasSize(1); - commitTransaction(); + runInTx( + () -> { + TrackingId trackingId = new TrackingId("AAA"); + Location origin = locationRepository.find(SampleLocations.DALLAS.getUnLocode()); + Location destination = + locationRepository.find(SampleLocations.HELSINKI.getUnLocode()); + + Cargo cargo = + new Cargo( + trackingId, + new RouteSpecification(origin, destination, LocalDate.now())); + cargoRepository.store(cargo); + + cargo.assignToRoute( + new Itinerary( + List.of( + new org.eclipse.cargotracker.domain.model.cargo.Leg( + voyageRepository.find( + new org.eclipse.cargotracker.domain + .model.voyage.VoyageNumber( + "0300A")), + locationRepository.find( + org.eclipse.cargotracker.domain.model + .location.SampleLocations.DALLAS + .getUnLocode()), + locationRepository.find( + org.eclipse.cargotracker.domain.model + .location.SampleLocations + .HELSINKI + .getUnLocode()), + java.time.LocalDateTime.now(), + java.time.LocalDateTime.now())))); + + this.entityManager.flush(); + + var result = + this.entityManager + .createQuery( + "select c from Cargo c where c.trackingId=:trackingId", + Cargo.class) + .setParameter("trackingId", trackingId) + .getSingleResult(); + + assertThat(result.getTrackingId()).isEqualTo(trackingId); + assertThat(result.getRouteSpecification().origin()).isEqualTo(origin); + assertThat(result.getRouteSpecification().destination()).isEqualTo(destination); + assertThat(result.getItinerary().legs()).hasSize(1); + }); } @Test @Order(7) public void testSpecifyNewRoute() throws Exception { LOGGER.log(Level.INFO, "run test :: testSpecifyNewRoute"); - startTransaction(); var trackingId = new TrackingId("AAA"); - Cargo cargo = cargoRepository.find(trackingId); - LOGGER.log(Level.INFO, "retrieved cargo: {0}", cargo.toString(true)); - assertThat(cargo).isNotNull(); - - Location origin = locationRepository.find(SampleLocations.NEWYORK.getUnLocode()); - Location destination = locationRepository.find(SampleLocations.HELSINKI.getUnLocode()); - - cargo.specifyNewRoute(new RouteSpecification(origin, destination, LocalDate.now())); - - cargoRepository.store(cargo); - LOGGER.log(Level.INFO, "saved cargo: {0}", cargo.toString(true)); - commitTransaction(); - - // verify in the new tx - LOGGER.log(Level.INFO, "run test :: verify cargo state"); - startTransaction(); - var result = - this.entityManager - .createQuery( - "select c from Cargo c where c.trackingId=:trackingId", Cargo.class) - .setParameter("trackingId", trackingId) - .getSingleResult(); - LOGGER.log( - Level.INFO, - "query cargo by tracking id: {0}, \n result: {1}", - new Object[] {trackingId, result.toString(true)}); - assertThat(result.getTrackingId()).isEqualTo(trackingId); - assertThat(result.getRouteSpecification().origin()).isEqualTo(origin); - assertThat(result.getRouteSpecification().destination()).isEqualTo(destination); - assertThat(result.getItinerary().legs()).hasSize(1); - - commitTransaction(); + runInTx( + () -> { + Cargo cargo = cargoRepository.find(trackingId); + LOGGER.log(Level.INFO, "retrieved cargo: {0}", cargo.toString(true)); + assertThat(cargo).isNotNull(); + + Location origin = + locationRepository.find(SampleLocations.NEWYORK.getUnLocode()); + Location destination = + locationRepository.find(SampleLocations.HELSINKI.getUnLocode()); + + cargo.specifyNewRoute( + new RouteSpecification(origin, destination, LocalDate.now())); + + cargoRepository.store(cargo); + LOGGER.log(Level.INFO, "saved cargo: {0}", cargo.toString(true)); + + this.entityManager.flush(); + + // verify in the new tx + LOGGER.log(Level.INFO, "run test :: verify cargo state"); + var result = + this.entityManager + .createQuery( + "select c from Cargo c where c.trackingId=:trackingId", + Cargo.class) + .setParameter("trackingId", trackingId) + .getSingleResult(); + LOGGER.log( + Level.INFO, + "query cargo by tracking id: {0}, \n result: {1}", + new Object[] {trackingId, result.toString(true)}); + assertThat(result.getTrackingId()).isEqualTo(trackingId); + assertThat(result.getRouteSpecification().origin()).isEqualTo(origin); + assertThat(result.getRouteSpecification().destination()).isEqualTo(destination); + assertThat(result.getItinerary().legs()).hasSize(1); + }); } @Test @Order(8) public void testReplaceItinerary() throws Exception { - startTransaction(); - var trackingId = new TrackingId("AAA"); - Cargo cargo = cargoRepository.find(trackingId); - Long cargoId = getLongId(cargo); - assertLegCount(trackingId, 1); - // assertThat(jdbcTemplate.queryForObject("select count(*) from Leg where cargo_id = ?", new - // Object[]{cargoId}, Integer.class).intValue()).isEqualTo(3); - - Itinerary newItinerary = - new Itinerary( - Arrays.asList( - new Leg( - SampleVoyages.NEW_YORK_TO_DALLAS, - locationRepository.find( - SampleLocations.NEWYORK.getUnLocode()), - locationRepository.find( - SampleLocations.DALLAS.getUnLocode()), - LocalDateTime.now(), - LocalDateTime.now()), - new Leg( - SampleVoyages.DALLAS_TO_HELSINKI, - locationRepository.find( - SampleLocations.DALLAS.getUnLocode()), - locationRepository.find( - SampleLocations.HELSINKI.getUnLocode()), - LocalDateTime.now(), - LocalDateTime.now()))); - - cargo.assignToRoute(newItinerary); - - cargoRepository.store(cargo); - commitTransaction(); - - // verify in the new tx - startTransaction(); - - assertLegCount(trackingId, 2); - // assertThat(jdbcTemplate.queryForObject("select count(*) from Leg where cargo_id = ?", new - // Object[]{cargoId}, Integer.class).intValue()).isEqualTo(1); - commitTransaction(); + runInTx( + () -> { + var trackingId = new TrackingId("AAA"); + Cargo cargo = cargoRepository.find(trackingId); + assertLegCount(trackingId, 1); + + Itinerary newItinerary = + new Itinerary( + Arrays.asList( + new Leg( + SampleVoyages.NEW_YORK_TO_DALLAS, + locationRepository.find( + SampleLocations.NEWYORK.getUnLocode()), + locationRepository.find( + SampleLocations.DALLAS.getUnLocode()), + LocalDateTime.now(), + LocalDateTime.now()), + new Leg( + SampleVoyages.DALLAS_TO_HELSINKI, + locationRepository.find( + SampleLocations.DALLAS.getUnLocode()), + locationRepository.find( + SampleLocations.HELSINKI.getUnLocode()), + LocalDateTime.now(), + LocalDateTime.now()))); + + cargo.assignToRoute(newItinerary); + + cargoRepository.store(cargo); + this.entityManager.flush(); + + // verify in the new tx + + assertLegCount(trackingId, 2); + // assertThat(jdbcTemplate.queryForObject("select count(*) from Leg where + // cargo_id = ?", new + // Object[]{cargoId}, Integer.class).intValue()).isEqualTo(1); + }); } private void assertLegCount(TrackingId trackingId, int expected) { @@ -367,14 +391,4 @@ private void assertLegCount(TrackingId trackingId, int expected) { // LOGGER.log(Level.INFO, "leg count: {0}", count); // assertThat((count.toString())).isEqualTo(String.valueOf(expected)); // } - - private Long getLongId(Object o) { - try { - Field id = o.getClass().getDeclaredField("id"); - id.setAccessible(true); - return (Long) id.get(o); - } catch (Exception e) { - throw new RuntimeException(); - } - } } diff --git a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CarrierMovementRepositoryTest.java b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CarrierMovementRepositoryTest.java index b3b374801..cc3949dbd 100644 --- a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CarrierMovementRepositoryTest.java +++ b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/CarrierMovementRepositoryTest.java @@ -5,7 +5,6 @@ import jakarta.inject.Inject; import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; @@ -33,7 +32,7 @@ public class CarrierMovementRepositoryTest { private static final Logger LOGGER = Logger.getLogger(CarrierMovementRepositoryTest.class.getName()); @Inject VoyageRepository voyageRepository; - @PersistenceContext EntityManager entityManager; + @Inject EntityManager entityManager; @Inject UserTransaction utx; String voyageNumberIdString = "007"; Voyage voyage; @@ -104,7 +103,7 @@ public void testFind() throws Exception { startTransaction(); Voyage result = voyageRepository.find(new VoyageNumber(voyageNumberIdString)); assertThat(result).isNotNull(); - assertThat(result.getVoyageNumber().getIdString()).isEqualTo(voyageNumberIdString); + assertThat(result.getVoyageNumber().number()).isEqualTo(voyageNumberIdString); var movements = result.getSchedule().getCarrierMovements(); assertThat(movements).hasSize(1); diff --git a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/HandlingEventRepositoryTest.java b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/HandlingEventRepositoryTest.java index 8899441e8..b877fd0ba 100644 --- a/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/HandlingEventRepositoryTest.java +++ b/src/test/java/org/eclipse/cargotracker/infrastructure/persistence/jpa/HandlingEventRepositoryTest.java @@ -5,7 +5,6 @@ import jakarta.inject.Inject; import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; import jakarta.transaction.Status; import jakarta.transaction.UserTransaction; @@ -48,7 +47,7 @@ public class HandlingEventRepositoryTest { @Inject private CargoRepository cargoRepository; - @PersistenceContext private EntityManager entityManager; + @Inject private EntityManager entityManager; @Deployment public static WebArchive createDeployment() { diff --git a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/CargoInspectedStub.java b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/CargoInspectedStub.java index a8e8a2551..205b2027b 100644 --- a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/CargoInspectedStub.java +++ b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/CargoInspectedStub.java @@ -3,6 +3,8 @@ import jakarta.annotation.PostConstruct; import jakarta.annotation.Resource; import jakarta.ejb.*; +import jakarta.enterprise.concurrent.ManagedScheduledExecutorService; +import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.event.Event; import jakarta.inject.Inject; @@ -17,30 +19,43 @@ import java.util.logging.Level; import java.util.logging.Logger; -@Startup -@Singleton +@ApplicationScoped +// @Startup @Singleton // imported from ejb public class CargoInspectedStub { private static final Logger LOGGER = Logger.getLogger(CargoInspectedStub.class.getName()); @Inject @CargoInspected Event cargoEvent; - @Resource TimerService timerService; + @Inject + ManagedScheduledExecutorService scheduledExecutorService; + // @Resource TimerService timerService; @PostConstruct public void initialize() { - LOGGER.log(Level.INFO, "starting timer service..."); - timerService.createTimer(TimeUnit.SECONDS.toMillis(5), "delayed 5 seconds to execute"); + LOGGER.log(Level.INFO, "raise event after 5 seconds..."); + scheduledExecutorService.schedule( + ()-> cargoEvent.fire( + new Cargo( + new TrackingId("AAA"), + new RouteSpecification( + SampleLocations.HONGKONG, + SampleLocations.NEWYORK, + LocalDate.now().plusMonths(6)))), + 5000, + TimeUnit.MILLISECONDS + ); + //timerService.createTimer(5000, "delayed 5 seconds to execute"); } - @Timeout - public void raiseEvent(Timer timer) { - LOGGER.log(Level.INFO, "raising event: {0}", timer.getInfo()); - cargoEvent.fire( - new Cargo( - new TrackingId("AAA"), - new RouteSpecification( - SampleLocations.HONGKONG, - SampleLocations.NEWYORK, - LocalDate.now().plusMonths(6)))); - } +// @Timeout +// public void raiseEvent(Timer timer) { +// LOGGER.log(Level.INFO, "raising event: {0}", timer.getInfo()); +// cargoEvent.fire( +// new Cargo( +// new TrackingId("AAA"), +// new RouteSpecification( +// SampleLocations.HONGKONG, +// SampleLocations.NEWYORK, +// LocalDate.now().plusMonths(6)))); +// } } diff --git a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingServiceTest.java b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingServiceTest.java index 0daf8c688..61bfaf1a1 100644 --- a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingServiceTest.java +++ b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/RealtimeCargoTrackingServiceTest.java @@ -35,11 +35,9 @@ public class RealtimeCargoTrackingServiceTest { private static final Logger LOGGER = Logger.getLogger(RealtimeCargoTrackingServiceTest.class.getName()); - @ArquillianResource URL base; @Deployment(testable = false) public static WebArchive createDeployment() { - WebArchive war = ShrinkWrap.create(WebArchive.class, "test-RealtimeCargoTrackingServiceTest.war"); @@ -65,13 +63,15 @@ public static WebArchive createDeployment() { return war; } + @ArquillianResource URL base; + @Test public void testOnCargoInspected() throws Exception { LOGGER.log(Level.INFO, "run test RealtimeCargoTrackingServiceTest# testOnCargoInspected"); TestClient.latch = new CountDownLatch(1); var session = connectToServer(); assertThat(session).isNotNull(); - TestClient.latch.await(5, TimeUnit.SECONDS); + TestClient.latch.await(6, TimeUnit.SECONDS); assertThat(TestClient.response).isNotNull(); var json = JsonPath.parse(TestClient.response); LOGGER.log(Level.INFO, "response json string: {0}", json); diff --git a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/TestClient.java b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/TestClient.java index 2c788eb7d..2fa3663c4 100644 --- a/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/TestClient.java +++ b/src/test/java/org/eclipse/cargotracker/interfaces/booking/socket/TestClient.java @@ -24,9 +24,8 @@ public void connected(Session session, EndpointConfig clientConfig) { @OnMessage public void onMessage(String msg) { - LOGGER.info("Message from server: " + msg); + LOGGER.info("message from server: " + msg); response = msg; - latch.countDown(); } @OnClose diff --git a/src/test/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportServiceTest.java b/src/test/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportServiceTest.java index 6197f34e1..5eb834ee9 100644 --- a/src/test/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportServiceTest.java +++ b/src/test/java/org/eclipse/cargotracker/interfaces/handling/rest/HandlingReportServiceTest.java @@ -98,7 +98,7 @@ public void submitReport() throws MalformedURLException { report.setCompletionTime(DateUtil.toString(LocalDateTime.now())); report.setEventType("LOAD"); report.setTrackingId("A001"); - report.setVoyageNumber(SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber().getIdString()); + report.setVoyageNumber(SampleVoyages.HONGKONG_TO_NEW_YORK.getVoyageNumber().number()); report.setUnLocode(SampleLocations.HONGKONG.getUnLocode().getIdString()); final WebTarget postReportTarget =