Search in sources :

Example 1 with NaturalLanguageStringStructure

use of uk.org.siri.siri20.NaturalLanguageStringStructure in project OpenTripPlanner by opentripplanner.

the class SiriTimetableSnapshotSource method handleAddedTrip.

private boolean handleAddedTrip(Graph graph, String feedId, EstimatedVehicleJourney estimatedVehicleJourney) {
    // Verifying values required in SIRI Profile
    // Added ServiceJourneyId
    String newServiceJourneyRef = estimatedVehicleJourney.getEstimatedVehicleJourneyCode();
    Preconditions.checkNotNull(newServiceJourneyRef, "EstimatedVehicleJourneyCode is required");
    // Replaced/duplicated ServiceJourneyId
    // VehicleJourneyRef existingServiceJourneyRef = estimatedVehicleJourney.getVehicleJourneyRef();
    // Preconditions.checkNotNull(existingServiceJourneyRef, "VehicleJourneyRef is required");
    // LineRef of added trip
    Preconditions.checkNotNull(estimatedVehicleJourney.getLineRef(), "LineRef is required");
    String lineRef = estimatedVehicleJourney.getLineRef().getValue();
    // OperatorRef of added trip
    Preconditions.checkNotNull(estimatedVehicleJourney.getOperatorRef(), "OperatorRef is required");
    String operatorRef = estimatedVehicleJourney.getOperatorRef().getValue();
    // Required in SIRI, but currently not in use by OTP
    // Preconditions.checkNotNull(estimatedVehicleJourney.getRouteRef(), "RouteRef is required");
    // String routeRef = estimatedVehicleJourney.getRouteRef().getValue();
    // Preconditions.checkNotNull(estimatedVehicleJourney.getGroupOfLinesRef(), "GroupOfLinesRef is required");
    // String groupOfLines = estimatedVehicleJourney.getGroupOfLinesRef().getValue();
    // Preconditions.checkNotNull(estimatedVehicleJourney.getExternalLineRef(), "ExternalLineRef is required");
    String externalLineRef = estimatedVehicleJourney.getExternalLineRef().getValue();
    // TODO - SIRI: Where is the Operator?
    // Operator operator = graphIndex.operatorForId.get(new FeedScopedId(feedId, operatorRef));
    // Preconditions.checkNotNull(operator, "Operator " + operatorRef + " is unknown");
    FeedScopedId tripId = new FeedScopedId(feedId, newServiceJourneyRef);
    FeedScopedId serviceId = new FeedScopedId(feedId, newServiceJourneyRef);
    Route replacedRoute = null;
    if (externalLineRef != null) {
        replacedRoute = graph.index.getRouteForId(new FeedScopedId(feedId, externalLineRef));
    }
    FeedScopedId routeId = new FeedScopedId(feedId, lineRef);
    Route route = graph.index.getRouteForId(routeId);
    if (route == null) {
        // Route is unknown - create new
        route = new Route();
        route.setId(routeId);
        route.setType(getRouteType(estimatedVehicleJourney.getVehicleModes()));
        // route.setOperator(operator);
        // TODO - SIRI: Is there a better way to find authority/Agency?
        // Finding first Route with same Operator, and using same Authority
        Agency agency = graph.index.getAllRoutes().stream().findFirst().get().getAgency();
        route.setAgency(agency);
        if (estimatedVehicleJourney.getPublishedLineNames() != null && !estimatedVehicleJourney.getPublishedLineNames().isEmpty()) {
            route.setShortName("" + estimatedVehicleJourney.getPublishedLineNames().get(0).getValue());
        }
        LOG.info("Adding route {} to graph.", routeId);
        graph.index.addRoutes(route);
    }
    Trip trip = new Trip();
    trip.setId(tripId);
    trip.setRoute(route);
    // TODO - SIRI: Set transport-submode based on replaced- and replacement-route
    if (replacedRoute != null) {
        if (replacedRoute.getType() >= 100 && replacedRoute.getType() < 200) {
            // Replaced-route is RAIL
            if (route.getType() == 100) {
            // Replacement-route is also RAIL
            // trip.setTransportSubmode(TransmodelTransportSubmode.REPLACEMENT_RAIL_SERVICE);
            } else if (route.getType() == 700) {
            // Replacement-route is BUS
            // trip.setTransportSubmode(TransmodelTransportSubmode.RAIL_REPLACEMENT_BUS);
            }
        }
    }
    trip.setServiceId(serviceId);
    // TODO - SIRI: PublishedLineName not defined in SIRI-profile
    if (estimatedVehicleJourney.getPublishedLineNames() != null && !estimatedVehicleJourney.getPublishedLineNames().isEmpty()) {
        trip.setRouteShortName("" + estimatedVehicleJourney.getPublishedLineNames().get(0).getValue());
    }
    // trip.setTripOperator(operator);
    // TODO - SIRI: Populate these?
    // Replacement-trip has different shape
    trip.setShapeId(null);
    // trip.setTripPrivateCode(null);
    // trip.setTripPublicCode(null);
    trip.setBlockId(null);
    trip.setTripShortName(null);
    trip.setTripHeadsign(null);
    // trip.setKeyValues(null);
    List<Stop> addedStops = new ArrayList<>();
    List<StopTime> aimedStopTimes = new ArrayList<>();
    List<EstimatedCall> estimatedCalls = estimatedVehicleJourney.getEstimatedCalls().getEstimatedCalls();
    for (int i = 0; i < estimatedCalls.size(); i++) {
        EstimatedCall estimatedCall = estimatedCalls.get(i);
        Stop stop = getStopForStopId(feedId, estimatedCall.getStopPointRef().getValue());
        StopTime stopTime = new StopTime();
        stopTime.setStop(stop);
        stopTime.setStopSequence(i);
        stopTime.setTrip(trip);
        ZonedDateTime aimedArrivalTime = estimatedCall.getAimedArrivalTime();
        ZonedDateTime aimedDepartureTime = estimatedCall.getAimedDepartureTime();
        if (aimedArrivalTime != null) {
            stopTime.setArrivalTime(calculateSecondsSinceMidnight(aimedArrivalTime));
        }
        if (aimedDepartureTime != null) {
            stopTime.setDepartureTime(calculateSecondsSinceMidnight(aimedDepartureTime));
        }
        if (estimatedCall.getArrivalBoardingActivity() == ArrivalBoardingActivityEnumeration.ALIGHTING) {
            stopTime.setDropOffType(PICKDROP_SCHEDULED);
        } else {
            stopTime.setDropOffType(PICKDROP_NONE);
        }
        if (estimatedCall.getDepartureBoardingActivity() == DepartureBoardingActivityEnumeration.BOARDING) {
            stopTime.setPickupType(PICKDROP_SCHEDULED);
        } else {
            stopTime.setPickupType(PICKDROP_NONE);
        }
        if (estimatedCall.getDestinationDisplaies() != null && !estimatedCall.getDestinationDisplaies().isEmpty()) {
            NaturalLanguageStringStructure destinationDisplay = estimatedCall.getDestinationDisplaies().get(0);
            stopTime.setStopHeadsign(destinationDisplay.getValue());
        }
        if (i == 0) {
            // Fake arrival on first stop
            stopTime.setArrivalTime(stopTime.getDepartureTime());
        } else if (i == (estimatedCalls.size() - 1)) {
            // Fake departure from last stop
            stopTime.setDepartureTime(stopTime.getArrivalTime());
        }
        addedStops.add(stop);
        aimedStopTimes.add(stopTime);
    }
    StopPattern stopPattern = new StopPattern(aimedStopTimes);
    TripPattern pattern = new TripPattern(trip.getRoute(), stopPattern);
    TripTimes tripTimes = new TripTimes(trip, aimedStopTimes, graph.deduplicator);
    boolean isJourneyPredictionInaccurate = (estimatedVehicleJourney.isPredictionInaccurate() != null && estimatedVehicleJourney.isPredictionInaccurate());
    // If added trip is updated with realtime - loop through and add delays
    for (int i = 0; i < estimatedCalls.size(); i++) {
        EstimatedCall estimatedCall = estimatedCalls.get(i);
        ZonedDateTime expectedArrival = estimatedCall.getExpectedArrivalTime();
        ZonedDateTime expectedDeparture = estimatedCall.getExpectedDepartureTime();
        int aimedArrivalTime = aimedStopTimes.get(i).getArrivalTime();
        int aimedDepartureTime = aimedStopTimes.get(i).getDepartureTime();
        if (expectedArrival != null) {
            int expectedArrivalTime = calculateSecondsSinceMidnight(expectedArrival);
            tripTimes.updateArrivalDelay(i, expectedArrivalTime - aimedArrivalTime);
        }
        if (expectedDeparture != null) {
            int expectedDepartureTime = calculateSecondsSinceMidnight(expectedDeparture);
            tripTimes.updateDepartureDelay(i, expectedDepartureTime - aimedDepartureTime);
        }
        if (estimatedCall.isCancellation() != null) {
            tripTimes.setCancelledStop(i, estimatedCall.isCancellation());
        }
        boolean isCallPredictionInaccurate = estimatedCall.isPredictionInaccurate() != null && estimatedCall.isPredictionInaccurate();
        tripTimes.setPredictionInaccurate(i, (isJourneyPredictionInaccurate | isCallPredictionInaccurate));
        if (i == 0) {
            // Fake arrival on first stop
            tripTimes.updateArrivalTime(i, tripTimes.getDepartureTime(i));
        } else if (i == (estimatedCalls.size() - 1)) {
            // Fake departure from last stop
            tripTimes.updateDepartureTime(i, tripTimes.getArrivalTime(i));
        }
    }
    // Adding trip to index necessary to include values in graphql-queries
    // TODO - SIRI: should more data be added to index?
    graph.index.getTripForId().put(tripId, trip);
    graph.index.getPatternForTrip().put(trip, pattern);
    if (estimatedVehicleJourney.isCancellation() != null && estimatedVehicleJourney.isCancellation()) {
        tripTimes.cancel();
    } else {
        tripTimes.setRealTimeState(RealTimeState.ADDED);
    }
    if (!graph.getServiceCodes().containsKey(serviceId)) {
        graph.getServiceCodes().put(serviceId, graph.getServiceCodes().size());
    }
    tripTimes.serviceCode = graph.getServiceCodes().get(serviceId);
    pattern.add(tripTimes);
    Preconditions.checkState(tripTimes.timesIncreasing(), "Non-increasing triptimes for added trip");
    ServiceDate serviceDate = getServiceDateForEstimatedVehicleJourney(estimatedVehicleJourney);
    if (graph.getCalendarService().getServiceDatesForServiceId(serviceId) == null || graph.getCalendarService().getServiceDatesForServiceId(serviceId).isEmpty()) {
        LOG.info("Adding serviceId {} to CalendarService", serviceId);
    // TODO - SIRI: Need to add the ExtraJourney as a Trip - alerts may be attached to it
    // graph.getCalendarService().addServiceIdAndServiceDates(serviceId, Arrays.asList(serviceDate));
    }
    return addTripToGraphAndBuffer(feedId, graph, trip, aimedStopTimes, addedStops, tripTimes, serviceDate);
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri20.NaturalLanguageStringStructure) StopPattern(org.opentripplanner.model.StopPattern) Trip(org.opentripplanner.model.Trip) Agency(org.opentripplanner.model.Agency) Stop(org.opentripplanner.model.Stop) ArrayList(java.util.ArrayList) TripPattern(org.opentripplanner.model.TripPattern) ServiceDate(org.opentripplanner.model.calendar.ServiceDate) ZonedDateTime(java.time.ZonedDateTime) FeedScopedId(org.opentripplanner.model.FeedScopedId) TimetableHelper.createUpdatedTripTimes(org.opentripplanner.ext.siri.TimetableHelper.createUpdatedTripTimes) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) EstimatedCall(uk.org.siri.siri20.EstimatedCall) Route(org.opentripplanner.model.Route) StopTime(org.opentripplanner.model.StopTime)

