Search in sources :

Example 1 with MonitoredVehicleJourneyStructure

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

the class TimetableHelper method createUpdatedTripTimes.

/**
 * Apply the TripUpdate to the appropriate TripTimes from this Timetable. The existing TripTimes
 * must not be modified directly because they may be shared with the underlying
 * scheduledTimetable, or other updated Timetables. The {@link TimetableSnapshot} performs the
 * protective copying of this Timetable. It is not done in this update method to avoid
 * repeatedly cloning the same Timetable when several updates are applied to it at once. We
 * assume here that all trips in a timetable are from the same feed, which should always be the
 * case.
 *
 * @param activity SIRI-VM VehicleActivity
 * @param timeZone time zone of trip update
 * @param tripId
 * @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 TripTimes createUpdatedTripTimes(Timetable timetable, Graph graph, VehicleActivityStructure activity, TimeZone timeZone, FeedScopedId tripId) {
    if (activity == null) {
        return null;
    }
    MonitoredVehicleJourneyStructure mvj = activity.getMonitoredVehicleJourney();
    int tripIndex = timetable.getTripIndex(tripId);
    if (tripIndex == -1) {
        LOG.trace("tripId {} not found in pattern.", tripId);
        return null;
    }
    final TripTimes existingTripTimes = timetable.getTripTimes(tripIndex);
    TripTimes newTimes = new TripTimes(existingTripTimes);
    MonitoredCallStructure update = mvj.getMonitoredCall();
    if (update == null) {
        return null;
    }
    final List<Stop> stops = timetable.pattern.getStops();
    VehicleActivityStructure.MonitoredVehicleJourney monitoredVehicleJourney = activity.getMonitoredVehicleJourney();
    Duration delay = null;
    if (monitoredVehicleJourney != null) {
        delay = monitoredVehicleJourney.getDelay();
        int updatedDelay = 0;
        if (delay != null) {
            updatedDelay = delay.getSign() * (delay.getHours() * 3600 + delay.getMinutes() * 60 + delay.getSeconds());
        }
        MonitoredCallStructure monitoredCall = monitoredVehicleJourney.getMonitoredCall();
        if (monitoredCall != null && monitoredCall.getStopPointRef() != null) {
            boolean matchFound = false;
            int arrivalDelay = 0;
            int departureDelay = 0;
            for (int index = 0; index < newTimes.getNumStops(); ++index) {
                if (!matchFound) {
                    // Delay is set on a single stop at a time. When match is found - propagate delay on all following stops
                    final Stop stop = stops.get(index);
                    matchFound = stop.getId().getId().equals(monitoredCall.getStopPointRef().getValue());
                    if (!matchFound && stop.isPartOfStation()) {
                        FeedScopedId alternativeId = new FeedScopedId(stop.getId().getFeedId(), monitoredCall.getStopPointRef().getValue());
                        Stop alternativeStop = graph.index.getStopForId(alternativeId);
                        if (alternativeStop != null && alternativeStop.isPartOfStation()) {
                            matchFound = stop.isPartOfSameStationAs(alternativeStop);
                        }
                    }
                    if (matchFound) {
                        arrivalDelay = departureDelay = updatedDelay;
                    } else {
                        /*
                             * If updated delay is less than previously set delay, the existing delay needs to be adjusted to avoid
                             * non-increasing times causing updates to be rejected. Will only affect historical data.
                             */
                        arrivalDelay = Math.min(existingTripTimes.getArrivalDelay(index), updatedDelay);
                        departureDelay = Math.min(existingTripTimes.getDepartureDelay(index), updatedDelay);
                    }
                }
                newTimes.updateArrivalDelay(index, arrivalDelay);
                newTimes.updateDepartureDelay(index, departureDelay);
            }
        }
    }
    if (!newTimes.timesIncreasing()) {
        LOG.info("TripTimes are non-increasing after applying SIRI delay propagation - delay: {}", delay);
        return null;
    }
    // If state is already MODIFIED - keep existing state
    if (newTimes.getRealTimeState() != RealTimeState.MODIFIED) {
        // Make sure that updated trip times have the correct real time state
        newTimes.setRealTimeState(RealTimeState.UPDATED);
    }
    return newTimes;
}
Also used : MonitoredVehicleJourneyStructure(uk.org.siri.siri20.MonitoredVehicleJourneyStructure) Stop(org.opentripplanner.model.Stop) TripTimes(org.opentripplanner.routing.trippattern.TripTimes) FeedScopedId(org.opentripplanner.model.FeedScopedId) Duration(javax.xml.datatype.Duration) VehicleActivityStructure(uk.org.siri.siri20.VehicleActivityStructure) MonitoredCallStructure(uk.org.siri.siri20.MonitoredCallStructure)

Example 2 with MonitoredVehicleJourneyStructure

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

the class VehicleMonitoringV2Action method index.

public DefaultHttpHeaders index() throws IOException {
    long currentTimestamp = getTime();
    processGoogleAnalytics();
    _realtimeService.setTime(currentTimestamp);
    String detailLevelParam = _servletRequest.getParameter(VEHICLE_MONITORING_DETAIL_LEVEL);
    // get the detail level parameter or set it to default if not specified
    DetailLevel detailLevel;
    if (DetailLevel.contains(detailLevelParam)) {
        detailLevel = DetailLevel.valueOf(detailLevelParam.toUpperCase());
    } else {
        detailLevel = DetailLevel.NORMAL;
    }
    // User Parameters
    String lineRef = _servletRequest.getParameter(LINE_REF);
    String vehicleRef = _servletRequest.getParameter(VEHICLE_REF);
    String directionId = _servletRequest.getParameter(DIRECTION_REF);
    String agencyId = _servletRequest.getParameter(OPERATOR_REF);
    String maxOnwardCallsParam = _servletRequest.getParameter(MAX_ONWARD_CALLS);
    String maxStopVisitsParam = _servletRequest.getParameter(MAX_STOP_VISITS);
    String minStopVisitsParam = _servletRequest.getParameter(MIN_STOP_VISITS);
    // Error Strings
    String routeIdsErrorString = "";
    /*
     * We need to support the user providing no agency id which means 'all agencies'.
    So, this array will hold a single agency if the user provides it or all
    agencies if the user provides none. We'll iterate over them later while 
    querying for vehicles and routes
    */
    List<AgencyAndId> routeIds = new ArrayList<AgencyAndId>();
    List<String> agencyIds = processAgencyIds(agencyId);
    List<AgencyAndId> vehicleIds = processVehicleIds(vehicleRef, agencyIds);
    routeIdsErrorString = processRouteIds(lineRef, routeIds, agencyIds);
    int maximumOnwardCalls = 0;
    if (detailLevel.equals(DetailLevel.CALLS)) {
        maximumOnwardCalls = SiriSupportV2.convertToNumeric(maxOnwardCallsParam, Integer.MAX_VALUE);
    }
    String gaLabel = null;
    // *** CASE 1: single vehicle, ignore any other filters
    if (vehicleIds.size() > 0) {
        gaLabel = vehicleRef;
        List<VehicleActivityStructure> activities = new ArrayList<VehicleActivityStructure>();
        try {
            for (AgencyAndId vehicleId : vehicleIds) {
                VehicleActivityStructure activity = _realtimeService.getVehicleActivityForVehicle(vehicleId.toString(), maximumOnwardCalls, detailLevel, currentTimestamp);
                if (activity != null) {
                    activities.add(activity);
                }
            }
        } catch (Exception e) {
            _log.info(e.getMessage(), e);
        }
        // No vehicle id validation, so we pass null for error
        _siriResponse = generateSiriResponse(activities, null, null, currentTimestamp);
    // *** CASE 2: by route, using direction id, if provided
    } else if (lineRef != null) {
        gaLabel = lineRef;
        List<VehicleActivityStructure> activities = new ArrayList<VehicleActivityStructure>();
        for (AgencyAndId routeId : routeIds) {
            List<VehicleActivityStructure> activitiesForRoute = _realtimeService.getVehicleActivityForRoute(routeId.toString(), directionId, maximumOnwardCalls, detailLevel, currentTimestamp);
            if (activitiesForRoute != null) {
                activities.addAll(activitiesForRoute);
            }
        }
        if (vehicleIds.size() > 0) {
            List<VehicleActivityStructure> filteredActivities = new ArrayList<VehicleActivityStructure>();
            for (VehicleActivityStructure activity : activities) {
                MonitoredVehicleJourneyStructure journey = activity.getMonitoredVehicleJourney();
                AgencyAndId thisVehicleId = AgencyAndIdLibrary.convertFromString(journey.getVehicleRef().getValue());
                // user filtering
                if (!vehicleIds.contains(thisVehicleId))
                    continue;
                filteredActivities.add(activity);
            }
            activities = filteredActivities;
        }
        Exception error = null;
        if (lineRef != null && routeIds.size() == 0) {
            error = new Exception(routeIdsErrorString.trim());
        }
        _siriResponse = generateSiriResponse(activities, routeIds, error, currentTimestamp);
    // *** CASE 3: all vehicles
    } else {
        try {
            gaLabel = "All Vehicles";
            // int hashKey = _siriCacheService.hash(maximumOnwardCalls, agencyIds, _type);
            List<VehicleActivityStructure> activities = new ArrayList<VehicleActivityStructure>();
            // if (!_siriCacheService.containsKey(hashKey)) {
            for (String agency : agencyIds) {
                ListBean<VehicleStatusBean> vehicles = _transitDataService.getAllVehiclesForAgency(agency, currentTimestamp);
                for (VehicleStatusBean v : vehicles.getList()) {
                    VehicleActivityStructure activity = _realtimeService.getVehicleActivityForVehicle(v.getVehicleId(), maximumOnwardCalls, detailLevel, currentTimestamp);
                    if (activity != null) {
                        activities.add(activity);
                    }
                }
            }
            // There is no input (route id) to validate, so pass null error
            _siriResponse = generateSiriResponse(activities, null, null, currentTimestamp);
        // _siriCacheService.store(hashKey, getVehicleMonitoring());
        // } else {
        // _cachedResponse = _siriCacheService.retrieve(hashKey);
        // }
        } catch (Exception e) {
            _log.error("vm all broke:", e);
            throw new RuntimeException(e);
        }
    }
    return setOkResponseText(getSiri());
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) ArrayList(java.util.ArrayList) ListBean(org.onebusaway.transit_data.model.ListBean) IOException(java.io.IOException) VehicleStatusBean(org.onebusaway.transit_data.model.VehicleStatusBean) MonitoredVehicleJourneyStructure(uk.org.siri.siri_2.MonitoredVehicleJourneyStructure) DetailLevel(org.onebusaway.api.actions.siri.model.DetailLevel) ArrayList(java.util.ArrayList) List(java.util.List) VehicleActivityStructure(uk.org.siri.siri_2.VehicleActivityStructure)

