Search in sources :

Example 11 with CoordinateBounds

use of org.onebusaway.geospatial.model.CoordinateBounds in project onebusaway-application-modules by camsys.

the class StopPointsActionTest method initialize.

@Before
public void initialize() throws Exception {
    // Agencies
    Map<String, List<CoordinateBounds>> agencies = new HashMap<String, List<CoordinateBounds>>();
    agencies.put("1", new ArrayList<CoordinateBounds>(Arrays.asList(new CoordinateBounds(47.410813, -122.038662, 47.810813, -122.638662))));
    agencies.put("3", new ArrayList<CoordinateBounds>(Arrays.asList(new CoordinateBounds(0.0, 0.0, 0.0, 0.0))));
    agencies.put("40", new ArrayList<CoordinateBounds>(Arrays.asList(new CoordinateBounds(47.510813, -122.138662, 47.710813, -122.538662))));
    // Route Bean
    Builder routeBuilder = RouteBean.builder();
    routeBuilder.setAgency(new AgencyBean());
    routeBuilder.setId("1_100194");
    routeBean = routeBuilder.create();
    // Route Bean List
    routes = new ArrayList<RouteBean>(1);
    routes.add(routeBean);
    // Stop Bean
    stopBean = new StopBean();
    stopBean.setId("1_430");
    stopBean.setName("3rd Ave & Pine St");
    stopBean.setLon(-122.338662);
    stopBean.setLat(47.610813);
    stopBean.setRoutes(routes);
    // Stop Bean List
    stops = new ArrayList<StopBean>(1);
    stops.add(stopBean);
    // Stop Group
    stopIds = new ArrayList<String>(1);
    stopIds.add(stopBean.getId());
    stopGroupName = new NameBean("destination", "Destination");
    stopGroup = new StopGroupBean();
    stopGroup.setId("0");
    stopGroup.setStopIds(stopIds);
    stopGroup.setName(stopGroupName);
    // Stop Group List
    stopGroups = new ArrayList<StopGroupBean>(1);
    stopGroups.add(stopGroup);
    // Stop Grouping
    stopGrouping = new StopGroupingBean();
    stopGrouping.setStopGroups(stopGroups);
    // Stop Grouping List
    List<StopGroupingBean> stopGroupings = new ArrayList<StopGroupingBean>(1);
    stopGroupings.add(stopGrouping);
    // Stops For Route
    stopsForRouteBean = new StopsForRouteBean();
    stopsForRouteBean.setRoute(routeBean);
    stopsForRouteBean.setStopGroupings(stopGroupings);
    stopsForRouteBean.setStops(stops);
    // LineDirectionStructure
    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");
    // Location Structure
    LocationStructure ls = new LocationStructure();
    BigDecimal lat = new BigDecimal(47.610813);
    BigDecimal lon = new BigDecimal(-122.338662);
    ls.setLongitude(lon.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    ls.setLatitude(lat.setScale(6, BigDecimal.ROUND_HALF_DOWN));
    // StopNames
    NaturalLanguageStringStructure stopName = new NaturalLanguageStringStructure();
    stopName.setValue("3rd Ave & Pine St");
    List<NaturalLanguageStringStructure> stopNames = new ArrayList<NaturalLanguageStringStructure>();
    stopNames.add(stopName);
    // StopPointRef
    StopPointRefStructure stopPointRef = new StopPointRefStructure();
    stopPointRef.setValue("1_430");
    // Monitored
    Boolean monitored = true;
    // AnnotatedStopPointStructure
    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);
    List<AnnotatedStopPointStructure> mockStopPoints = new ArrayList<AnnotatedStopPointStructure>(1);
    mockStopPoints.add(mockStopPoint);
    Map<Boolean, List<AnnotatedStopPointStructure>> annotatedStopPointMap = new HashMap<Boolean, List<AnnotatedStopPointStructure>>();
    annotatedStopPointMap.put(true, mockStopPoints);
    when(realtimeService.getAnnotatedStopPointStructures(anyListOf(String.class), anyListOf(AgencyAndId.class), any(DetailLevel.class), anyLong(), anyMapOf(Filters.class, String.class))).thenReturn(annotatedStopPointMap);
    // XML Serializer
    SiriXmlSerializerV2 serializer = new SiriXmlSerializerV2();
    when(realtimeService.getSiriXmlSerializer()).thenReturn(serializer);
    // Print Writer
    PrintWriter nothingPrintWriter = new PrintWriter(new OutputStream() {

        @Override
        public void write(int b) throws IOException {
        // Do nothing
        }
    });
    when(servletResponse.getWriter()).thenReturn(nothingPrintWriter);
    when(transitDataService.getRouteForId("1_430")).thenReturn(routeBean);
    when(transitDataService.getStopsForRoute("1_430")).thenReturn(stopsForRouteBean);
    when(transitDataService.stopHasUpcomingScheduledService(anyString(), anyLong(), anyString(), anyString(), anyString())).thenReturn(true);
    when(transitDataService.getAgencyIdsWithCoverageArea()).thenReturn(agencies);
}
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) Builder(org.onebusaway.transit_data.model.RouteBean.Builder) StopGroupBean(org.onebusaway.transit_data.model.StopGroupBean) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) StopsForRouteBean(org.onebusaway.transit_data.model.StopsForRouteBean) Matchers.anyString(org.mockito.Matchers.anyString) LocationStructure(uk.org.siri.siri_2.LocationStructure) RouteBean(org.onebusaway.transit_data.model.RouteBean) StopsForRouteBean(org.onebusaway.transit_data.model.StopsForRouteBean) Filters(org.onebusaway.api.actions.siri.impl.SiriSupportV2.Filters) ArrayList(java.util.ArrayList) List(java.util.List) StopPointRefStructure(uk.org.siri.siri_2.StopPointRefStructure) AgencyBean(org.onebusaway.transit_data.model.AgencyBean) PrintWriter(java.io.PrintWriter) AnnotatedStopPointStructure(uk.org.siri.siri_2.AnnotatedStopPointStructure) LineRefStructure(uk.org.siri.siri_2.LineRefStructure) IOException(java.io.IOException) BigDecimal(java.math.BigDecimal) StopGroupingBean(org.onebusaway.transit_data.model.StopGroupingBean) DetailLevel(org.onebusaway.api.actions.siri.model.DetailLevel) SiriXmlSerializerV2(org.onebusaway.transit_data_federation.siri.SiriXmlSerializerV2) StopBean(org.onebusaway.transit_data.model.StopBean) NameBean(org.onebusaway.transit_data.model.NameBean) DirectionRefStructure(uk.org.siri.siri_2.DirectionRefStructure) CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds) Before(org.junit.Before)

Example 12 with CoordinateBounds

use of org.onebusaway.geospatial.model.CoordinateBounds in project onebusaway-application-modules by camsys.

the class SearchBoundsFactory method createBounds.

public CoordinateBounds createBounds() {
    CoordinateBounds bounds = createInternalBounds();
    if (_maxSearchRadius > 0) {
        CoordinateBounds maxBounds = SphericalGeometryLibrary.bounds(_lat, _lon, _maxSearchRadius);
        double latSpan = (bounds.getMaxLat() - bounds.getMinLat());
        double lonSpan = (bounds.getMaxLon() - bounds.getMinLon());
        double maxLatSpan = (maxBounds.getMaxLat() - maxBounds.getMinLat());
        double maxLonSpan = (maxBounds.getMaxLon() - maxBounds.getMinLon());
        if (latSpan > maxLatSpan || lonSpan > maxLonSpan) {
            latSpan = Math.min(latSpan, maxLatSpan);
            lonSpan = Math.min(lonSpan, maxLonSpan);
            bounds = SphericalGeometryLibrary.boundsFromLatLonOffset(_lat, _lon, _latSpan / 2, _lonSpan / 2);
        }
    }
    return bounds;
}
Also used : CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds)

Example 13 with CoordinateBounds

use of org.onebusaway.geospatial.model.CoordinateBounds in project onebusaway-application-modules by camsys.

the class LinesRequestV2Action method index.

public DefaultHttpHeaders index() throws IOException {
    long responseTimestamp = getTime();
    processGoogleAnalytics();
    _realtimeService.setTime(responseTimestamp);
    boolean useLineRefOnly = false;
    Boolean upcomingServiceAllStops = null;
    CoordinateBounds bounds = null;
    boolean validBoundDistance = true;
    // User Parameters
    String boundingBox = _request.getParameter(BOUNDING_BOX);
    String circle = _request.getParameter(CIRCLE);
    String lineRef = _request.getParameter(LINE_REF);
    String directionId = _request.getParameter(DIRECTION_REF);
    String agencyId = _request.getParameter(OPERATOR_REF);
    String hasUpcomingScheduledService = _request.getParameter(UPCOMING_SCHEDULED_SERVICE);
    String detailLevelParam = _request.getParameter(LINES_DETAIL_LEVEL);
    String includePolylines = _request.getParameter(INCLUDE_POLYLINES);
    // 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;
    }
    // Error Strings
    String routeIdsErrorString = "";
    String boundsErrorString = "";
    /*
     * 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<String> agencyIds = processAgencyIds(agencyId);
    List<AgencyAndId> routeIds = new ArrayList<AgencyAndId>();
    routeIdsErrorString = processRouteIds(lineRef, routeIds, agencyIds);
    // Calculate Bounds
    try {
        if (StringUtils.isNotBlank(circle)) {
            bounds = getCircleBounds(circle);
            if (bounds != null && !isValidBoundsDistance(bounds, MAX_BOUNDS_RADIUS)) {
                boundsErrorString += "Provided values exceed allowed search radius of " + MAX_BOUNDS_RADIUS + "m. ";
                validBoundDistance = false;
            }
        } else if (StringUtils.isNotBlank(boundingBox)) {
            bounds = getBoxBounds(boundingBox);
            if (bounds != null && !isValidBoundBoxDistance(bounds, MAX_BOUNDS_DISTANCE)) {
                boundsErrorString += "Provided values exceed allowed search distance of " + MAX_BOUNDS_DISTANCE + "m. ";
                validBoundDistance = false;
            }
        }
    } catch (NumberFormatException nfe) {
        boundsErrorString += ERROR_NON_NUMERIC;
    }
    // Check for case where only LineRef was provided
    if (routeIds.size() > 0) {
        useLineRefOnly = true;
    } else if (bounds == null) {
        boundsErrorString += ERROR_REQUIRED_PARAMS;
    }
    // Setup Filters
    Map<Filters, String> filters = new HashMap<Filters, String>();
    filters.put(Filters.DIRECTION_REF, directionId);
    filters.put(Filters.LINE_REF, lineRef);
    filters.put(Filters.INCLUDE_POLYLINES, includePolylines);
    filters.put(Filters.UPCOMING_SCHEDULED_SERVICE, hasUpcomingScheduledService);
    // Annotated Lines
    List<AnnotatedLineStructure> lines = new ArrayList<AnnotatedLineStructure>();
    Map<Boolean, List<AnnotatedLineStructure>> linesMap;
    // Error Handler
    Exception error = null;
    if ((bounds == null && !useLineRefOnly) || (lineRef != null && routeIds.size() == 0) || !validBoundDistance) {
        String errorString = (boundsErrorString + " " + routeIdsErrorString).trim();
        error = new Exception(errorString);
    } else {
        if (useLineRefOnly) {
            linesMap = _realtimeService.getAnnotatedLineStructures(agencyIds, routeIds, detailLevel, responseTimestamp, filters);
        } else {
            linesMap = _realtimeService.getAnnotatedLineStructures(agencyIds, bounds, detailLevel, responseTimestamp, filters);
        }
        for (Map.Entry<Boolean, List<AnnotatedLineStructure>> entry : linesMap.entrySet()) {
            upcomingServiceAllStops = entry.getKey();
            lines.addAll(entry.getValue());
        }
    }
    _response = generateSiriResponse(lines, upcomingServiceAllStops, error, responseTimestamp);
    try {
        this._servletResponse.getWriter().write(getLines());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AnnotatedLineStructure(uk.org.siri.siri_2.AnnotatedLineStructure) IOException(java.io.IOException) IOException(java.io.IOException) 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) HashMap(java.util.HashMap) Map(java.util.Map) CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds)

Example 14 with CoordinateBounds

use of org.onebusaway.geospatial.model.CoordinateBounds in project onebusaway-application-modules by camsys.

the class RoutesForLocationAction method index.

public DefaultHttpHeaders index() throws IOException, ServiceException {
    int maxCount = _maxCount.getMaxCount();
    if (maxCount <= 0)
        addFieldError("maxCount", "must be greater than zero");
    if (hasErrors())
        return setValidationErrorsResponse();
    CoordinateBounds bounds = getSearchBounds();
    SearchQueryBean routesQuery = new SearchQueryBean();
    if (_query != null)
        routesQuery.setQuery(_query);
    routesQuery.setBounds(bounds);
    routesQuery.setMaxCount(maxCount);
    routesQuery.setType(EQueryType.BOUNDS_OR_CLOSEST);
    try {
        RoutesBean result = _service.getRoutes(routesQuery);
        return transformResult(result);
    } catch (OutOfServiceAreaServiceException ex) {
        return transformOutOfRangeResult();
    }
}
Also used : SearchQueryBean(org.onebusaway.transit_data.model.SearchQueryBean) RoutesBean(org.onebusaway.transit_data.model.RoutesBean) OutOfServiceAreaServiceException(org.onebusaway.exceptions.OutOfServiceAreaServiceException) CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds)

Example 15 with CoordinateBounds

use of org.onebusaway.geospatial.model.CoordinateBounds in project onebusaway-application-modules by camsys.

the class ShapeGeospatialIndexTask method buildShapeSpatialIndex.

private Map<CoordinateBounds, List<AgencyAndId>> buildShapeSpatialIndex() {
    Map<CoordinatePoint, Set<AgencyAndId>> shapeIdsByGridCellCorner = new FactoryMap<CoordinatePoint, Set<AgencyAndId>>(new HashSet<AgencyAndId>());
    CoordinateBounds fullBounds = new CoordinateBounds();
    for (StopEntry stop : _transitGraphDao.getAllStops()) {
        if (stop.getStopLat() > MIN_LAT_LON && stop.getStopLon() > MIN_LAT_LON && stop.getStopLat() < MAX_LAT_LON && stop.getStopLon() < MAX_LAT_LON) {
            fullBounds.addPoint(stop.getStopLat(), stop.getStopLon());
        } else {
            _log.error("rejecting stop " + stop + " for invalid (lat,lon)=" + stop.getStopLat() + ", " + stop.getStopLon());
        }
    }
    if (fullBounds.isEmpty()) {
        return Collections.emptyMap();
    }
    double centerLat = (fullBounds.getMinLat() + fullBounds.getMaxLat()) / 2;
    double centerLon = (fullBounds.getMinLon() + fullBounds.getMaxLon()) / 2;
    CoordinateBounds gridCellExample = SphericalGeometryLibrary.bounds(centerLat, centerLon, _gridSize / 2);
    double latStep = gridCellExample.getMaxLat() - gridCellExample.getMinLat();
    double lonStep = gridCellExample.getMaxLon() - gridCellExample.getMinLon();
    _log.info("generating shape point geospatial index...");
    Set<AgencyAndId> allShapeIds = getAllShapeIds();
    for (AgencyAndId shapeId : allShapeIds) {
        ShapePoints shapePoints = _shapePointHelper.getShapePointsForShapeId(shapeId);
        for (int i = 0; i < shapePoints.getSize(); i++) {
            double lat = shapePoints.getLatForIndex(i);
            double lon = shapePoints.getLonForIndex(i);
            addGridCellForShapePoint(shapeIdsByGridCellCorner, lat, lon, latStep, lonStep, shapeId);
            /**
             * If there is a particularly long stretch between shape points, we want
             * to fill in grid cells in-between
             */
            if (i > 0) {
                double prevLat = shapePoints.getLatForIndex(i - 1);
                double prevLon = shapePoints.getLonForIndex(i - 1);
                double totalDistance = SphericalGeometryLibrary.distance(prevLat, prevLon, lat, lon);
                for (double d = _gridSize; d < totalDistance; d += _gridSize) {
                    double r = d / totalDistance;
                    double latPart = (lat - prevLat) * r + prevLat;
                    double lonPart = (lon - prevLon) * r + prevLon;
                    addGridCellForShapePoint(shapeIdsByGridCellCorner, latPart, lonPart, latStep, lonStep, shapeId);
                }
            }
        }
    }
    _log.info("block shape geospatial nodes: " + shapeIdsByGridCellCorner.size());
    Map<CoordinateBounds, List<AgencyAndId>> shapeIdsByGridCell = new HashMap<CoordinateBounds, List<AgencyAndId>>();
    for (Map.Entry<CoordinatePoint, Set<AgencyAndId>> entry : shapeIdsByGridCellCorner.entrySet()) {
        CoordinatePoint p = entry.getKey();
        CoordinateBounds bounds = new CoordinateBounds(p.getLat(), p.getLon(), p.getLat() + latStep, p.getLon() + lonStep);
        List<AgencyAndId> shapeIds = new ArrayList<AgencyAndId>(entry.getValue());
        shapeIdsByGridCell.put(bounds, shapeIds);
    }
    return shapeIdsByGridCell;
}
Also used : FactoryMap(org.onebusaway.collections.FactoryMap) CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) HashSet(java.util.HashSet) Set(java.util.Set) AgencyAndId(org.onebusaway.gtfs.model.AgencyAndId) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CoordinatePoint(org.onebusaway.geospatial.model.CoordinatePoint) ShapePoints(org.onebusaway.transit_data_federation.model.ShapePoints) StopEntry(org.onebusaway.transit_data_federation.services.transit_graph.StopEntry) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) FactoryMap(org.onebusaway.collections.FactoryMap) CoordinateBounds(org.onebusaway.geospatial.model.CoordinateBounds)

Aggregations

CoordinateBounds (org.onebusaway.geospatial.model.CoordinateBounds)70 Test (org.junit.Test)20 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)16 AgencyAndId (org.onebusaway.gtfs.model.AgencyAndId)15 List (java.util.List)14 SearchQueryBean (org.onebusaway.transit_data.model.SearchQueryBean)12 Map (java.util.Map)9 StopBean (org.onebusaway.transit_data.model.StopBean)9 CoordinatePoint (org.onebusaway.geospatial.model.CoordinatePoint)7 RouteBean (org.onebusaway.transit_data.model.RouteBean)7 StopsBean (org.onebusaway.transit_data.model.StopsBean)7 Envelope (com.vividsolutions.jts.geom.Envelope)5 OutOfServiceAreaServiceException (org.onebusaway.exceptions.OutOfServiceAreaServiceException)5 STRtree (com.vividsolutions.jts.index.strtree.STRtree)4 File (java.io.File)4 IOException (java.io.IOException)4 Filters (org.onebusaway.api.actions.siri.impl.SiriSupportV2.Filters)4 DetailLevel (org.onebusaway.api.actions.siri.model.DetailLevel)4 RoutesBean (org.onebusaway.transit_data.model.RoutesBean)4