Example 2 with NaturalLanguageStringStructure

use of uk.org.siri.siri20.NaturalLanguageStringStructure in project OpenTripPlanner by opentripplanner.

the class TimetableHelper method createModifiedStopTimes.

/**
 * Apply the SIRI ET to the appropriate TripTimes from this Timetable.
 * Calculate new stoppattern based on single stop cancellations
 *
 * @param oldTimes
 * @param journey    SIRI-ET EstimatedVehicleJourney
 * @param trip
 * @param routingService
 * @return new copy of updated TripTimes after TripUpdate has been applied on TripTimes of trip
 * with the id specified in the trip descriptor of the TripUpdate; null if something
 * went wrong
 */
public static List<StopTime> createModifiedStopTimes(Timetable timetable, TripTimes oldTimes, EstimatedVehicleJourney journey, Trip trip, RoutingService routingService) {
    if (journey == null) {
        return null;
    }
    EstimatedVehicleJourney.EstimatedCalls journeyCalls = journey.getEstimatedCalls();
    if (journeyCalls == null) {
        return null;
    }
    List<EstimatedCall> estimatedCalls = journeyCalls.getEstimatedCalls();
    List<Stop> stops = createModifiedStops(timetable, journey, routingService);
    List<StopTime> modifiedStops = new ArrayList<>();
    ZonedDateTime departureDate = null;
    int numberOfRecordedCalls = (journey.getRecordedCalls() != null && journey.getRecordedCalls().getRecordedCalls() != null) ? journey.getRecordedCalls().getRecordedCalls().size() : 0;
    Set<Object> alreadyVisited = new HashSet<>();
    // modify updated stop-times
    for (int i = 0; i < stops.size(); i++) {
        Stop stop = stops.get(i);
        final StopTime stopTime = new StopTime();
        stopTime.setStop(stop);
        stopTime.setTrip(trip);
        stopTime.setStopSequence(i);
        stopTime.setDropOffType(timetable.pattern.stopPattern.dropoffs[i]);
        stopTime.setPickupType(timetable.pattern.stopPattern.pickups[i]);
        stopTime.setArrivalTime(oldTimes.getScheduledArrivalTime(i));
        stopTime.setDepartureTime(oldTimes.getScheduledDepartureTime(i));
        stopTime.setStopHeadsign(oldTimes.getHeadsign(i));
        // TODO: Do we need to set the StopTime.id?
        // stopTime.setId(oldTimes.getStopTimeIdByIndex(i));
        boolean foundMatch = false;
        if (i >= numberOfRecordedCalls) {
            for (EstimatedCall estimatedCall : estimatedCalls) {
                if (alreadyVisited.contains(estimatedCall)) {
                    continue;
                }
                if (departureDate == null) {
                    departureDate = (estimatedCall.getAimedDepartureTime() != null ? estimatedCall.getAimedDepartureTime() : estimatedCall.getAimedArrivalTime());
                }
                // Current stop is being updated
                boolean stopsMatchById = stop.getId().getId().equals(estimatedCall.getStopPointRef().getValue());
                if (!stopsMatchById && stop.isPartOfStation()) {
                    Stop alternativeStop = routingService.getStopForId(new FeedScopedId(stop.getId().getFeedId(), estimatedCall.getStopPointRef().getValue()));
                    if (alternativeStop != null && stop.isPartOfSameStationAs(alternativeStop)) {
                        stopsMatchById = true;
                        stopTime.setStop(alternativeStop);
                    }
                }
                if (stopsMatchById) {
                    foundMatch = true;
                    CallStatusEnumeration arrivalStatus = estimatedCall.getArrivalStatus();
                    if (arrivalStatus == CallStatusEnumeration.CANCELLED) {
                        stopTime.setDropOffType(PICKDROP_NONE);
                    } else if (estimatedCall.getArrivalBoardingActivity() == ArrivalBoardingActivityEnumeration.ALIGHTING) {
                        stopTime.setDropOffType(PICKDROP_SCHEDULED);
                    } else if (estimatedCall.getArrivalBoardingActivity() == ArrivalBoardingActivityEnumeration.NO_ALIGHTING) {
                        stopTime.setDropOffType(PICKDROP_NONE);
                    } else if (estimatedCall.getArrivalBoardingActivity() == null && i == 0) {
                        // First stop - default no pickup
                        stopTime.setDropOffType(PICKDROP_NONE);
                    }
                    CallStatusEnumeration departureStatus = estimatedCall.getDepartureStatus();
                    if (departureStatus == CallStatusEnumeration.CANCELLED) {
                        stopTime.setPickupType(PICKDROP_NONE);
                    } else if (estimatedCall.getDepartureBoardingActivity() == DepartureBoardingActivityEnumeration.BOARDING) {
                        stopTime.setPickupType(PICKDROP_SCHEDULED);
                    } else if (estimatedCall.getDepartureBoardingActivity() == DepartureBoardingActivityEnumeration.NO_BOARDING) {
                        stopTime.setPickupType(PICKDROP_NONE);
                    } else if (estimatedCall.getDepartureBoardingActivity() == null && i == (stops.size() - 1)) {
                        // Last stop - default no dropoff
                        stopTime.setPickupType(PICKDROP_NONE);
                    }
                    if (estimatedCall.getDestinationDisplaies() != null && !estimatedCall.getDestinationDisplaies().isEmpty()) {
                        NaturalLanguageStringStructure destinationDisplay = estimatedCall.getDestinationDisplaies().get(0);
                        stopTime.setStopHeadsign(destinationDisplay.getValue());
                    }
                    modifiedStops.add(stopTime);
                    alreadyVisited.add(estimatedCall);
                    break;
                }
            }
        }
        if (!foundMatch) {
            modifiedStops.add(stopTime);
        }
    }
    return modifiedStops;
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri20.NaturalLanguageStringStructure) EstimatedVehicleJourney(uk.org.siri.siri20.EstimatedVehicleJourney) Stop(org.opentripplanner.model.Stop) ArrayList(java.util.ArrayList) ZonedDateTime(java.time.ZonedDateTime) FeedScopedId(org.opentripplanner.model.FeedScopedId) EstimatedCall(uk.org.siri.siri20.EstimatedCall) CallStatusEnumeration(uk.org.siri.siri20.CallStatusEnumeration) StopTime(org.opentripplanner.model.StopTime) HashSet(java.util.HashSet)

Example 3 with NaturalLanguageStringStructure

use of uk.org.siri.siri20.NaturalLanguageStringStructure in project onebusaway-application-modules by camsys.

the class SiriSupportV2 method fillMonitoredVehicleJourney.

/**
 * NOTE: The tripDetails bean here may not be for the trip the vehicle is
 * currently on in the case of A-D for stop!
 * @param filters
 */
public static void fillMonitoredVehicleJourney(MonitoredVehicleJourneyStructure monitoredVehicleJourney, TripBean framedJourneyTripBean, TripStatusBean currentVehicleTripStatus, StopBean monitoredCallStopBean, OnwardCallsMode onwardCallsMode, PresentationService presentationService, TransitDataService transitDataService, int maximumOnwardCalls, List<TimepointPredictionRecord> stopLevelPredictions, boolean hasRealtimeData, boolean showApc, DetailLevel detailLevel, long responseTimestamp, Map<Filters, String> filters) {
    if (currentVehicleTripStatus != null && TransitDataConstants.STATUS_CANCELED.equals(currentVehicleTripStatus.getStatus())) {
        _log.error("aborting fillMVJ as trip is canceled");
        return;
    }
    BlockInstanceBean blockInstance = transitDataService.getBlockInstance(currentVehicleTripStatus.getActiveTrip().getBlockId(), currentVehicleTripStatus.getServiceDate());
    List<BlockTripBean> blockTrips = blockInstance.getBlockConfiguration().getTrips();
    if (monitoredCallStopBean == null) {
        monitoredCallStopBean = currentVehicleTripStatus.getNextStop();
    }
    /**
     *******************************************
     */
    // Route ID
    LineRefStructure lineRef = new LineRefStructure();
    lineRef.setValue(framedJourneyTripBean.getRoute().getId());
    DirectionRefStructure directionRef = new DirectionRefStructure();
    directionRef.setValue(framedJourneyTripBean.getDirectionId());
    // Route Short Name
    NaturalLanguageStringStructure routeShortName = new NaturalLanguageStringStructure();
    String shortName = framedJourneyTripBean.getRoute().getShortName();
    if (!isBlank(currentVehicleTripStatus.getActiveTrip().getRouteShortName())) {
        // look for an override like an express desginator
        shortName = currentVehicleTripStatus.getActiveTrip().getRouteShortName();
    }
    if (shortName == null) {
        shortName = framedJourneyTripBean.getRoute().getId().split("_")[1];
    }
    routeShortName.setValue(shortName);
    // Agency Id
    OperatorRefStructure operatorRef = new OperatorRefStructure();
    operatorRef.setValue(AgencySupportLibrary.getAgencyForId(framedJourneyTripBean.getRoute().getId()));
    // Framed Journey
    FramedVehicleJourneyRefStructure framedJourney = new FramedVehicleJourneyRefStructure();
    DataFrameRefStructure dataFrame = new DataFrameRefStructure();
    dataFrame.setValue(String.format("%1$tY-%1$tm-%1$td", currentVehicleTripStatus.getServiceDate()));
    framedJourney.setDataFrameRef(dataFrame);
    framedJourney.setDatedVehicleJourneyRef(framedJourneyTripBean.getId());
    // Shape Id
    JourneyPatternRefStructure journeyPattern = new JourneyPatternRefStructure();
    journeyPattern.setValue(framedJourneyTripBean.getShapeId());
    // Destination
    NaturalLanguageStringStructure headsign = new NaturalLanguageStringStructure();
    headsign.setValue(framedJourneyTripBean.getTripHeadsign());
    // Vehicle Id
    VehicleRefStructure vehicleRef = new VehicleRefStructure();
    if (currentVehicleTripStatus.getVehicleId() == null) {
        String tripId = framedJourneyTripBean.getId();
        String blockId = framedJourneyTripBean.getBlockId();
        String directionId = framedJourneyTripBean.getDirectionId();
        String vehicleIdHash = Integer.toString((tripId + blockId + directionId).hashCode());
        String agencyName = tripId.split("_")[0];
        String vehicleId = agencyName + "_" + vehicleIdHash;
        vehicleRef.setValue(vehicleId);
    } else {
        vehicleRef.setValue(currentVehicleTripStatus.getVehicleId());
    }
    // Set Origin and Destination stops from Block trips.
    StopBean lastStop = new StopBean();
    JourneyPlaceRefStructure origin = new JourneyPlaceRefStructure();
    for (int i = 0; i < blockTrips.size(); i++) {
        BlockTripBean blockTrip = blockTrips.get(i);
        if (blockTrip.getTrip().getId().equals(framedJourneyTripBean.getId())) {
            List<BlockStopTimeBean> stops = blockTrip.getBlockStopTimes();
            origin.setValue(stops.get(0).getStopTime().getStop().getId());
            lastStop = stops.get(stops.size() - 1).getStopTime().getStop();
            break;
        }
    }
    // location
    // if vehicle is detected to be on detour, use actual lat/lon, not
    // snapped location.
    LocationStructure location = new LocationStructure();
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(6);
    if (presentationService.isOnDetour(currentVehicleTripStatus)) {
        location.setLatitude(new BigDecimal(df.format(currentVehicleTripStatus.getLastKnownLocation().getLat())));
        location.setLongitude(new BigDecimal(df.format(currentVehicleTripStatus.getLastKnownLocation().getLon())));
    } else {
        location.setLatitude(new BigDecimal(df.format(currentVehicleTripStatus.getLocation().getLat())));
        location.setLongitude(new BigDecimal(df.format(currentVehicleTripStatus.getLocation().getLon())));
    }
    // progress status
    List<String> progressStatuses = new ArrayList<String>();
    if (presentationService.isInLayover(currentVehicleTripStatus)) {
        progressStatuses.add("layover");
    }
    // "prevTrip" really means not on the framedvehiclejourney trip
    if (!framedJourneyTripBean.getId().equals(currentVehicleTripStatus.getActiveTrip().getId())) {
        progressStatuses.add("prevTrip");
    }
    if (!progressStatuses.isEmpty()) {
        NaturalLanguageStringStructure progressStatus = new NaturalLanguageStringStructure();
        progressStatus.setValue(StringUtils.join(progressStatuses, ","));
        monitoredVehicleJourney.getProgressStatus().add(progressStatus);
    }
    // scheduled depature time
    if (presentationService.isBlockLevelInference(currentVehicleTripStatus) && (presentationService.isInLayover(currentVehicleTripStatus) || !framedJourneyTripBean.getId().equals(currentVehicleTripStatus.getActiveTrip().getId()))) {
        BlockStopTimeBean originDepartureStopTime = null;
        for (int t = 0; t < blockTrips.size(); t++) {
            BlockTripBean thisTrip = blockTrips.get(t);
            BlockTripBean nextTrip = null;
            if (t + 1 < blockTrips.size()) {
                nextTrip = blockTrips.get(t + 1);
            }
            if (thisTrip.getTrip().getId().equals(currentVehicleTripStatus.getActiveTrip().getId())) {
                // just started new trip
                if (currentVehicleTripStatus.getDistanceAlongTrip() < (0.5 * currentVehicleTripStatus.getTotalDistanceAlongTrip())) {
                    originDepartureStopTime = thisTrip.getBlockStopTimes().get(0);
                // at end of previous trip
                } else {
                    if (nextTrip != null) {
                        originDepartureStopTime = nextTrip.getBlockStopTimes().get(0);
                    }
                }
                break;
            }
        }
        if (originDepartureStopTime != null) {
            long departureTime = currentVehicleTripStatus.getServiceDate() + (originDepartureStopTime.getStopTime().getDepartureTime() * 1000);
            monitoredVehicleJourney.setOriginAimedDepartureTime(DateUtil.toXmlGregorianCalendar(departureTime));
        }
    }
    Map<String, TimepointPredictionRecord> stopIdToPredictionRecordMap = new HashMap<String, TimepointPredictionRecord>();
    // (build map of stop IDs to TPRs)
    if (stopLevelPredictions != null) {
        for (TimepointPredictionRecord tpr : stopLevelPredictions) {
            if (!tpr.isSkipped()) {
                stopIdToPredictionRecordMap.put(AgencyAndId.convertToString(tpr.getTimepointId()), tpr);
            }
        }
    }
    // monitored call
    if (!presentationService.isOnDetour(currentVehicleTripStatus))
        fillMonitoredCall(monitoredVehicleJourney, blockInstance, currentVehicleTripStatus, monitoredCallStopBean, presentationService, transitDataService, stopIdToPredictionRecordMap, hasRealtimeData, detailLevel, responseTimestamp);
    // detail level - minimal
    if (detailLevel.equals(DetailLevel.MINIMUM) || detailLevel.equals(DetailLevel.BASIC) || detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.getPublishedLineName().add(routeShortName);
        monitoredVehicleJourney.getDestinationName().add(headsign);
        monitoredVehicleJourney.setMonitored(currentVehicleTripStatus.isPredicted());
        monitoredVehicleJourney.getVehicleMode().add(toVehicleMode(currentVehicleTripStatus.getVehicleType()));
        monitoredVehicleJourney.setVehicleRef(vehicleRef);
        monitoredVehicleJourney.setBearing((float) currentVehicleTripStatus.getOrientation());
        monitoredVehicleJourney.setVehicleLocation(location);
        // block ref
        BlockRefStructure blockRef = new BlockRefStructure();
        blockRef.setValue(framedJourneyTripBean.getBlockId());
        monitoredVehicleJourney.setBlockRef(blockRef);
    }
    // detail level - basic
    if (detailLevel.equals(DetailLevel.BASIC) || detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.setFramedVehicleJourneyRef(framedJourney);
        monitoredVehicleJourney.setDirectionRef(directionRef);
        // since LineRef is fully qualified with operatorref, moving OperatorRef to normal detail
        // monitoredVehicleJourney.setOperatorRef(operatorRef);
        DestinationRefStructure dest = new DestinationRefStructure();
        dest.setValue(lastStop.getId());
        monitoredVehicleJourney.setDestinationRef(dest);
        monitoredVehicleJourney.setLineRef(lineRef);
        monitoredVehicleJourney.setProgressRate(getProgressRateForPhaseAndStatus(currentVehicleTripStatus.getStatus(), currentVehicleTripStatus.getPhase()));
    }
    if (showApc) {
        fillOccupancy(monitoredVehicleJourney, transitDataService, currentVehicleTripStatus);
    }
    // detail level - normal
    if (detailLevel.equals(DetailLevel.NORMAL) || detailLevel.equals(DetailLevel.CALLS)) {
        monitoredVehicleJourney.setOperatorRef(operatorRef);
        monitoredVehicleJourney.setOriginRef(origin);
        monitoredVehicleJourney.setJourneyPatternRef(journeyPattern);
    }
    // onward calls
    if (detailLevel.equals(DetailLevel.CALLS)) {
        if (!presentationService.isOnDetour(currentVehicleTripStatus))
            fillOnwardCalls(monitoredVehicleJourney, blockInstance, framedJourneyTripBean, currentVehicleTripStatus, onwardCallsMode, presentationService, transitDataService, stopIdToPredictionRecordMap, maximumOnwardCalls, responseTimestamp);
    }
    // situations
    fillSituations(monitoredVehicleJourney, currentVehicleTripStatus);
    return;
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri_2.NaturalLanguageStringStructure) BlockTripBean(org.onebusaway.transit_data.model.blocks.BlockTripBean) HashMap(java.util.HashMap) DestinationRefStructure(uk.org.siri.siri_2.DestinationRefStructure) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) LocationStructure(uk.org.siri.siri_2.LocationStructure) DataFrameRefStructure(uk.org.siri.siri_2.DataFrameRefStructure) BlockStopTimeBean(org.onebusaway.transit_data.model.blocks.BlockStopTimeBean) OperatorRefStructure(uk.org.siri.siri_2.OperatorRefStructure) JourneyPlaceRefStructure(uk.org.siri.siri_2.JourneyPlaceRefStructure) FramedVehicleJourneyRefStructure(uk.org.siri.siri_2.FramedVehicleJourneyRefStructure) JourneyPatternRefStructure(uk.org.siri.siri_2.JourneyPatternRefStructure) BlockRefStructure(uk.org.siri.siri_2.BlockRefStructure) LineRefStructure(uk.org.siri.siri_2.LineRefStructure) BigDecimal(java.math.BigDecimal) BlockInstanceBean(org.onebusaway.transit_data.model.blocks.BlockInstanceBean) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) StopBean(org.onebusaway.transit_data.model.StopBean) DirectionRefStructure(uk.org.siri.siri_2.DirectionRefStructure) VehicleRefStructure(uk.org.siri.siri_2.VehicleRefStructure)

Example 4 with NaturalLanguageStringStructure

use of uk.org.siri.siri20.NaturalLanguageStringStructure in project onebusaway-application-modules by camsys.

the class RealtimeServiceTest method testStopPointsByBounds.

@Test
public void testStopPointsByBounds() throws Exception {
    // MOCKS
    // Coordinate Bounds
    CoordinateBounds bounds = new CoordinateBounds(Double.parseDouble("47.612813"), Double.parseDouble("-122.339662"), Double.parseDouble("47.608813"), Double.parseDouble("-122.337662"));
    // Stops For Bounds
    StopsBean stopsBean = new StopsBean();
    stopsBean.setStops(stops);
    lenient().when(transitDataService.getRouteForId("1_100194")).thenReturn(routeBean);
    when(transitDataService.getStops(any(SearchQueryBean.class))).thenReturn(stopsBean);
    when(transitDataService.getStopsForRoute("1_100194")).thenReturn(stopsForRouteBean);
    when(transitDataService.stopHasUpcomingScheduledService(anyString(), anyLong(), anyString(), anyString(), anyString())).thenReturn(true);
    // EXPECTED
    LineDirectionStructure lds = new LineDirectionStructure();
    DirectionRefStructure drs = new DirectionRefStructure();
    LineRefStructure lrs = new LineRefStructure();
    lds.setDirectionRef(drs);
    lds.setLineRef(lrs);
    drs.setValue("0");
    lrs.setValue("1_100194");
    LocationStructure ls = new LocationStructure();
    BigDecimal lat = new BigDecimal(47.610813);
    BigDecimal lon = new BigDecimal(-122.338662);
    ls.setLatitude(lat.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    ls.setLongitude(lon.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    NaturalLanguageStringStructure stopName = new NaturalLanguageStringStructure();
    stopName.setValue("3rd Ave & Pine St");
    List<NaturalLanguageStringStructure> stopNames = new ArrayList<NaturalLanguageStringStructure>();
    stopNames.add(stopName);
    StopPointRefStructure stopPointRef = new StopPointRefStructure();
    stopPointRef.setValue("1_430");
    Boolean monitored = true;
    AnnotatedStopPointStructure mockStopPoint = new AnnotatedStopPointStructure();
    mockStopPoint.setLines(new AnnotatedStopPointStructure.Lines());
    mockStopPoint.getLines().getLineRefOrLineDirection().add(lds);
    mockStopPoint.setLocation(ls);
    mockStopPoint.getStopName().add(stopName);
    mockStopPoint.setStopPointRef(stopPointRef);
    mockStopPoint.setMonitored(monitored);
    // REALTIME ARGUMENTS
    // Agency Ids
    List<String> agencyIds = new ArrayList<String>();
    String agencyId = "1";
    agencyIds.add(agencyId);
    // Route Ids
    List<AgencyAndId> routeIds = new ArrayList<AgencyAndId>();
    AgencyAndId routeId = AgencyAndIdLibrary.convertFromString("1_100194");
    routeIds.add(routeId);
    // Detail Level
    DetailLevel detailLevel = DetailLevel.NORMAL;
    // Time
    long time = System.currentTimeMillis();
    // Filters
    Map<Filters, String> filters = new HashMap<Filters, String>();
    Map<Boolean, List<AnnotatedStopPointStructure>> actualResult = realtimeService.getAnnotatedStopPointStructures(bounds, agencyIds, routeIds, detailLevel, time, filters);
    AnnotatedStopPointStructure actualStopPoint = actualResult.get(true).get(0);
    assertTrue(isEqual(mockStopPoint, actualStopPoint));
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri_2.NaturalLanguageStringStructure) LineDirectionStructure(uk.org.siri.siri_2.LineDirectionStructure) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Matchers.anyString(org.mockito.Matchers.anyString) LocationStructure(uk.org.siri.siri_2.LocationStructure) Filters(org.onebusaway.api.actions.siri.impl.SiriSupportV2.Filters) SearchQueryBean(org.onebusaway.transit_data.model.SearchQueryBean) ArrayList(java.util.ArrayList) List(java.util.List) StopPointRefStructure(uk.org.siri.siri_2.StopPointRefStructure) AnnotatedStopPointStructure(uk.org.siri.siri_2.AnnotatedStopPointStructure) LineRefStructure(uk.org.siri.siri_2.LineRefStructure) BigDecimal(java.math.BigDecimal) DetailLevel(org.onebusaway.api.actions.siri.model.DetailLevel) DirectionRefStructure(uk.org.siri.siri_2.DirectionRefStructure) CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds) StopsBean(org.onebusaway.transit_data.model.StopsBean) Test(org.junit.Test)

Example 5 with NaturalLanguageStringStructure

use of uk.org.siri.siri20.NaturalLanguageStringStructure in project onebusaway-application-modules by camsys.

the class RealtimeServiceTest method testStopPointsByRoute.

@Test
public void testStopPointsByRoute() throws Exception {
    lenient().when(transitDataService.getRouteForId("1_100194")).thenReturn(routeBean);
    when(transitDataService.getStopsForRoute("1_100194")).thenReturn(stopsForRouteBean);
    when(transitDataService.stopHasUpcomingScheduledService(anyString(), anyLong(), anyString(), anyString(), anyString())).thenReturn(true);
    LineDirectionStructure lds = new LineDirectionStructure();
    DirectionRefStructure drs = new DirectionRefStructure();
    LineRefStructure lrs = new LineRefStructure();
    lds.setDirectionRef(drs);
    lds.setLineRef(lrs);
    drs.setValue("0");
    lrs.setValue("1_100194");
    LocationStructure ls = new LocationStructure();
    BigDecimal lat = new BigDecimal(47.610813);
    BigDecimal lon = new BigDecimal(-122.338662);
    ls.setLatitude(lat.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    ls.setLongitude(lon.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    NaturalLanguageStringStructure stopName = new NaturalLanguageStringStructure();
    stopName.setValue("3rd Ave & Pine St");
    List<NaturalLanguageStringStructure> stopNames = new ArrayList<NaturalLanguageStringStructure>();
    stopNames.add(stopName);
    StopPointRefStructure stopPointRef = new StopPointRefStructure();
    stopPointRef.setValue("1_430");
    Boolean monitored = true;
    AnnotatedStopPointStructure mockStopPoint = new AnnotatedStopPointStructure();
    mockStopPoint.setLines(new AnnotatedStopPointStructure.Lines());
    mockStopPoint.getLines().getLineRefOrLineDirection().add(lds);
    mockStopPoint.setLocation(ls);
    mockStopPoint.getStopName().add(stopName);
    mockStopPoint.setStopPointRef(stopPointRef);
    mockStopPoint.setMonitored(monitored);
    // REALTIME ARGUMENTS
    // Agency Ids
    List<String> agencyIds = new ArrayList<String>();
    String agencyId = "1";
    agencyIds.add(agencyId);
    // Route Ids
    List<AgencyAndId> routeIds = new ArrayList<AgencyAndId>();
    AgencyAndId routeId = AgencyAndIdLibrary.convertFromString("1_100194");
    routeIds.add(routeId);
    // Detail Level
    DetailLevel detailLevel = DetailLevel.NORMAL;
    // Time
    long time = System.currentTimeMillis();
    // Filters
    Map<Filters, String> filters = new HashMap<Filters, String>();
    Map<Boolean, List<AnnotatedStopPointStructure>> actualResult = realtimeService.getAnnotatedStopPointStructures(agencyIds, routeIds, detailLevel, time, filters);
    AnnotatedStopPointStructure actualStopPoint = actualResult.get(true).get(0);
    assertTrue(isEqual(mockStopPoint, actualStopPoint));
}
Also used : NaturalLanguageStringStructure(uk.org.siri.siri_2.NaturalLanguageStringStructure) LineDirectionStructure(uk.org.siri.siri_2.LineDirectionStructure) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) HashMap(java.util.HashMap) AnnotatedStopPointStructure(uk.org.siri.siri_2.AnnotatedStopPointStructure) ArrayList(java.util.ArrayList) LineRefStructure(uk.org.siri.siri_2.LineRefStructure) Matchers.anyString(org.mockito.Matchers.anyString) LocationStructure(uk.org.siri.siri_2.LocationStructure) BigDecimal(java.math.BigDecimal) Filters(org.onebusaway.api.actions.siri.impl.SiriSupportV2.Filters) DetailLevel(org.onebusaway.api.actions.siri.model.DetailLevel) ArrayList(java.util.ArrayList) List(java.util.List) StopPointRefStructure(uk.org.siri.siri_2.StopPointRefStructure) DirectionRefStructure(uk.org.siri.siri_2.DirectionRefStructure) Test(org.junit.Test)

Aggregations

BigDecimal (java.math.BigDecimal)8 NaturalLanguageStringStructure (uk.org.siri.siri_2.NaturalLanguageStringStructure)8 ArrayList (java.util.ArrayList)7 StopPointRefStructure (uk.org.siri.siri_2.StopPointRefStructure)7 DirectionRefStructure (uk.org.siri.siri_2.DirectionRefStructure)6 LineRefStructure (uk.org.siri.siri_2.LineRefStructure)6 LocationStructure (uk.org.siri.siri_2.LocationStructure)6 HashMap (java.util.HashMap)4 LineDirectionStructure (uk.org.siri.siri_2.LineDirectionStructure)4 List (java.util.List)3 Matchers.anyString (org.mockito.Matchers.anyString)3 Filters (org.onebusaway.api.actions.siri.impl.SiriSupportV2.Filters)3 DetailLevel (org.onebusaway.api.actions.siri.model.DetailLevel)3 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)3 StopBean (org.onebusaway.transit_data.model.StopBean)3 NaturalLanguageStringStructure (uk.org.siri.siri20.NaturalLanguageStringStructure)3 AnnotatedStopPointStructure (uk.org.siri.siri_2.AnnotatedStopPointStructure)3 ZonedDateTime (java.time.ZonedDateTime)2 Test (org.junit.Test)2 CoordinateBounds (org.onebusaway.geospatial.model.CoordinateBounds)2