All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.opentripplanner.netex.mapping.TariffZoneMapper Maven / Gradle / Ivy

package org.opentripplanner.netex.mapping;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import java.time.LocalDateTime;
import java.util.Collection;
import org.opentripplanner.netex.index.api.ReadOnlyHierarchicalVersionMapById;
import org.opentripplanner.netex.mapping.support.FeedScopedIdFactory;
import org.opentripplanner.transit.model.framework.FeedScopedId;
import org.opentripplanner.transit.model.site.FareZone;
import org.rutebanken.netex.model.TariffZone;
import org.rutebanken.netex.model.TariffZoneRef;

class TariffZoneMapper {

  private final LocalDateTime startOfPeriod;
  private final FeedScopedIdFactory idFactory;
  private final ReadOnlyHierarchicalVersionMapById tariffZonesById;
  private final Multimap deduplicateCache = ArrayListMultimap.create();

  TariffZoneMapper(
    LocalDateTime startOfPeriod,
    FeedScopedIdFactory idFactory,
    ReadOnlyHierarchicalVersionMapById tariffZonesById
  ) {
    this.startOfPeriod = startOfPeriod;
    this.idFactory = idFactory;
    this.tariffZonesById = tariffZonesById;
  }

  /**
   * Map all current TariffZones.
   */
  Collection listAllCurrentFareZones() {
    return tariffZonesById
      .localListCurrentVersionEntities(startOfPeriod)
      .stream()
      .map(this::mapTariffZone)
      .toList();
  }

  /**
   * Map Netex TariffZone to OTP TariffZone
   */
  FareZone findAndMapTariffZone(TariffZoneRef ref) {
    var tariffZone = tariffZonesById.lookup(ref, startOfPeriod);
    return (tariffZone == null) ? null : mapTariffZone(tariffZone);
  }

  /**
   * Map Netex TariffZone to OTP TariffZone
   */
  private FareZone mapTariffZone(org.rutebanken.netex.model.TariffZone tariffZone) {
    if (tariffZone == null) {
      return null;
    }

    FeedScopedId id = idFactory.createId(tariffZone.getId());
    String name = tariffZone.getName().getValue();
    return deduplicate(FareZone.of(id).withName(name).build());
  }

  private FareZone deduplicate(FareZone candidate) {
    var existing = deduplicateCache
      .get(candidate.getId())
      .stream()
      .filter(candidate::sameAs)
      .findFirst();

    if (existing.isPresent()) {
      return existing.get();
    }

    deduplicateCache.put(candidate.getId(), candidate);
    return candidate;
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy