DeduplicateServiceIdsStrategy implements GtfsTransformStrategy { @Override public void run(TransformContext context, GtfsMutableRelationalDao dao) { CalendarService service = CalendarServiceDataFactoryImpl.createService(dao); Map<Set<ServiceDate>, List<AgencyAndId>> serviceIdsByServiceDates = new FactoryMap<Set<ServiceDate>, List<AgencyAndId>>( new ArrayList<AgencyAndId>()); for (AgencyAndId serviceId : dao.getAllServiceIds()) { Set<ServiceDate> serviceDates = service.getServiceDatesForServiceId(serviceId); serviceIdsByServiceDates.get(serviceDates).add(serviceId); } Map<AgencyAndId, AgencyAndId> serviceIdMapping = new HashMap<AgencyAndId, AgencyAndId>(); for (List<AgencyAndId> serviceIds : serviceIdsByServiceDates.values()) { Collections.sort(serviceIds); if (serviceIds.size() == 1) { continue; } AgencyAndId target = serviceIds.get(0); for (int i = 1; i < serviceIds.size(); ++i) { AgencyAndId source = serviceIds.get(i); serviceIdMapping.put(source, target); } } for (Trip trip : dao.getAllTrips()) { AgencyAndId mappedServiceId = serviceIdMapping.get(trip.getServiceId()); if (mappedServiceId != null) { trip.setServiceId(mappedServiceId); } } for (AgencyAndId serviceId : serviceIdMapping.keySet()) { ServiceCalendar serviceCalendar = dao.getCalendarForServiceId(serviceId); if (serviceCalendar != null) { dao.removeEntity(serviceCalendar); } for (ServiceCalendarDate date : dao.getCalendarDatesForServiceId(serviceId)) { dao.removeEntity(date); } } _log.info("removed {} duplicate service ids", serviceIdMapping.size()); UpdateLibrary.clearDaoCache(dao); }  @Override String getName(); @Override void run(TransformContext context, GtfsMutableRelationalDao dao);  }
@Test public void test() throws IOException { _gtfs.putTrips(2, "r0", "sid0,sid1"); _gtfs.putCalendars(2, "start_date=20120630", "end_date=20121224", "mask=1111100"); GtfsMutableRelationalDao dao = _gtfs.read(); assertEquals(2, dao.getAllCalendars().size()); _strategy.run(_context, dao); assertEquals(1, dao.getAllCalendars().size()); AgencyAndId serviceId = new AgencyAndId("a0", "sid0"); assertNotNull(dao.getCalendarForServiceId(serviceId)); for (Trip trip : dao.getAllTrips()) { assertEquals(serviceId, trip.getServiceId()); } assertNull(dao.getCalendarForServiceId(new AgencyAndId("a0", "sid1"))); }