Search in sources :

Example 16 with FeedMessage

use of com.google.transit.realtime.GtfsRealtime.FeedMessage in project onebusaway-application-modules by camsys.

the class VehiclePositionsAction method getModel.

@Override
public FeedMessage getModel() {
    FeedMessage cachedVehiclePositions = _cache.getVehiclePositions();
    if (cachedVehiclePositions != null) {
        return cachedVehiclePositions;
    } else {
        FeedMessage.Builder feedMessage = createFeedWithDefaultHeader();
        FeedMessage remoteFeedMessage = null;
        List<String> agencyIds = new ArrayList<String>();
        if (agencyId != null) {
            agencyIds.add(agencyId);
        } else {
            Map<String, List<CoordinateBounds>> agencies = _transitDataService.getAgencyIdsWithCoverageArea();
            agencyIds.addAll(agencies.keySet());
        }
        for (String agencyId : agencyIds) {
            String gtfsrtUrl = getServiceUrl() + agencyId + VEHICLE_UPDATES_COMMAND;
            try {
                remoteFeedMessage = _httpUtil.getFeedMessage(gtfsrtUrl, 30);
                feedMessage.addAllEntity(remoteFeedMessage.getEntityList());
            } catch (Exception e) {
                _log.error(e.getMessage());
            }
        }
        FeedMessage builtFeedMessage = feedMessage.build();
        _cache.putVehiclePositions(builtFeedMessage);
        return builtFeedMessage;
    }
}
Also used : FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 17 with FeedMessage

use of com.google.transit.realtime.GtfsRealtime.FeedMessage in project onebusaway-application-modules by camsys.

the class GtfsRealtimePlaybackController method tripUpdates.

@RequestMapping(value = "/gtfs-realtime/{path:trip-updates|vehicle-positions}")
public void tripUpdates(ServletRequest request, HttpServletResponse response, @RequestParam(value = "key", required = true) String key, @RequestParam(value = "timestamp", required = false) Long timestampInSeconds, @RequestParam(value = "time", required = false) String simpleDate, @RequestParam(value = "interval", required = false, defaultValue = "30") long interval, @PathVariable String path) throws IOException {
    Status status = isAllowed(key);
    if (Status.RATE_EXCEEDED == status) {
        response.sendError(TOO_MANY_REQUESTS);
        return;
    }
    if (Status.AUTHORIZED != status) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    if (simpleDate != null) {
        Date parsed;
        try {
            parsed = DATE_FORMAT.parse(simpleDate);
            timestampInSeconds = parsed.getTime() / 1000;
        } catch (ParseException e) {
        // bury
        }
    }
    if (timestampInSeconds == null) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED, "time or timestamp parameters required");
        return;
    }
    EntityType type = path.equals("trip-updates") ? EntityType.TRIP : EntityType.VEHICLE;
    // will not create new session if time is the same
    Date requestedDate = new Date(timestampInSeconds * 1000);
    _timeService.setCurrentTime(key, requestedDate);
    Date endDate = _timeService.getCurrentTime(key);
    Date startDate = new Date((endDate.getTime() - (interval * 1000)));
    FeedMessage tripUpdates = _gtfsRealtimeRetriever.getFeedMessage(type, startDate, endDate);
    render(request, response, tripUpdates);
}
Also used : Status(org.onebusaway.users.services.ApiKeyPermissionService.Status) EntityType(org.onebusaway.gtfs_realtime.archiver.service.GtfsRealtimeRetriever.EntityType) FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) ParseException(java.text.ParseException) Date(java.util.Date) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with FeedMessage

use of com.google.transit.realtime.GtfsRealtime.FeedMessage in project onebusaway-application-modules by camsys.

the class FeedServiceImplTest method testReadAlerts.

@Test
public void testReadAlerts() {
    // Create GTFS Feed with service alerts
    FeedEntity alertEntityA = createAlert("alertA", TEST_1, DESC_1, CAUSE_1, EFFECT_1, URL_1, TIME_START_1, TIME_END_1, AGENCY_1, ROUTE_1, STOP_1);
    FeedEntity alertEntityB = createAlert("alertB", TEST_2, DESC_2, CAUSE_2, EFFECT_2, URL_2, TIME_START_2, TIME_END_2, AGENCY_2, ROUTE_2, STOP_2);
    FeedEntity alertEntityC = createAlert("alertC", TEST_3, DESC_3, CAUSE_3, EFFECT_3, URL_3, TIME_START_3, TIME_END_3, AGENCY_3, ROUTE_3, STOP_3);
    // Create FeedMessage
    FeedMessage.Builder alerts = createFeed();
    alerts.addEntity(alertEntityA);
    alerts.addEntity(alertEntityB);
    alerts.addEntity(alertEntityC);
    FeedMessage alert = alerts.build();
    _feedService.readAlerts(alert, _entitySource);
    Collection<AlertModel> alertsFromDB = null;
    // the AlertThread, which actually writes to the DB.
    try {
        TimeUnit.SECONDS.sleep(15);
    } catch (Exception ignoredEx) {
    }
    // Get data that was persisted to the database
    try {
        alertsFromDB = (Collection<AlertModel>) _template.find("from AlertModel");
    } catch (Exception ex) {
        ex.getMessage();
        _log.info("find failed: " + ex.getMessage());
    }
    // Check persisted data against the original value.
    _log.info("results size: " + alertsFromDB.size());
    assertEquals(3, alertsFromDB.size());
    for (AlertModel alertFromDB : alertsFromDB) {
        String header = alertFromDB.getHeaderText();
        String desc = alertFromDB.getDescriptionText();
        String cause = alertFromDB.getCause();
        String effect = alertFromDB.getEffect();
        String url = alertFromDB.getUrl();
        long timeStart = 0L;
        long timeEnd = 0L;
        List<TimeRangeModel> timeRanges = alertFromDB.getTimeRanges();
        for (TimeRangeModel tr : timeRanges) {
            timeStart = tr.getStart();
            timeEnd = tr.getEnd();
        }
        String agency = "";
        String route = "";
        String stop = "";
        List<EntitySelectorModel> entitySelectors = alertFromDB.getEntitySelectors();
        for (EntitySelectorModel es : entitySelectors) {
            agency = es.getAgencyId();
            route = es.getRouteId();
            stop = es.getStopId();
        }
        if (header.equals(TEST_1)) {
            assertEquals(TEST_1, header);
            assertEquals(DESC_1, desc);
            assertEquals(CAUSE_1.toString(), cause);
            assertEquals(EFFECT_1.toString(), effect);
            assertEquals(URL_1.toString(), url);
            assertEquals(TIME_START_1, timeStart);
            assertEquals(TIME_END_1, timeEnd);
            assertEquals(AGENCY_1, agency);
            assertEquals(ROUTE_1, route);
            assertEquals(STOP_1, stop);
        } else if (header.equals(TEST_2)) {
            assertEquals(TEST_2, header);
            assertEquals(DESC_2, desc);
            assertEquals(CAUSE_2.toString(), cause);
            assertEquals(EFFECT_2.toString(), effect);
            assertEquals(URL_2.toString(), url);
            assertEquals(TIME_START_2, timeStart);
            assertEquals(TIME_END_2, timeEnd);
            assertEquals(AGENCY_2, agency);
            // Verify that agency has
            assertEquals(AGENCY_2 + "_" + ROUTE_2, route);
            // been prepended to
            // route.
            assertEquals(STOP_2, stop);
        } else if (header.equals(TEST_3)) {
            assertEquals(TEST_3, header);
            assertEquals(DESC_3, desc);
            assertEquals(CAUSE_3.toString(), cause);
            assertEquals(EFFECT_3.toString(), effect);
            assertEquals(URL_3.toString(), url);
            assertEquals(TIME_START_3, timeStart);
            assertEquals(TIME_END_3, timeEnd);
            assertEquals(AGENCY_3, agency);
            assertEquals(ROUTE_3, route);
            // Verify that agency has
            assertEquals(AGENCY_3 + "_" + STOP_3, stop);
        // been prepended to stop.
        }
    }
}
Also used : FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) AlertModel(org.onebusaway.gtfs_realtime.model.AlertModel) TimeRangeModel(org.onebusaway.gtfs_realtime.model.TimeRangeModel) TranslatedString(com.google.transit.realtime.GtfsRealtime.TranslatedString) FeedEntity(com.google.transit.realtime.GtfsRealtime.FeedEntity) EntitySelectorModel(org.onebusaway.gtfs_realtime.model.EntitySelectorModel) IOException(java.io.IOException) Test(org.junit.Test)