Example 3 with MonitoredVehicleJourneyStructure

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

the class RealtimeServiceV2Impl method getMonitoredStopVisitsForStop.

@Override
public List<MonitoredStopVisitStructure> getMonitoredStopVisitsForStop(String stopId, int maximumOnwardCalls, DetailLevel detailLevel, long currentTime, List<AgencyAndId> routeIds, Map<Filters, String> filters) {
    List<MonitoredStopVisitStructure> output = new ArrayList<MonitoredStopVisitStructure>();
    String directionId = filters.get(Filters.DIRECTION_REF);
    int maximumStopVisits = SiriSupportV2.convertToNumeric(filters.get(Filters.MAX_STOP_VISITS), Integer.MAX_VALUE);
    Integer minimumStopVisitsPerLine = SiriSupportV2.convertToNumeric(filters.get(Filters.MIN_STOP_VISITS), null);
    Map<AgencyAndId, Integer> visitCountByLine = new HashMap<AgencyAndId, Integer>();
    int visitCount = 0;
    for (ArrivalAndDepartureBean adBean : getArrivalsAndDeparturesForStop(stopId, currentTime)) {
        TripStatusBean statusBeanForCurrentTrip = adBean.getTripStatus();
        TripBean tripBeanForAd = adBean.getTrip();
        if (statusBeanForCurrentTrip == null)
            continue;
        if (!_presentationService.include(statusBeanForCurrentTrip) || !_presentationService.include(adBean, statusBeanForCurrentTrip))
            continue;
        MonitoredStopVisitStructure stopVisit = new MonitoredStopVisitStructure();
        stopVisit.setRecordedAtTime(DateUtil.toXmlGregorianCalendar(statusBeanForCurrentTrip.getLastUpdateTime()));
        List<TimepointPredictionRecord> timePredictionRecords = null;
        timePredictionRecords = _transitDataService.getPredictionRecordsForTrip(AgencyAndId.convertFromString(stopId).getAgencyId(), statusBeanForCurrentTrip);
        MonitoredVehicleJourneyStructure mvjourney = new MonitoredVehicleJourneyStructure();
        if (!TransitDataConstants.STATUS_CANCELED.equals(statusBeanForCurrentTrip.getStatus())) {
            stopVisit.setMonitoredVehicleJourney(mvjourney);
            boolean showApc = useApc();
            SiriSupportV2.fillMonitoredVehicleJourney(mvjourney, tripBeanForAd, statusBeanForCurrentTrip, adBean.getStop(), OnwardCallsMode.STOP_MONITORING, _presentationService, _transitDataService, maximumOnwardCalls, timePredictionRecords, statusBeanForCurrentTrip.isPredicted(), showApc, detailLevel, currentTime, filters);
        }
        // FILTERS
        AgencyAndId thisRouteId = AgencyAndIdLibrary.convertFromString(mvjourney.getLineRef().getValue());
        String thisDirectionId = mvjourney.getDirectionRef().getValue();
        if (routeIds.size() > 0 && !routeIds.contains(thisRouteId))
            continue;
        if (directionId != null && !thisDirectionId.equals(directionId))
            continue;
        // Monitored Stop Visits
        Map<String, MonitoredStopVisitStructure> visitsMap = new HashMap<String, MonitoredStopVisitStructure>();
        // visit count filters
        Integer visitCountForThisLine = visitCountByLine.get(thisRouteId);
        if (visitCountForThisLine == null) {
            visitCountForThisLine = 0;
        }
        if (visitCount >= maximumStopVisits) {
            if (minimumStopVisitsPerLine == null) {
                break;
            } else {
                if (visitCountForThisLine >= minimumStopVisitsPerLine) {
                    continue;
                }
            }
        }
        // unique stops filters
        if (stopVisit.getMonitoredVehicleJourney() == null || stopVisit.getMonitoredVehicleJourney().getVehicleRef() == null || StringUtils.isBlank(stopVisit.getMonitoredVehicleJourney().getVehicleRef().getValue())) {
            continue;
        } else {
            String visitKey = stopVisit.getMonitoredVehicleJourney().getVehicleRef().getValue();
            if (visitsMap.containsKey(stopVisit.getMonitoredVehicleJourney().getVehicleRef().getValue())) {
                if (stopVisit.getMonitoredVehicleJourney().getProgressStatus() == null) {
                    visitsMap.remove(visitKey);
                    visitsMap.put(visitKey, stopVisit);
                }
                continue;
            } else {
                visitsMap.put(stopVisit.getMonitoredVehicleJourney().getVehicleRef().getValue(), stopVisit);
            }
        }
        output.add(stopVisit);
        visitCount++;
        visitCountForThisLine++;
        visitCountByLine.put(thisRouteId, visitCountForThisLine);
    }
    Collections.sort(output, new Comparator<MonitoredStopVisitStructure>() {

        public int compare(MonitoredStopVisitStructure arg0, MonitoredStopVisitStructure arg1) {
            try {
                SiriExtensionWrapper wrapper0 = (SiriExtensionWrapper) arg0.getMonitoredVehicleJourney().getMonitoredCall().getExtensions().getAny();
                SiriExtensionWrapper wrapper1 = (SiriExtensionWrapper) arg1.getMonitoredVehicleJourney().getMonitoredCall().getExtensions().getAny();
                return wrapper0.getDistances().getDistanceFromCall().compareTo(wrapper1.getDistances().getDistanceFromCall());
            } catch (Exception e) {
                return -1;
            }
        }
    });
    return output;
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SiriExtensionWrapper(org.onebusaway.transit_data_federation.siri.SiriExtensionWrapper) TripBean(org.onebusaway.transit_data.model.trips.TripBean) MonitoredStopVisitStructure(uk.org.siri.siri_2.MonitoredStopVisitStructure) ArrivalAndDepartureBean(org.onebusaway.transit_data.model.ArrivalAndDepartureBean) MonitoredVehicleJourneyStructure(uk.org.siri.siri_2.MonitoredVehicleJourneyStructure) TimepointPredictionRecord(org.onebusaway.realtime.api.TimepointPredictionRecord) TripStatusBean(org.onebusaway.transit_data.model.trips.TripStatusBean)

Aggregations

ArrayList (java.util.ArrayList)2 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)2 MonitoredVehicleJourneyStructure (uk.org.siri.siri_2.MonitoredVehicleJourneyStructure)2 IOException (java.io.IOException)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Duration (javax.xml.datatype.Duration)1 DetailLevel (org.onebusaway.api.actions.siri.model.DetailLevel)1 TimepointPredictionRecord (org.onebusaway.realtime.api.TimepointPredictionRecord)1 ArrivalAndDepartureBean (org.onebusaway.transit_data.model.ArrivalAndDepartureBean)1 ListBean (org.onebusaway.transit_data.model.ListBean)1 VehicleStatusBean (org.onebusaway.transit_data.model.VehicleStatusBean)1 TripBean (org.onebusaway.transit_data.model.trips.TripBean)1 TripStatusBean (org.onebusaway.transit_data.model.trips.TripStatusBean)1 SiriExtensionWrapper (org.onebusaway.transit_data_federation.siri.SiriExtensionWrapper)1 FeedScopedId (org.opentripplanner.model.FeedScopedId)1 Stop (org.opentripplanner.model.Stop)1 TripTimes (org.opentripplanner.routing.trippattern.TripTimes)1 MonitoredCallStructure (uk.org.siri.siri20.MonitoredCallStructure)1 MonitoredVehicleJourneyStructure (uk.org.siri.siri20.MonitoredVehicleJourneyStructure)1