Example 19 with FeedMessage

use of com.google.transit.realtime.GtfsRealtime.FeedMessage in project onebusaway-application-modules by camsys.

the class GtfsRealtimeRetrieverImpl method getFeedMessage.

@Override
public FeedMessage getFeedMessage(EntityType type, Date startDate, Date endDate) {
    FeedMessage.Builder builder = FeedMessage.newBuilder();
    List<? extends FeedEntityModel> updates = (type == EntityType.VEHICLE) ? _vehiclePositionDao.findByDate(startDate, endDate) : _tripUpdateDao.findByDate(startDate, endDate);
    long timestamp = 0;
    for (FeedEntityModel update : updates) {
        FeedEntity.Builder fe = fillFeedEntity(update);
        // This is not guaranteed to match entityID in source feed.
        fe.setId(Long.toString(update.getId()));
        builder.addEntity(fe);
        timestamp = Math.max(timestamp, update.getTimestamp().getTime());
    }
    FeedHeader.Builder header = FeedHeader.newBuilder();
    header.setTimestamp(timestamp / 1000);
    header.setGtfsRealtimeVersion(GTFS_RT_VERSION);
    builder.setHeader(header);
    return builder.build();
}
Also used : FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) FeedEntityModel(org.onebusaway.gtfs_realtime.interfaces.FeedEntityModel) FeedEntity(com.google.transit.realtime.GtfsRealtime.FeedEntity) FeedHeader(com.google.transit.realtime.GtfsRealtime.FeedHeader)

Example 20 with FeedMessage

use of com.google.transit.realtime.GtfsRealtime.FeedMessage in project onebusaway-application-modules by camsys.

the class CustomProtocolBufferHandler method fromObject.

@Override
public String fromObject(Object obj, String resultCode, Writer stream) throws IOException {
    if (obj != null && obj instanceof FeedMessage) {
        FeedMessage message = (FeedMessage) obj;
        /**
         * Instead of writing to the output Writer, we write directly to the
         * HttpServletResponse output stream. That way, we can avoid any weirdness
         * with encoding the serialized protobuf to a String.
         */
        HttpServletResponse res = ServletActionContext.getResponse();
        message.writeTo(res.getOutputStream());
    }
    return null;
}
Also used : FeedMessage(com.google.transit.realtime.GtfsRealtime.FeedMessage) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Aggregations

FeedMessage (com.google.transit.realtime.GtfsRealtime.FeedMessage)24 FeedEntity (com.google.transit.realtime.GtfsRealtime.FeedEntity)8 InputStream (java.io.InputStream)6 ArrayList (java.util.ArrayList)6 TripUpdate (com.google.transit.realtime.GtfsRealtime.TripUpdate)4 Date (java.util.Date)4 Test (org.junit.Test)4 ResponseBean (org.onebusaway.api.model.ResponseBean)3 ListBean (org.onebusaway.transit_data.model.ListBean)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 TranslatedString (com.google.transit.realtime.GtfsRealtime.TranslatedString)2 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 List (java.util.List)2 GET (javax.ws.rs.GET)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 Response (javax.ws.rs.core.Response)2 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)2 RouteBean (org.onebusaway.transit_data.model.RouteBean)2