proj_name
stringclasses
26 values
relative_path
stringlengths
42
188
class_name
stringlengths
2
53
func_name
stringlengths
2
49
masked_class
stringlengths
68
178k
func_body
stringlengths
56
6.8k
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Transfer.java
Transfer
loadOneRow
class Transfer extends Entity { private static final long serialVersionUID = -4944512120812641063L; public String from_stop_id; public String to_stop_id; public int transfer_type; public int min_transfer_time; public String from_route_id; public String to_route_id; public String from_trip_id; public String to_trip_id; @Override public String toString() { return "Transfer{" + "from_stop_id='" + from_stop_id + '\'' + ", to_stop_id='" + to_stop_id + '\'' + ", transfer_type=" + transfer_type + ", min_transfer_time=" + min_transfer_time + ", from_route_id='" + from_route_id + '\'' + ", to_route_id='" + to_route_id + '\'' + ", from_trip_id='" + from_trip_id + '\'' + ", to_trip_id='" + to_trip_id + '\'' + '}'; } public static class Loader extends Entity.Loader<Transfer> { public Loader(GTFSFeed feed) { super(feed, "transfers"); } @Override protected boolean isRequired() { return false; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } @Override public Transfer clone() { try { return (Transfer) super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } }
Transfer tr = new Transfer(); tr.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index tr.from_stop_id = getStringField("from_stop_id", true); tr.to_stop_id = getStringField("to_stop_id", true); tr.transfer_type = getIntField("transfer_type", true, 0, 3); tr.min_transfer_time = getIntField("min_transfer_time", false, 0, Integer.MAX_VALUE); tr.from_route_id = getStringField("from_route_id", false); tr.to_route_id = getStringField("to_route_id", false); tr.from_trip_id = getStringField("from_trip_id", false); tr.to_trip_id = getStringField("to_trip_id", false); getRefField("from_stop_id", true, feed.stops); getRefField("to_stop_id", true, feed.stops); getRefField("from_route_id", false, feed.routes); getRefField("to_route_id", false, feed.routes); getRefField("from_trip_id", false, feed.trips); getRefField("to_trip_id", false, feed.trips); tr.feed = feed; feed.transfers.put(Long.toString(row), tr);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/conveyal/gtfs/model/Trip.java
Trip
loadOneRow
class Trip extends Entity { private static final long serialVersionUID = -4869384750974542712L; public String route_id; public String service_id; public String trip_id; public String trip_headsign; public String trip_short_name; public int direction_id; public String block_id; public String shape_id; public int bikes_allowed; public int wheelchair_accessible; public String feed_id; public static class Loader extends Entity.Loader<Trip> { public Loader(GTFSFeed feed) { super(feed, "trips"); } @Override protected boolean isRequired() { return true; } @Override public void loadOneRow() throws IOException {<FILL_FUNCTION_BODY>} } }
Trip t = new Trip(); t.sourceFileLine = row + 1; // offset line number by 1 to account for 0-based row index t.route_id = getStringField("route_id", true); t.service_id = getStringField("service_id", true); t.trip_id = getStringField("trip_id", true); t.trip_headsign = getStringField("trip_headsign", false); t.trip_short_name = getStringField("trip_short_name", false); t.direction_id = getIntField("direction_id", false, 0, 1); t.block_id = getStringField("block_id", false); // make a blocks multimap t.shape_id = getStringField("shape_id", false); t.bikes_allowed = getIntField("bikes_allowed", false, 0, 2); t.wheelchair_accessible = getIntField("wheelchair_accessible", false, 0, 2); t.feed = feed; t.feed_id = feed.feedId; feed.trips.put(t.trip_id, t); /* Check referential integrity without storing references. Trip cannot directly reference Services or Routes because they would be serialized into the MapDB. */ // TODO confirm existence of shape ID getRefField("service_id", true, feed.services); getRefField("route_id", true, feed.routes);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/GHLocation.java
GHLocation
fromString
class GHLocation { private static final Pattern PATTERN = Pattern.compile("^Stop\\((.*)\\)$"); public static GHLocation fromString(String s) {<FILL_FUNCTION_BODY>} }
final Matcher matcher = PATTERN.matcher(s); if (matcher.find()) { return new GHStationLocation(matcher.group(1)); } else { return new GHPointLocation(GHPoint.fromString(s)); }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/GtfsHelper.java
GtfsHelper
time
class GtfsHelper { private GtfsHelper() { } private static final int SECONDS_IN_MINUTE = 60; private static final int MINUTES_IN_HOUR = 60; private static final int HOURS_IN_DAY = 24; private static final int SECONDS_IN_HOUR = SECONDS_IN_MINUTE * MINUTES_IN_HOUR; public static int time(int hours, int minutes, int seconds) {<FILL_FUNCTION_BODY>} public static int time(int hours, int minutes) { return time(hours, minutes, 0); } public static int time(LocalDateTime localDateTime) { return time(localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond()); } public static int time(LocalTime localTime) { return time(localTime.getHour(), localTime.getMinute(), localTime.getSecond()); } public static LocalDateTime localDateTimeFromDate(Date date) { return LocalDateTime.parse(new SimpleDateFormat("YYYY-MM-dd'T'HH:mm", Locale.ROOT).format(date)); } }
return (hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds) * 1000;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/Label.java
Label
getTransitions
class Label { static class Transition { final Label label; final GraphExplorer.MultiModalEdge edge; Transition(Label label, GraphExplorer.MultiModalEdge edge) { this.label = label; this.edge = edge; } @Override public String toString() { return (edge != null ? edge.toString() + " -> " : "") + label.node; } } public boolean deleted = false; public final long currentTime; public final GraphExplorer.MultiModalEdge edge; public final NodeId node; public final int nTransfers; public final Long departureTime; public final long streetTime; public final long extraWeight; final long residualDelay; final boolean impossible; public final Label parent; Label(long currentTime, GraphExplorer.MultiModalEdge edge, NodeId node, int nTransfers, Long departureTime, long streetTime, long extraWeight, long residualDelay, boolean impossible, Label parent) { this.currentTime = currentTime; this.edge = edge; this.node = node; this.nTransfers = nTransfers; this.departureTime = departureTime; this.streetTime = streetTime; this.extraWeight = extraWeight; this.residualDelay = residualDelay; this.impossible = impossible; this.parent = parent; } @Override public String toString() { return node + " " + (departureTime != null ? Instant.ofEpochMilli(departureTime) : "---") + "\t" + nTransfers + "\t" + Instant.ofEpochMilli(currentTime); } static List<Label.Transition> getTransitions(Label _label, boolean arriveBy) {<FILL_FUNCTION_BODY>} public static class NodeId { public NodeId(int streetNode, int ptNode) { this.streetNode = streetNode; this.ptNode = ptNode; } public int streetNode; public int ptNode; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NodeId nodeId = (NodeId) o; return streetNode == nodeId.streetNode && ptNode == nodeId.ptNode; } @Override public int hashCode() { int result = 1; result = 31 * result + streetNode; result = 31 * result + ptNode; return result; } @Override public String toString() { return "NodeId{" + "streetNode=" + streetNode + ", ptNode=" + ptNode + '}'; } } }
Label label = _label; boolean reverseEdgeFlags = !arriveBy; List<Label.Transition> result = new ArrayList<>(); if (!reverseEdgeFlags) { result.add(new Label.Transition(label, null)); } while (label.parent != null) { Label.Transition transition; if (reverseEdgeFlags) { transition = new Label.Transition(label, label.edge); } else { transition = new Label.Transition(label.parent, label.edge); } label = label.parent; result.add(transition); } if (reverseEdgeFlags) { result.add(new Label.Transition(label, null)); Collections.reverse(result); } return result;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/MultiCriteriaLabelSetting.java
MultiCriteriaLabelSetting
compare
class MultiCriteriaLabelSetting { private final Comparator<Label> queueComparator; private final List<Label> targetLabels; private long startTime; private final Map<Label.NodeId, List<Label>> fromMap; private final PriorityQueue<Label> fromHeap; private final long maxProfileDuration; private final boolean reverse; private final boolean mindTransfers; private final boolean profileQuery; private final GraphExplorer explorer; private double betaTransfers = 0.0; private IntToLongFunction transferPenaltiesByRouteType = (routeType -> 0L); private double betaStreetTime = 1.0; private long limitTripTime = Long.MAX_VALUE; private long limitStreetTime = Long.MAX_VALUE; public MultiCriteriaLabelSetting(GraphExplorer explorer, boolean reverse, boolean mindTransfers, boolean profileQuery, long maxProfileDuration, List<Label> solutions) { this.explorer = explorer; this.reverse = reverse; this.mindTransfers = mindTransfers; this.profileQuery = profileQuery; this.maxProfileDuration = maxProfileDuration; this.targetLabels = solutions; queueComparator = new LabelComparator(); fromHeap = new PriorityQueue<>(queueComparator); fromMap = new HashMap<>(); } public Iterable<Label> calcLabels(Label.NodeId from, Instant startTime) { this.startTime = startTime.toEpochMilli(); return () -> Spliterators.iterator(new MultiCriteriaLabelSettingSpliterator(from)); } void setBetaTransfers(double betaTransfers) { this.betaTransfers = betaTransfers; } void setBetaStreetTime(double betaWalkTime) { this.betaStreetTime = betaWalkTime; } void setBoardingPenaltyByRouteType(IntToLongFunction transferPenaltiesByRouteType) { this.transferPenaltiesByRouteType = transferPenaltiesByRouteType; } private class MultiCriteriaLabelSettingSpliterator extends Spliterators.AbstractSpliterator<Label> { MultiCriteriaLabelSettingSpliterator(Label.NodeId from) { super(0, 0); Label label = new Label(startTime, null, from, 0, null, 0, 0L, 0, false, null); ArrayList<Label> labels = new ArrayList<>(1); labels.add(label); fromMap.put(from, labels); fromHeap.add(label); } @Override public boolean tryAdvance(Consumer<? super Label> action) { while (!fromHeap.isEmpty() && fromHeap.peek().deleted) fromHeap.poll(); if (fromHeap.isEmpty()) { return false; } else { Label label = fromHeap.poll(); action.accept(label); for (GraphExplorer.MultiModalEdge edge : explorer.exploreEdgesAround(label)) { long nextTime; if (reverse) { nextTime = label.currentTime - explorer.calcTravelTimeMillis(edge, label.currentTime); } else { nextTime = label.currentTime + explorer.calcTravelTimeMillis(edge, label.currentTime); } int nTransfers = label.nTransfers + edge.getTransfers(); long extraWeight = label.extraWeight; Long firstPtDepartureTime = label.departureTime; GtfsStorage.EdgeType edgeType = edge.getType(); if (!reverse && (edgeType == GtfsStorage.EdgeType.ENTER_PT) || reverse && (edgeType == GtfsStorage.EdgeType.EXIT_PT)) { extraWeight += transferPenaltiesByRouteType.applyAsLong(edge.getRouteType()); } if (edgeType == GtfsStorage.EdgeType.TRANSFER) { extraWeight += transferPenaltiesByRouteType.applyAsLong(edge.getRouteType()); } if (!reverse && (edgeType == GtfsStorage.EdgeType.ENTER_TIME_EXPANDED_NETWORK || edgeType == GtfsStorage.EdgeType.WAIT)) { if (label.nTransfers == 0) { firstPtDepartureTime = nextTime - label.streetTime; } } else if (reverse && (edgeType == GtfsStorage.EdgeType.LEAVE_TIME_EXPANDED_NETWORK || edgeType == GtfsStorage.EdgeType.WAIT_ARRIVAL)) { if (label.nTransfers == 0) { firstPtDepartureTime = nextTime + label.streetTime; } } long walkTime = label.streetTime + (edgeType == GtfsStorage.EdgeType.HIGHWAY || edgeType == GtfsStorage.EdgeType.ENTER_PT || edgeType == GtfsStorage.EdgeType.EXIT_PT ? ((reverse ? -1 : 1) * (nextTime - label.currentTime)) : 0); if (walkTime > limitStreetTime) continue; if (Math.abs(nextTime - startTime) > limitTripTime) continue; boolean result = false; if (label.edge != null) { result = label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT; } if (edgeType == GtfsStorage.EdgeType.ENTER_PT && result) { continue; } boolean impossible = label.impossible || explorer.isBlocked(edge) || (!reverse) && edgeType == GtfsStorage.EdgeType.BOARD && label.residualDelay > 0 || reverse && edgeType == GtfsStorage.EdgeType.ALIGHT && label.residualDelay < explorer.getDelayFromAlightEdge(edge, label.currentTime); long residualDelay; if (!reverse) { if (edgeType == GtfsStorage.EdgeType.WAIT || edgeType == GtfsStorage.EdgeType.TRANSFER) { residualDelay = Math.max(0, label.residualDelay - explorer.calcTravelTimeMillis(edge, label.currentTime)); } else if (edgeType == GtfsStorage.EdgeType.ALIGHT) { residualDelay = label.residualDelay + explorer.getDelayFromAlightEdge(edge, label.currentTime); } else if (edgeType == GtfsStorage.EdgeType.BOARD) { residualDelay = -explorer.getDelayFromBoardEdge(edge, label.currentTime); } else { residualDelay = label.residualDelay; } } else { if (edgeType == GtfsStorage.EdgeType.WAIT || edgeType == GtfsStorage.EdgeType.TRANSFER) { residualDelay = label.residualDelay + explorer.calcTravelTimeMillis(edge, label.currentTime); } else { residualDelay = 0; } } if (!reverse && edgeType == GtfsStorage.EdgeType.LEAVE_TIME_EXPANDED_NETWORK && residualDelay > 0) { Label newImpossibleLabelForDelayedTrip = new Label(nextTime, edge, edge.getAdjNode(), nTransfers, firstPtDepartureTime, walkTime, extraWeight, residualDelay, true, label); insertIfNotDominated(newImpossibleLabelForDelayedTrip); nextTime += residualDelay; residualDelay = 0; Label newLabel = new Label(nextTime, edge, edge.getAdjNode(), nTransfers, firstPtDepartureTime, walkTime, extraWeight, residualDelay, impossible, label); insertIfNotDominated(newLabel); } else { Label newLabel = new Label(nextTime, edge, edge.getAdjNode(), nTransfers, firstPtDepartureTime, walkTime, extraWeight, residualDelay, impossible, label); insertIfNotDominated(newLabel); } } return true; } } } void insertIfNotDominated(Label me) { Predicate<Label> filter; if (profileQuery && me.departureTime != null) { filter = (targetLabel) -> (!reverse ? prc(me, targetLabel) : rprc(me, targetLabel)); } else { filter = label -> true; } if (isNotDominatedByAnyOf(me, targetLabels, filter)) { List<Label> sptEntries = fromMap.computeIfAbsent(me.node, k -> new ArrayList<>(1)); if (isNotDominatedByAnyOf(me, sptEntries, filter)) { removeDominated(me, sptEntries, filter); sptEntries.add(me); fromHeap.add(me); } } } boolean rprc(Label me, Label they) { return they.departureTime != null && (they.departureTime <= me.departureTime || they.departureTime <= startTime - maxProfileDuration); } boolean prc(Label me, Label they) { return they.departureTime != null && (they.departureTime >= me.departureTime || they.departureTime >= startTime + maxProfileDuration); } boolean isNotDominatedByAnyOf(Label me, Collection<Label> sptEntries, Predicate<Label> filter) { for (Label they : sptEntries) { if (filter.test(they) && dominates(they, me)) { return false; } } return true; } void removeDominated(Label me, Collection<Label> sptEntries, Predicate<Label> filter) { for (Iterator<Label> iterator = sptEntries.iterator(); iterator.hasNext(); ) { Label sptEntry = iterator.next(); if (filter.test(sptEntry) && dominates(me, sptEntry)) { sptEntry.deleted = true; iterator.remove(); } } } private boolean dominates(Label me, Label they) { if (weight(me) > weight(they)) return false; if (mindTransfers && me.nTransfers > they.nTransfers) return false; if (me.impossible && !they.impossible) return false; if (weight(me) < weight(they)) return true; if (mindTransfers && me.nTransfers < they.nTransfers) return true; return queueComparator.compare(me, they) <= 0; } long weight(Label label) { return timeSinceStartTime(label) + (long) (label.nTransfers * betaTransfers) + (long) (label.streetTime * (betaStreetTime - 1.0)) + label.extraWeight; } long timeSinceStartTime(Label label) { return (reverse ? -1 : 1) * (label.currentTime - startTime); } Long departureTimeSinceStartTime(Label label) { return label.departureTime != null ? (reverse ? -1 : 1) * (label.departureTime - startTime) : null; } public void setLimitTripTime(long limitTripTime) { this.limitTripTime = limitTripTime; } public void setLimitStreetTime(long limitStreetTime) { this.limitStreetTime = limitStreetTime; } private class LabelComparator implements Comparator<Label> { @Override public int compare(Label o1, Label o2) {<FILL_FUNCTION_BODY>} } }
int c = Long.compare(weight(o1), weight(o2)); if (c != 0) return c; c = Integer.compare(o1.nTransfers, o2.nTransfers); if (c != 0) return c; c = Long.compare(o1.streetTime, o2.streetTime); if (c != 0) return c; c = Long.compare(o1.departureTime != null ? reverse ? o1.departureTime : -o1.departureTime : 0, o2.departureTime != null ? reverse ? o2.departureTime : -o2.departureTime : 0); if (c != 0) return c; c = Integer.compare(o1.impossible ? 1 : 0, o2.impossible ? 1 : 0); return c;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/PtEdgeAttributes.java
PtEdgeAttributes
toString
class PtEdgeAttributes { public final GtfsStorage.Validity validity; public GtfsStorage.EdgeType type; public int time; public int route_type; public GtfsStorage.FeedIdWithTimezone feedIdWithTimezone; public int transfers; public int stop_sequence; public GtfsRealtime.TripDescriptor tripDescriptor; public GtfsStorage.PlatformDescriptor platformDescriptor; @Override public String toString() {<FILL_FUNCTION_BODY>} public PtEdgeAttributes(GtfsStorage.EdgeType type, int time, GtfsStorage.Validity validity, int route_type, GtfsStorage.FeedIdWithTimezone feedIdWithTimezone, int transfers, int stop_sequence, GtfsRealtime.TripDescriptor tripDescriptor, GtfsStorage.PlatformDescriptor platformDescriptor) { this.type = type; this.time = time; this.validity = validity; this.route_type = route_type; this.feedIdWithTimezone = feedIdWithTimezone; this.transfers = transfers; this.stop_sequence = stop_sequence; this.tripDescriptor = tripDescriptor; this.platformDescriptor = platformDescriptor; } }
return "PtEdgeAttributes{" + "type=" + type + ", time=" + time + ", transfers=" + transfers + '}';
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/PtLocationSnapper.java
PtLocationSnapper
snapAll
class PtLocationSnapper { public static class Result { public final QueryGraph queryGraph; public final List<Label.NodeId> nodes; public final PointList points; public Result(QueryGraph queryGraph, List<Label.NodeId> nodes, PointList points) { this.queryGraph = queryGraph; this.nodes = nodes; this.points = points; } } BaseGraph baseGraph; LocationIndex locationIndex; GtfsStorage gtfsStorage; public PtLocationSnapper(BaseGraph baseGraph, LocationIndex locationIndex, GtfsStorage gtfsStorage) { this.baseGraph = baseGraph; this.locationIndex = locationIndex; this.gtfsStorage = gtfsStorage; } public Result snapAll(List<GHLocation> locations, List<EdgeFilter> snapFilters) {<FILL_FUNCTION_BODY>} private Snap findByStopId(GHStationLocation station, int indexForErrorMessage) { for (Map.Entry<String, GTFSFeed> entry : gtfsStorage.getGtfsFeeds().entrySet()) { final Integer node = gtfsStorage.getStationNodes().get(new GtfsStorage.FeedIdWithStopId(entry.getKey(), station.stop_id)); if (node != null) { Stop stop = gtfsStorage.getGtfsFeeds().get(entry.getKey()).stops.get(station.stop_id); final Snap stationSnap = new Snap(stop.stop_lat, stop.stop_lon); stationSnap.setClosestNode(node); return stationSnap; } } throw new PointNotFoundException("Cannot find station: " + station.stop_id, indexForErrorMessage); } }
PointList points = new PointList(2, false); ArrayList<Snap> pointSnaps = new ArrayList<>(); ArrayList<Supplier<Label.NodeId>> allSnaps = new ArrayList<>(); for (int i = 0; i < locations.size(); i++) { GHLocation location = locations.get(i); if (location instanceof GHPointLocation) { GHPoint point = ((GHPointLocation) location).ghPoint; final Snap closest = locationIndex.findClosest(point.lat, point.lon, snapFilters.get(i)); if (!closest.isValid()) { IntHashSet result = new IntHashSet(); gtfsStorage.getStopIndex().findEdgeIdsInNeighborhood(point.lat, point.lon, 0, result::add); gtfsStorage.getStopIndex().findEdgeIdsInNeighborhood(point.lat, point.lon, 1, result::add); if (result.isEmpty()) { throw new PointNotFoundException("Cannot find point: " + point, i); } IntCursor stopNodeId = result.iterator().next(); for (Map.Entry<GtfsStorage.FeedIdWithStopId, Integer> e : gtfsStorage.getStationNodes().entrySet()) { if (e.getValue() == stopNodeId.value) { Stop stop = gtfsStorage.getGtfsFeeds().get(e.getKey().feedId).stops.get(e.getKey().stopId); final Snap stopSnap = new Snap(stop.stop_lat, stop.stop_lon); stopSnap.setClosestNode(stopNodeId.value); allSnaps.add(() -> new Label.NodeId(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } } else { pointSnaps.add(closest); allSnaps.add(() -> new Label.NodeId(closest.getClosestNode(), gtfsStorage.getStreetToPt().getOrDefault(closest.getClosestNode(), -1))); points.add(closest.getSnappedPoint()); } } else if (location instanceof GHStationLocation) { final Snap stopSnap = findByStopId((GHStationLocation) location, i); allSnaps.add(() -> new Label.NodeId(gtfsStorage.getPtToStreet().getOrDefault(stopSnap.getClosestNode(), -1), stopSnap.getClosestNode())); points.add(stopSnap.getQueryPoint().lat, stopSnap.getQueryPoint().lon); } } QueryGraph queryGraph = QueryGraph.create(baseGraph.getBaseGraph(), pointSnaps); // modifies pointSnaps! List<Label.NodeId> nodes = new ArrayList<>(); for (Supplier<Label.NodeId> supplier : allSnaps) { nodes.add(supplier.get()); } return new Result(queryGraph, nodes, points);
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/analysis/Analysis.java
Analysis
getStopsForNode
class Analysis { public static List<List<GtfsStorage.FeedIdWithStopId>> findStronglyConnectedComponentsOfStopGraph(PtGraph ptGraph) { PtGraphAsAdjacencyList ptGraphAsAdjacencyList = new PtGraphAsAdjacencyList(ptGraph); TarjanSCC.ConnectedComponents components = TarjanSCC.findComponents(ptGraphAsAdjacencyList, EdgeFilter.ALL_EDGES, false); List<List<GtfsStorage.FeedIdWithStopId>> stronglyConnectedComponentsOfStopGraph = new ArrayList<>(); for (IntArrayList component : components.getComponents()) { ArrayList<GtfsStorage.FeedIdWithStopId> stopsOfComponent = new ArrayList<>(); for (IntCursor intCursor : component) { stopsOfComponent.addAll(getStopsForNode(ptGraph, intCursor.value)); } if (!stopsOfComponent.isEmpty()) { stronglyConnectedComponentsOfStopGraph.add(stopsOfComponent); } } BitSetIterator iter = components.getSingleNodeComponents().iterator(); for (int i = iter.nextSetBit(); i >= 0; i = iter.nextSetBit()) { List<GtfsStorage.FeedIdWithStopId> stopsForNode = getStopsForNode(ptGraph, i); if (!stopsForNode.isEmpty()) { stronglyConnectedComponentsOfStopGraph.add(stopsForNode); } } return stronglyConnectedComponentsOfStopGraph; } public static List<GtfsStorage.FeedIdWithStopId> getStopsForNode(PtGraph ptGraph, int i) {<FILL_FUNCTION_BODY>} }
EnumSet<GtfsStorage.EdgeType> inEdgeTypes = EnumSet.noneOf(GtfsStorage.EdgeType.class); for (PtGraph.PtEdge ptEdge : ptGraph.backEdgesAround(i)) { inEdgeTypes.add(ptEdge.getType()); } EnumSet<GtfsStorage.EdgeType> outEdgeTypes = EnumSet.noneOf(GtfsStorage.EdgeType.class); for (PtGraph.PtEdge ptEdge : ptGraph.edgesAround(i)) { outEdgeTypes.add(ptEdge.getType()); } if (inEdgeTypes.equals(EnumSet.of(GtfsStorage.EdgeType.EXIT_PT)) && outEdgeTypes.equals((EnumSet.of(ENTER_PT)))) { Set<GtfsStorage.FeedIdWithStopId> stops = new HashSet<>(); ptGraph.backEdgesAround(i).forEach(e -> stops.add(new GtfsStorage.FeedIdWithStopId(e.getAttrs().platformDescriptor.feed_id, e.getAttrs().platformDescriptor.stop_id))); ptGraph.edgesAround(i).forEach(e -> stops.add(new GtfsStorage.FeedIdWithStopId(e.getAttrs().platformDescriptor.feed_id, e.getAttrs().platformDescriptor.stop_id))); return new ArrayList<>(stops); } else { return Collections.emptyList(); }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/analysis/PtGraphAsAdjacencyList.java
PtGraphAsAdjacencyList
next
class PtGraphAsAdjacencyList implements Graph { private final PtGraph ptGraph; public PtGraphAsAdjacencyList(PtGraph ptGraph) { this.ptGraph = ptGraph; } @Override public BaseGraph getBaseGraph() { throw new RuntimeException(); } @Override public int getNodes() { return ptGraph.getNodeCount(); } @Override public int getEdges() { throw new RuntimeException(); } @Override public NodeAccess getNodeAccess() { throw new RuntimeException(); } @Override public BBox getBounds() { throw new RuntimeException(); } @Override public EdgeIteratorState edge(int a, int b) { throw new RuntimeException(); } @Override public EdgeIteratorState getEdgeIteratorState(int edgeId, int adjNode) { throw new RuntimeException(); } @Override public EdgeIteratorState getEdgeIteratorStateForKey(int edgeKey) { throw new RuntimeException(); } @Override public int getOtherNode(int edge, int node) { throw new RuntimeException(); } @Override public boolean isAdjacentToNode(int edge, int node) { throw new RuntimeException(); } @Override public AllEdgesIterator getAllEdges() { throw new RuntimeException(); } @Override public EdgeExplorer createEdgeExplorer(EdgeFilter filter) { return new StationGraphEdgeExplorer(); } @Override public TurnCostStorage getTurnCostStorage() { throw new RuntimeException(); } @Override public Weighting wrapWeighting(Weighting weighting) { throw new RuntimeException(); } private class StationGraphEdgeExplorer implements EdgeExplorer { private int baseNode; @Override public EdgeIterator setBaseNode(int baseNode) { this.baseNode = baseNode; return new StationGraphEdgeIterator(ptGraph.edgesAround(baseNode).iterator()); } private class StationGraphEdgeIterator implements EdgeIterator { private final Iterator<PtGraph.PtEdge> iterator; private PtGraph.PtEdge currentElement; public StationGraphEdgeIterator(Iterator<PtGraph.PtEdge> iterator) { this.iterator = iterator; } @Override public boolean next() {<FILL_FUNCTION_BODY>} @Override public int getEdge() { throw new RuntimeException(); } @Override public int getEdgeKey() { throw new RuntimeException(); } @Override public int getReverseEdgeKey() { throw new RuntimeException(); } @Override public int getBaseNode() { throw new RuntimeException(); } @Override public int getAdjNode() { assert currentElement.getBaseNode() == baseNode; return currentElement.getAdjNode(); } @Override public PointList fetchWayGeometry(FetchMode mode) { throw new RuntimeException(); } @Override public EdgeIteratorState setWayGeometry(PointList list) { throw new RuntimeException(); } @Override public double getDistance() { throw new RuntimeException(); } @Override public EdgeIteratorState setDistance(double dist) { throw new RuntimeException(); } @Override public IntsRef getFlags() { throw new RuntimeException(); } @Override public EdgeIteratorState setFlags(IntsRef edgeFlags) { throw new RuntimeException(); } @Override public boolean get(BooleanEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState set(BooleanEncodedValue property, boolean value) { throw new RuntimeException(); } @Override public boolean getReverse(BooleanEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState setReverse(BooleanEncodedValue property, boolean value) { throw new RuntimeException(); } @Override public EdgeIteratorState set(BooleanEncodedValue property, boolean fwd, boolean bwd) { throw new RuntimeException(); } @Override public int get(IntEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState set(IntEncodedValue property, int value) { throw new RuntimeException(); } @Override public int getReverse(IntEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState setReverse(IntEncodedValue property, int value) { throw new RuntimeException(); } @Override public EdgeIteratorState set(IntEncodedValue property, int fwd, int bwd) { throw new RuntimeException(); } @Override public double get(DecimalEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState set(DecimalEncodedValue property, double value) { throw new RuntimeException(); } @Override public double getReverse(DecimalEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState setReverse(DecimalEncodedValue property, double value) { throw new RuntimeException(); } @Override public EdgeIteratorState set(DecimalEncodedValue property, double fwd, double bwd) { throw new RuntimeException(); } @Override public <T extends Enum<?>> T get(EnumEncodedValue<T> property) { throw new RuntimeException(); } @Override public <T extends Enum<?>> EdgeIteratorState set(EnumEncodedValue<T> property, T value) { throw new RuntimeException(); } @Override public <T extends Enum<?>> T getReverse(EnumEncodedValue<T> property) { throw new RuntimeException(); } @Override public <T extends Enum<?>> EdgeIteratorState setReverse(EnumEncodedValue<T> property, T value) { throw new RuntimeException(); } @Override public <T extends Enum<?>> EdgeIteratorState set(EnumEncodedValue<T> property, T fwd, T bwd) { throw new RuntimeException(); } @Override public String get(StringEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState set(StringEncodedValue property, String value) { throw new RuntimeException(); } @Override public String getReverse(StringEncodedValue property) { throw new RuntimeException(); } @Override public EdgeIteratorState setReverse(StringEncodedValue property, String value) { throw new RuntimeException(); } @Override public EdgeIteratorState set(StringEncodedValue property, String fwd, String bwd) { throw new RuntimeException(); } @Override public String getName() { throw new RuntimeException(); } @Override public EdgeIteratorState setKeyValues(List<KVStorage.KeyValue> list) { throw new RuntimeException(); } @Override public List<KVStorage.KeyValue> getKeyValues() { throw new RuntimeException(); } @Override public Object getValue(String key) { throw new RuntimeException(); } @Override public EdgeIteratorState detach(boolean reverse) { throw new RuntimeException(); } @Override public EdgeIteratorState copyPropertiesFrom(EdgeIteratorState e) { throw new RuntimeException(); } } } }
if (iterator.hasNext()) { this.currentElement = iterator.next(); return true; } else { return false; }
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/fare/Fares.java
Fares
sanitizeFareRules
class Fares { public static Optional<Amount> cheapestFare(Map<String, Map<String, Fare>> fares, Trip trip) { return ticketsBruteForce(fares, trip) .flatMap(tickets -> tickets.stream() .map(ticket -> { Fare fare = fares.get(ticket.feed_id).get(ticket.getFare().fare_id); final BigDecimal priceOfOneTicket = BigDecimal.valueOf(fare.fare_attribute.price); return new Amount(priceOfOneTicket, fare.fare_attribute.currency_type); }) .collect(Collectors.groupingBy(Amount::getCurrencyType, Collectors.mapping(Amount::getAmount, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))) .entrySet() .stream() .findFirst() // TODO: Tickets in different currencies for one trip .map(e -> new Amount(e.getValue(), e.getKey()))); } static Optional<List<Ticket>> ticketsBruteForce(Map<String, Map<String, Fare>> fares, Trip trip) { // Recursively enumerate all packages of tickets with which the trip can be done. // Take the cheapest. TicketPurchaseScoreCalculator ticketPurchaseScoreCalculator = new TicketPurchaseScoreCalculator(); return allShoppingCarts(fares, trip) .max(Comparator.comparingDouble(ticketPurchaseScoreCalculator::calculateScore)) .map(TicketPurchase::getTickets); } static Stream<TicketPurchase> allShoppingCarts(Map<String, Map<String, Fare>> fares, Trip trip) { // Recursively enumerate all packages of tickets with which the trip can be done. List<Trip.Segment> segments = trip.segments; List<List<FareAssignment>> result = allFareAssignments(fares, segments); return result.stream().map(TicketPurchase::new); } private static List<List<FareAssignment>> allFareAssignments(Map<String, Map<String, Fare>> fares, List<Trip.Segment> segments) { // Recursively enumerate all possible ways of assigning trip segments to fares. if (segments.isEmpty()) { ArrayList<List<FareAssignment>> emptyList = new ArrayList<>(); emptyList.add(Collections.emptyList()); return emptyList; } else { List<List<FareAssignment>> result = new ArrayList<>(); Trip.Segment segment = segments.get(0); List<List<FareAssignment>> tail = allFareAssignments(fares, segments.subList(1, segments.size())); Collection<Fare> possibleFares = Fares.possibleFares(fares.get(segment.feed_id), segment); for (Fare fare : possibleFares) { for (List<FareAssignment> tailFareAssignments : tail) { ArrayList<FareAssignment> fairAssignments = new ArrayList<>(tailFareAssignments); FareAssignment fareAssignment = new FareAssignment(segment); fareAssignment.setFare(fare); fairAssignments.add(0, fareAssignment); result.add(fairAssignments); } } return result; } } static Collection<Fare> possibleFares(Map<String, Fare> fares, Trip.Segment segment) { return fares.values().stream().filter(fare -> applies(fare, segment)).collect(toList()); } private static boolean applies(Fare fare, Trip.Segment segment) { return fare.fare_rules.isEmpty() || sanitizeFareRules(fare.fare_rules).stream().anyMatch(rule -> rule.appliesTo(segment)); } static List<SanitizedFareRule> sanitizeFareRules(List<FareRule> gtfsFareRules) {<FILL_FUNCTION_BODY>} }
// Make proper fare rule objects from the CSV-like FareRule ArrayList<SanitizedFareRule> result = new ArrayList<>(); result.addAll(gtfsFareRules.stream().filter(rule -> rule.route_id != null).map(rule -> new RouteRule(rule.route_id)).collect(toList())); result.addAll(gtfsFareRules.stream().filter(rule -> rule.origin_id != null && rule.destination_id != null).map(rule -> new OriginDestinationRule(rule.origin_id, rule.destination_id)).collect(toList())); result.add(gtfsFareRules.stream().filter(rule -> rule.contains_id != null).map(rule -> rule.contains_id).collect(Collectors.collectingAndThen(toList(), ZoneRule::new))); return result;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/fare/TicketPurchase.java
TicketPurchase
getTickets
class TicketPurchase { public final List<FareAssignment> fareAssignments; TicketPurchase(List<FareAssignment> fareAssignments) { this.fareAssignments = fareAssignments; } List<Ticket> getTickets() {<FILL_FUNCTION_BODY>} private String fareKey(FareAssignment fareAssignment) { return fareAssignment.fare.fare_id+"_"+fareAssignment.fare.fare_attribute.feed_id; } int getNSchwarzfahrTrips() { return (int) fareAssignments.stream().filter(assignment -> assignment.fare == null).count(); } }
Map<String, TicketPurchaseScoreCalculator.TempTicket> currentTickets = new HashMap<>(); for (FareAssignment fareAssignment : fareAssignments) { if (fareAssignment.fare != null) { currentTickets.computeIfAbsent(fareKey(fareAssignment), fareId -> new TicketPurchaseScoreCalculator.TempTicket()); currentTickets.compute(fareKey(fareAssignment), (s, tempTicket) -> { if (fareAssignment.segment.getStartTime() > tempTicket.validUntil || tempTicket.nMoreTransfers == 0) { tempTicket.feed_id = fareAssignment.segment.feed_id; tempTicket.fare = fareAssignment.fare; tempTicket.validUntil = fareAssignment.segment.getStartTime() + fareAssignment.fare.fare_attribute.transfer_duration; tempTicket.nMoreTransfers = fareAssignment.fare.fare_attribute.transfers; tempTicket.totalNumber++; return tempTicket; } else { tempTicket.nMoreTransfers--; return tempTicket; } }); } } ArrayList<Ticket> tickets = new ArrayList<>(); for (TicketPurchaseScoreCalculator.TempTicket t : currentTickets.values()) { for (int i = 0; i<t.totalNumber; i++) { tickets.add(new Ticket(t.feed_id, t.fare)); } } return tickets;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/fare/TicketPurchaseScoreCalculator.java
TicketPurchaseScoreCalculator
calculateScore
class TicketPurchaseScoreCalculator { static class TempTicket { String feed_id; Fare fare; int totalNumber = 0; long validUntil; int nMoreTransfers = 0; } double calculateScore(TicketPurchase ticketPurchase) {<FILL_FUNCTION_BODY>} }
double cost = 0; for (Ticket ticket : ticketPurchase.getTickets()) { cost -= ticket.getFare().fare_attribute.price; } return cost - ticketPurchase.getNSchwarzfahrTrips() * 60.0;
graphhopper_graphhopper
graphhopper/reader-gtfs/src/main/java/com/graphhopper/gtfs/fare/ZoneRule.java
ZoneRule
appliesTo
class ZoneRule extends SanitizedFareRule { private final Set<String> zones; ZoneRule(Collection<String> zones) { this.zones = new HashSet<>(zones); } @Override boolean appliesTo(Trip.Segment segment) {<FILL_FUNCTION_BODY>} }
if (zones.isEmpty()) { return false; } else { return zones.containsAll(segment.getZones()); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/tools/Bzip2.java
Bzip2
main
class Bzip2 { public static void main(String[] args) throws IOException {<FILL_FUNCTION_BODY>} }
if (args.length == 0) { throw new IllegalArgumentException("You need to specify the bz2 file!"); } String fromFile = args[0]; if (!fromFile.endsWith(".bz2")) { throw new IllegalArgumentException("You need to specify a bz2 file! But was:" + fromFile); } String toFile = Helper.pruneFileEnd(fromFile); FileInputStream in = new FileInputStream(fromFile); FileOutputStream out = new FileOutputStream(toFile); BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(in); try { final byte[] buffer = new byte[1024 * 8]; int n = 0; while (-1 != (n = bzIn.read(buffer))) { out.write(buffer, 0, n); } } finally { out.close(); bzIn.close(); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/tools/CHImportTest.java
CHImportTest
main
class CHImportTest { public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static void runQueries(GraphHopper hopper, String profile) { // Bavaria, but trying to avoid regions that are not covered BBox bounds = new BBox(10.508422, 12.326602, 47.713457, 49.940615); int numQueries = 10_000; long seed = 123; Random rnd = new Random(seed); AtomicInteger notFoundCount = new AtomicInteger(); MiniPerfTest test = new MiniPerfTest().setIterations(numQueries).start((warmup, run) -> { GHPoint from = getRandomPoint(rnd, bounds); GHPoint to = getRandomPoint(rnd, bounds); GHRequest req = new GHRequest(from, to).setProfile(profile); GHResponse rsp = hopper.route(req); if (rsp.hasErrors()) { if (rsp.getErrors().stream().anyMatch(t -> !(t instanceof PointNotFoundException || t instanceof ConnectionNotFoundException))) throw new IllegalStateException("Unexpected error: " + rsp.getErrors().toString()); notFoundCount.incrementAndGet(); return 0; } else { return (int) rsp.getBest().getRouteWeight(); } }); System.out.println("Total queries: " + numQueries + ", Failed queries: " + notFoundCount.get()); System.out.println(test.getReport()); } private static GHPoint getRandomPoint(Random rnd, BBox bounds) { double lat = bounds.minLat + rnd.nextDouble() * (bounds.maxLat - bounds.minLat); double lon = bounds.minLon + rnd.nextDouble() * (bounds.maxLon - bounds.minLon); return new GHPoint(lat, lon); } }
System.out.println("running for args: " + Arrays.toString(args)); PMap map = PMap.read(args); String vehicle = map.getString("vehicle", "car"); GraphHopperConfig config = new GraphHopperConfig(map); config.putObject("datareader.file", map.getString("pbf", "map-matching/files/leipzig_germany.osm.pbf")); config.putObject("graph.location", map.getString("gh", "ch-import-test-gh")); config.setProfiles(Arrays.asList(new Profile(vehicle))); config.setCHProfiles(Collections.singletonList(new CHProfile(vehicle))); config.putObject(CHParameters.PERIODIC_UPDATES, map.getInt("periodic", 0)); config.putObject(CHParameters.LAST_LAZY_NODES_UPDATES, map.getInt("lazy", 100)); config.putObject(CHParameters.NEIGHBOR_UPDATES, map.getInt("neighbor", 100)); config.putObject(CHParameters.NEIGHBOR_UPDATES_MAX, map.getInt("neighbor_max", 2)); config.putObject(CHParameters.CONTRACTED_NODES, map.getInt("contracted", 100)); config.putObject(CHParameters.LOG_MESSAGES, map.getInt("logs", 20)); config.putObject(CHParameters.EDGE_DIFFERENCE_WEIGHT, map.getDouble("edge_diff", 10)); config.putObject(CHParameters.ORIGINAL_EDGE_COUNT_WEIGHT, map.getDouble("orig_edge", 1)); config.putObject(CHParameters.MAX_POLL_FACTOR_HEURISTIC_NODE, map.getDouble("mpf_heur", 5)); config.putObject(CHParameters.MAX_POLL_FACTOR_CONTRACTION_NODE, map.getDouble("mpf_contr", 200)); GraphHopper hopper = new GraphHopper(); hopper.init(config); if (map.getBool("use_country_rules", false)) // note that using this requires a new import of the base graph! hopper.setCountryRuleFactory(new CountryRuleFactory()); hopper.importOrLoad(); runQueries(hopper, vehicle);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/tools/GraphSpeedMeasurement.java
GraphSpeedMeasurement
main
class GraphSpeedMeasurement { public static void main(String[] strs) {<FILL_FUNCTION_BODY>} }
PMap args = PMap.read(strs); List<String> result = new ArrayList<>(); for (int speedBits = 7; speedBits <= 31; speedBits += 3) { System.out.println("Running measurement for speedBits=" + speedBits); GraphHopperConfig ghConfig = new GraphHopperConfig() .putObject("datareader.file", args.getString("map", "map-matching/files/leipzig_germany.osm.pbf")) .putObject("graph.location", args.getString("location", "graph-speed-measurement") + "-" + speedBits + "-gh") .putObject("graph.dataaccess", args.getString("da", "RAM_STORE")) .putObject("import.osm.ignored_highways", "") .putObject("graph.encoded_values", String.format("car_average_speed|speed_bits=%d,bike_average_speed|speed_bits=%d,foot_average_speed|speed_bits=%d", speedBits, speedBits, speedBits)) .setProfiles(List.of( TestProfiles.accessAndSpeed("car") )); GraphHopper hopper = new GraphHopper() .init(ghConfig) .importOrLoad(); BaseGraph baseGraph = hopper.getBaseGraph(); EncodingManager em = hopper.getEncodingManager(); List<BooleanEncodedValue> booleanEncodedValues = em.getEncodedValues().stream().filter(e -> e instanceof BooleanEncodedValue).map(e -> (BooleanEncodedValue) e).collect(Collectors.toList()); List<IntEncodedValue> intEncodedValues = em.getEncodedValues().stream().filter(e -> e.getClass().equals(IntEncodedValueImpl.class)).map(e -> (IntEncodedValue) e).collect(Collectors.toList()); List<DecimalEncodedValue> decimalEncodedValues = em.getEncodedValues().stream().filter(e -> e instanceof DecimalEncodedValue).map(e -> (DecimalEncodedValue) e).collect(Collectors.toList()); List<EnumEncodedValue> enumEncodedValues = em.getEncodedValues().stream().filter(e -> e.getClass().isAssignableFrom(EnumEncodedValue.class)).map(e -> (EnumEncodedValue) e).collect(Collectors.toList()); EdgeExplorer explorer = baseGraph.createEdgeExplorer(); Random rnd = new Random(123); final int iterations = args.getInt("iters", 1_000_000); // this parameter is quite interesting, because when we do multiple repeats per edge the differences between // caching and not caching should become more clear. if we benefited from caching doing multiple repeats should // not make much of a difference (thinking naively), while not caching should mean we need to do more work. final int repeatsPerEdge = args.getInt("repeats_per_edge", 10); MiniPerfTest t = new MiniPerfTest().setIterations(iterations) .start((warmup, run) -> { EdgeIterator iter = explorer.setBaseNode(rnd.nextInt(baseGraph.getNodes())); double sum = 0; while (iter.next()) { for (int i = 0; i < repeatsPerEdge; i++) { // note that reading **all** the EVs should be in favor of the caching solution, while cases // with many encoded values where only a selected few are read should make the caching less // important. but even in this scenario the caching provides no speedup apparently! for (BooleanEncodedValue ev : booleanEncodedValues) sum += iter.get(ev) ? 1 : 0; for (IntEncodedValue ev : intEncodedValues) sum += iter.get(ev) > 5 ? 1 : 0; for (DecimalEncodedValue ev : decimalEncodedValues) sum += iter.get(ev) > 20 ? 1 : 0; for (EnumEncodedValue ev : enumEncodedValues) sum += iter.get(ev).ordinal(); } } return (int) sum; }); result.add(String.format("bits: %d, ints: %d, took: %.2fms, checksum: %d", speedBits, em.getIntsForFlags(), t.getSum(), t.getDummySum())); System.out.println(result.get(result.size() - 1)); } System.out.println(); System.out.println("### RESULT ###"); for (String res : result) System.out.println(res);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/tools/TagInfoUtil.java
TagInfoUtil
analyzeTags
class TagInfoUtil { private static final String URL_TEMPLATE = "https://taginfo.openstreetmap.org/api/4/key/values?" + "filter=all&sortname=count&sortorder=desc&qtype=value&format=json&key="; private static final Extractor TONS_EXTRACTOR = OSMValueExtractor::stringToTons; private static final Extractor METER_EXTRACTOR = OSMValueExtractor::stringToMeter; private static final Extractor KMH_EXTRACTOR = OSMValueExtractor::stringToKmh; public static void main(String[] args) throws IOException { Map<String, Extractor> keyMap = new LinkedHashMap<>(); keyMap.put("maxweight", TONS_EXTRACTOR); keyMap.put("maxaxleload", TONS_EXTRACTOR); keyMap.put("maxwidth", METER_EXTRACTOR); keyMap.put("maxheight", METER_EXTRACTOR); keyMap.put("maxlength", METER_EXTRACTOR); keyMap.put("maxspeed", KMH_EXTRACTOR); for (Entry<String, Extractor> entry: keyMap.entrySet()) { String key = entry.getKey(); Extractor extractor = entry.getValue(); analyzeTags(key, extractor); } } private static void analyzeTags(String key, Extractor extractor) throws IOException {<FILL_FUNCTION_BODY>} private static List<Tag> loadTags(String key) throws IOException { JsonNode node; try (InputStream in = new URL(URL_TEMPLATE + key).openStream(); BufferedInputStream bufferedIn = new BufferedInputStream(in)) { node = new ObjectMapper().readTree(bufferedIn); } List<Tag> tags = new ArrayList<>(); Iterator<JsonNode> iter = node.path("data").elements(); while (iter.hasNext()) { JsonNode tagElement = iter.next(); String value = tagElement.path("value").asText(); int count = tagElement.path("count").asInt(); tags.add(new Tag(value, count)); } return tags; } private interface Extractor { double extract(String value); } private static class Tag { private final String value; private int count; public Tag(String value, int count) { this.value = value; this.count = count; } public String getValue() { return value; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Tag [value="); builder.append(value); builder.append(", count="); builder.append(count); builder.append("]"); return builder.toString(); } } }
System.out.println("Tag: " + key); Map<String, Tag> parsedMap = new LinkedHashMap<>(); List<Tag> failed = new ArrayList<>(); int count = 0; for (Tag tag : loadTags(key)) { count += tag.getCount(); double val = extractor.extract(tag.getValue()); if (Double.isNaN(val)) { failed.add(tag); continue; } System.out.println("\"" + tag.getValue() + "\" -> " + val); String normalized = Double.toString(val); if (parsedMap.containsKey(normalized)) { Tag existing = parsedMap.get(normalized); existing.setCount(existing.getCount() + tag.getCount()); } else { parsedMap.put(normalized, new Tag(normalized, tag.getCount())); } } for (Tag tag : failed) { System.out.println("Unable to parse \"" + tag.getValue() + "\" (" + tag.getCount() + " occurrences)"); } int parsedCount = parsedMap.values().stream().mapToInt(Tag::getCount).sum(); double percentage = parsedCount / (double) count * 100; System.out.println("Success rate: " + percentage + "%");
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/DebugAStar.java
DebugAStar
updateBestPath
class DebugAStar extends AStar implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; private NodeAccess na; public DebugAStar(Graph graph, Weighting type, TraversalMode tMode, GraphicsWrapper mg) { super(graph, type, tMode); this.mg = mg; na = graph.getNodeAccess(); } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(EdgeIteratorState es, SPTEntry bestEE, int currLoc) {<FILL_FUNCTION_BODY>} }
if (g2 != null) { mg.plotEdge(g2, na.getLat(bestEE.parent.adjNode), na.getLon(bestEE.parent.adjNode), na.getLat(currLoc), na.getLon(currLoc), .8f); } super.updateBestPath(es, bestEE, currLoc);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/DebugAStarBi.java
DebugAStarBi
updateBestPath
class DebugAStarBi extends AStarBidirection implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public DebugAStarBi(Graph graph, Weighting type, TraversalMode tMode, GraphicsWrapper mg) { super(graph, type, tMode); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) {<FILL_FUNCTION_BODY>} @Override public String toString() { return "debugui|" + super.toString(); } }
if (g2 != null) { mg.plotNode(g2, entry.adjNode, Color.YELLOW); } super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/DebugDijkstraBidirection.java
DebugDijkstraBidirection
updateBestPath
class DebugDijkstraBidirection extends DijkstraBidirectionRef implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; private NodeAccess na; public DebugDijkstraBidirection(Graph graph, Weighting type, TraversalMode tMode, GraphicsWrapper mg) { super(graph, type, tMode); this.mg = mg; na = graph.getNodeAccess(); } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) {<FILL_FUNCTION_BODY>} }
if (g2 != null) { mg.plotEdge(g2, na.getLat(entry.parent.adjNode), na.getLon(entry.parent.adjNode), na.getLat(entry.adjNode), na.getLon(entry.adjNode), .8f); } // System.out.println("new node:" + currLoc); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/DebugDijkstraSimple.java
DebugDijkstraSimple
updateBestPath
class DebugDijkstraSimple extends Dijkstra implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public DebugDijkstraSimple(Graph graph, Weighting weighting, TraversalMode tMode, GraphicsWrapper mg) { super(graph, weighting, tMode); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(EdgeIteratorState es, SPTEntry bestEE, int currLoc) {<FILL_FUNCTION_BODY>} }
if (g2 != null) { mg.plotNode(g2, currLoc, Color.YELLOW); } super.updateBestPath(es, bestEE, currLoc);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/DefaultMapLayer.java
DefaultMapLayer
makeTransparent
class DefaultMapLayer implements MapLayer { protected BufferedImage image; private Logger logger = LoggerFactory.getLogger(getClass()); private Rectangle bounds = new Rectangle(); private Graphics2D tmpG; private boolean buffering = true; // a bit transparent: // private RescaleOp op = new RescaleOp(new float[]{1f, 1f, 1f, 0.5f}, new float[4], null); private RescaleOp op = new RescaleOp(new float[]{1f, 1f, 1f, 1f}, new float[4], null); protected abstract void paintComponent(Graphics2D createGraphics); @Override public void paint(Graphics2D mainGraphics) { if (!buffering) { try { paintComponent(mainGraphics); } catch (Exception ex) { logger.error("Problem in paintComponent", ex); } return; } if (image != null) { mainGraphics.drawImage(image, op, bounds.x, bounds.y); } } @Override public void setBuffering(boolean enable) { buffering = enable; } @Override public final void repaint() { if (tmpG != null) { paintComponent(tmpG); } } @Override public Rectangle getBounds() { return bounds; } @Override public void setBounds(Rectangle bounds) { if (image == null || image.getHeight() != bounds.height || image.getWidth() != bounds.width) { image = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB); tmpG = image.createGraphics(); tmpG.setColor(Color.BLACK); tmpG.setBackground(Color.WHITE); } this.bounds = bounds; repaint(); } public void makeTransparent(Graphics2D g2) {<FILL_FUNCTION_BODY>} public void clearGraphics(Graphics2D g2) { g2.clearRect(0, 0, bounds.width, bounds.height); } }
Color col = g2.getColor(); Composite comp = null; // force transparence of this layer only. If no buffering we would clear layers below if (buffering) { comp = g2.getComposite(); g2.setComposite(AlphaComposite.Clear); } g2.setColor(new Color(0, 0, 0, 0)); g2.fillRect(0, 0, bounds.width, bounds.height); g2.setColor(col); if (comp != null) { g2.setComposite(comp); }
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/GraphicsWrapper.java
GraphicsWrapper
scale
class GraphicsWrapper { private final Logger logger = LoggerFactory.getLogger(getClass()); private NodeAccess na; private double scaleX; private double scaleY; private double offsetX; private double offsetY; private BBox bounds = new BBox(-180, 180, -90, 90); public GraphicsWrapper(Graph g) { this.na = g.getNodeAccess(); BBox b = g.getBounds(); scaleX = scaleY = 0.002 * (b.maxLat - b.minLat); offsetY = b.maxLat - 90; offsetX = -b.minLon; } public void setNodeAccess(Graph graph) { this.na = graph.getNodeAccess(); } public double getOffsetX() { return offsetX; } public double getOffsetY() { return offsetY; } public double getScaleX() { return scaleX; } public double getScaleY() { return scaleY; } public void plotText(Graphics2D g2, double lat, double lon, String text) { g2.drawString(text, (int) getX(lon) + 5, (int) getY(lat) + 5); } public void plotDirectedEdge(Graphics2D g2, double lat, double lon, double lat2, double lon2, float width) { g2.setStroke(new BasicStroke(width)); int startLon = (int) getX(lon); int startLat = (int) getY(lat); int destLon = (int) getX(lon2); int destLat = (int) getY(lat2); g2.drawLine(startLon, startLat, destLon, destLat); // only for deep zoom show direction if (scaleX < 0.0001) { g2.setStroke(new BasicStroke(3)); Path2D.Float path = new Path2D.Float(); path.moveTo(destLon, destLat); path.lineTo(destLon + 6, destLat - 2); path.lineTo(destLon + 6, destLat + 2); path.lineTo(destLon, destLat); AffineTransform at = new AffineTransform(); double angle = Math.atan2(lat2 - lat, lon2 - lon); at.rotate(-angle + Math.PI, destLon, destLat); path.transform(at); g2.draw(path); } } public void plotEdge(Graphics2D g2, double lat, double lon, double lat2, double lon2, float width) { g2.setStroke(new BasicStroke(width)); g2.drawLine((int) getX(lon), (int) getY(lat), (int) getX(lon2), (int) getY(lat2)); } public void plotEdge(Graphics2D g2, double lat, double lon, double lat2, double lon2) { plotEdge(g2, lat, lon, lat2, lon2, 1); } public double getX(double lon) { return (lon + offsetX) / scaleX; } public double getY(double lat) { return (90 - lat + offsetY) / scaleY; } public double getLon(int x) { return x * scaleX - offsetX; } public double getLat(int y) { return 90 - (y * scaleY - offsetY); } public void plotNode(Graphics2D g2, int loc, Color c) { plotNode(g2, loc, c, 4); } public void plotNode(Graphics2D g2, int loc, Color c, int size) { plotNode(g2, loc, c, size, ""); } public void plotNode(Graphics2D g2, int loc, Color c, int size, String text) { plotNode(g2, na, loc, c, size, ""); } public void plotNode(Graphics2D g2, NodeAccess na, int loc, Color c, int size, String text) { double lat = na.getLat(loc); double lon = na.getLon(loc); if (lat < bounds.minLat || lat > bounds.maxLat || lon < bounds.minLon || lon > bounds.maxLon) { return; } Color old = g2.getColor(); g2.setColor(c); plot(g2, lat, lon, size); g2.setColor(old); } public void plot(Graphics2D g2, double lat, double lon, int width) { double x = getX(lon); double y = getY(lat); g2.fillOval((int) x, (int) y, width, width); } public void scale(int x, int y, boolean zoomIn) {<FILL_FUNCTION_BODY>} public void setNewOffset(int offX, int offY) { offsetX += offX * scaleX; offsetY += offY * scaleY; } public BBox setBounds(int minX, int maxX, int minY, int maxY) { double minLon = getLon(minX); double maxLon = getLon(maxX); double maxLat = getLat(minY); double minLat = getLat(maxY); bounds = new BBox(minLon, maxLon, minLat, maxLat); return bounds; } }
double tmpFactor = 0.5f; if (!zoomIn) { tmpFactor = 2; } double oldScaleX = scaleX; double oldScaleY = scaleY; double resX = scaleX * tmpFactor; if (resX > 0) { scaleX = resX; } double resY = scaleY * tmpFactor; if (resY > 0) { scaleY = resY; } // respect mouse x,y when scaling // TODO minor bug: compute difference of lat,lon position for mouse before and after scaling if (zoomIn) { offsetX -= (offsetX + x) * scaleX; offsetY -= (offsetY + y) * scaleY; } else { offsetX += x * oldScaleX; offsetY += y * oldScaleY; } logger.info("mouse wheel moved => repaint. zoomIn:" + zoomIn + " " + offsetX + "," + offsetY + " " + scaleX + "," + scaleY);
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/LayeredPanel.java
LayeredPanel
paintComponent
class LayeredPanel extends JPanel { private final Collection<MapLayer> layers; public LayeredPanel() { this(new ArrayList<MapLayer>()); } public LayeredPanel(Collection<MapLayer> layer) { this.layers = layer; this.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { int w = e.getComponent().getWidth(); int h = e.getComponent().getHeight(); System.out.println("mainResized:" + w + " " + h); for (MapLayer ml : layers) { ml.setBounds(new Rectangle(0, 0, w, h)); } repaint(); } }); } public void setBuffering(boolean enable) { for (MapLayer ml : layers) { ml.setBuffering(enable); } } public void addLayer(MapLayer ml) { layers.add(ml); } @Override protected void paintComponent(Graphics g) {<FILL_FUNCTION_BODY>} }
super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; // StopWatch sw = new StopWatch(); g2.clearRect(0, 0, getBounds().width, getBounds().height); // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); // g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED); // int counter = 0; for (MapLayer ml : layers) { // sw.start(); ml.paint(g2); // System.out.println(++counter + " | mainRepaint took " + sw.stop().getSeconds() + " sec"); } // System.out.println("paintComponents");
graphhopper_graphhopper
graphhopper/tools/src/main/java/com/graphhopper/ui/MiniGraphUI.java
MiniGraphUI
visualize
class MiniGraphUI { private final Logger logger = LoggerFactory.getLogger(getClass()); private final BaseGraph graph; private final NodeAccess na; private final MapLayer pathLayer; private final DecimalEncodedValue avSpeedEnc; private final BooleanEncodedValue accessEnc; private final boolean useCH; // for moving int currentPosX; int currentPosY; private LocationIndexTree index; private String latLon = ""; private GraphicsWrapper mg; private JPanel infoPanel; private LayeredPanel mainPanel; private MapLayer roadsLayer; private boolean fastPaint = false; private boolean showQuadTree = false; private Snap fromRes; private Snap toRes; private QueryGraph qGraph; public static void main(String[] strs) { PMap args = PMap.read(strs); args.putObject("datareader.file", args.getString("datareader.file", "core/files/monaco.osm.gz")); args.putObject("graph.location", args.getString("graph.location", "tools/target/mini-graph-ui-gh")); GraphHopperConfig ghConfig = new GraphHopperConfig(args); ghConfig.setProfiles(List.of(TestProfiles.accessAndSpeed("profile", "car").setTurnCostsConfig(TurnCostsConfig.car()))). putObject("import.osm.ignored_highways", ""); ghConfig.setCHProfiles(List.of( new CHProfile("profile") )); ghConfig.setLMProfiles(List.of( new LMProfile("profile") )); GraphHopper hopper = new GraphHopper().init(ghConfig).importOrLoad(); boolean debug = args.getBool("minigraphui.debug", false); boolean useCH = args.getBool("minigraphui.useCH", false); new MiniGraphUI(hopper, debug, useCH).visualize(); } public MiniGraphUI(GraphHopper hopper, boolean debug, boolean useCH) { this.graph = hopper.getBaseGraph(); this.na = graph.getNodeAccess(); accessEnc = hopper.getEncodingManager().getBooleanEncodedValue(VehicleAccess.key("car")); avSpeedEnc = hopper.getEncodingManager().getDecimalEncodedValue(VehicleSpeed.key("car")); this.useCH = useCH; logger.info("locations:" + graph.getNodes() + ", debug:" + debug); mg = new GraphicsWrapper(graph); this.index = (LocationIndexTree) hopper.getLocationIndex(); infoPanel = new JPanel() { @Override protected void paintComponent(Graphics g) { g.setColor(Color.WHITE); Rectangle b = infoPanel.getBounds(); g.fillRect(0, 0, b.width, b.height); g.setColor(Color.BLUE); g.drawString(latLon, 40, 20); g.drawString("scale:" + mg.getScaleX(), 40, 40); int w = mainPanel.getBounds().width; int h = mainPanel.getBounds().height; g.drawString(mg.setBounds(0, w, 0, h).toLessPrecisionString(), 40, 60); } }; mainPanel = new LayeredPanel(); // TODO make it correct with bitset-skipping too final GHBitSet bitset = new GHTBitSet(graph.getNodes()); mainPanel.addLayer(roadsLayer = new DefaultMapLayer() { final Random rand = new Random(); @Override public void paintComponent(final Graphics2D g2) { clearGraphics(g2); Rectangle d = getBounds(); BBox b = mg.setBounds(0, d.width, 0, d.height); if (fastPaint) { rand.setSeed(0); bitset.clear(); } g2.setColor(Color.black); Color[] speedColors = generateColors(15); AllEdgesIterator edge = graph.getAllEdges(); while (edge.next()) { if (fastPaint && rand.nextInt(30) > 1) continue; int nodeIndex = edge.getBaseNode(); double lat = na.getLat(nodeIndex); double lon = na.getLon(nodeIndex); int nodeId = edge.getAdjNode(); double lat2 = na.getLat(nodeId); double lon2 = na.getLon(nodeId); // mg.plotText(g2, lat, lon, "" + nodeIndex); if (!b.contains(lat, lon) && !b.contains(lat2, lon2)) continue; int sum = nodeIndex + nodeId; if (fastPaint) { if (bitset.contains(sum)) continue; bitset.add(sum); } // mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, iter.getName()); //mg.plotText(g2, lat * 0.9 + lat2 * 0.1, lon * 0.9 + lon2 * 0.1, "s:" + (int) encoder.getSpeed(iter.getFlags())); double speed = edge.get(avSpeedEnc); Color color; if (speed >= 120) { // red color = speedColors[12]; } else if (speed >= 100) { color = speedColors[10]; } else if (speed >= 80) { color = speedColors[8]; } else if (speed >= 60) { color = speedColors[6]; } else if (speed >= 50) { color = speedColors[5]; } else if (speed >= 40) { color = speedColors[4]; } else if (speed >= 30) { color = Color.GRAY; } else { color = Color.LIGHT_GRAY; } g2.setColor(color); boolean fwd = edge.get(accessEnc); boolean bwd = edge.getReverse(accessEnc); float width = speed > 90 ? 1f : 0.8f; PointList pl = edge.fetchWayGeometry(FetchMode.ALL); for (int i = 1; i < pl.size(); i++) { if (fwd && !bwd) { mg.plotDirectedEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } else { mg.plotEdge(g2, pl.getLat(i - 1), pl.getLon(i - 1), pl.getLat(i), pl.getLon(i), width); } } } if (showQuadTree) index.query(graph.getBounds(), new LocationIndexTree.Visitor() { @Override public boolean isTileInfo() { return true; } @Override public void onTile(BBox bbox, int depth) { int width = Math.max(1, Math.min(4, 4 - depth)); g2.setColor(Color.GRAY); mg.plotEdge(g2, bbox.minLat, bbox.minLon, bbox.minLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.minLat, bbox.maxLon, bbox.maxLat, bbox.maxLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.maxLon, bbox.maxLat, bbox.minLon, width); mg.plotEdge(g2, bbox.maxLat, bbox.minLon, bbox.minLat, bbox.minLon, width); } @Override public void onEdge(int edgeId) { // mg.plotNode(g2, node, Color.BLUE); } }); g2.setColor(Color.WHITE); g2.fillRect(0, 0, 1000, 20); for (int i = 4; i < speedColors.length; i++) { g2.setColor(speedColors[i]); g2.drawString("" + (i * 10), i * 30 - 100, 10); } g2.setColor(Color.BLACK); } }); mainPanel.addLayer(pathLayer = new DefaultMapLayer() { @Override public void paintComponent(final Graphics2D g2) { if (qGraph == null) return; makeTransparent(g2); RoutingAlgorithm algo = createAlgo(hopper, qGraph); if (algo instanceof DebugAlgo) { ((DebugAlgo) algo).setGraphics2D(g2); } StopWatch sw = new StopWatch().start(); logger.info("start searching with " + algo + " from:" + fromRes + " to:" + toRes); Color red = Color.red.brighter(); g2.setColor(red); mg.plotNode(g2, qGraph.getNodeAccess(), fromRes.getClosestNode(), red, 10, ""); mg.plotNode(g2, qGraph.getNodeAccess(), toRes.getClosestNode(), red, 10, ""); g2.setColor(Color.blue.brighter().brighter()); java.util.List<Path> paths = algo.calcPaths(fromRes.getClosestNode(), toRes.getClosestNode()); sw.stop(); // if directed edges if (paths.isEmpty() || !paths.get(0).isFound()) { logger.warn("path not found! direction not valid?"); return; } Path best = paths.get(0); logger.info("found path in " + sw.getSeconds() + "s with nodes:" + best.calcNodes().size() + ", millis: " + best.getTime() + ", visited nodes:" + algo.getVisitedNodes()); g2.setColor(red); for (Path p : paths) plotPath(p, g2, 3); } }); if (debug) { // disable double buffering to see graphic changes while debugging. E.g. to set a break point in the // algorithm its updateBest method and see the shortest path tree increasing everytime the program continues. RepaintManager repaintManager = RepaintManager.currentManager(mainPanel); repaintManager.setDoubleBufferingEnabled(false); mainPanel.setBuffering(false); } } private RoutingAlgorithm createAlgo(GraphHopper hopper, QueryGraph qGraph) { Profile profile = hopper.getProfiles().iterator().next(); if (useCH) { RoutingCHGraph chGraph = hopper.getCHGraphs().get(profile.getName()); logger.info("CH algo, profile: " + profile.getName()); QueryRoutingCHGraph queryRoutingCHGraph = new QueryRoutingCHGraph(chGraph, qGraph); return new CHDebugAlgo(queryRoutingCHGraph, mg); } else { LandmarkStorage landmarks = hopper.getLandmarks().get(profile.getName()); RoutingAlgorithmFactory algoFactory = (g, w, opts) -> { RoutingAlgorithm algo = new LMRoutingAlgorithmFactory(landmarks).createAlgo(g, w, opts); if (algo instanceof AStarBidirection) { return new DebugAStarBi(g, w, opts.getTraversalMode(), mg). setApproximation(((AStarBidirection) algo).getApproximation()); } else if (algo instanceof AStar) { return new DebugAStar(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof DijkstraBidirectionRef) { return new DebugDijkstraBidirection(g, w, opts.getTraversalMode(), mg); } else if (algo instanceof Dijkstra) { return new DebugDijkstraSimple(g, w, opts.getTraversalMode(), mg); } else return algo; }; AlgorithmOptions algoOpts = new AlgorithmOptions().setAlgorithm(Algorithms.ASTAR_BI). setTraversalMode(TraversalMode.EDGE_BASED); return algoFactory.createAlgo(qGraph, hopper.createWeighting(profile, new PMap()), algoOpts); } } private static class CHDebugAlgo extends DijkstraBidirectionCH implements DebugAlgo { private final GraphicsWrapper mg; private Graphics2D g2; public CHDebugAlgo(RoutingCHGraph graph, GraphicsWrapper mg) { super(graph); this.mg = mg; } @Override public void setGraphics2D(Graphics2D g2) { this.g2 = g2; } @Override public void updateBestPath(double edgeWeight, SPTEntry entry, int origEdgeId, int traversalId, boolean reverse) { if (g2 != null) mg.plotNode(g2, traversalId, Color.YELLOW, 6); super.updateBestPath(edgeWeight, entry, origEdgeId, traversalId, reverse); } } public Color[] generateColors(int n) { Color[] cols = new Color[n]; for (int i = 0; i < n; i++) { cols[i] = Color.getHSBColor((float) i / (float) n, 0.85f, 1.0f); } return cols; } void plotNodeName(Graphics2D g2, int node) { double lat = na.getLat(node); double lon = na.getLon(node); mg.plotText(g2, lat, lon, "" + node); } private Path plotPath(Path tmpPath, Graphics2D g2, int w) { if (!tmpPath.isFound()) { logger.info("cannot plot path as not found: " + tmpPath); return tmpPath; } double prevLat = Double.NaN; double prevLon = Double.NaN; boolean plotNodes = false; IntIndexedContainer nodes = tmpPath.calcNodes(); if (plotNodes) { for (int i = 0; i < nodes.size(); i++) { plotNodeName(g2, nodes.get(i)); } } PointList list = tmpPath.calcPoints(); for (int i = 0; i < list.size(); i++) { double lat = list.getLat(i); double lon = list.getLon(i); if (!Double.isNaN(prevLat)) { mg.plotEdge(g2, prevLat, prevLon, lat, lon, w); } else { mg.plot(g2, lat, lon, w); } prevLat = lat; prevLon = lon; } logger.info("dist:" + tmpPath.getDistance() + ", path points(" + list.size() + ")"); return tmpPath; } public void visualize() {<FILL_FUNCTION_BODY>} void updateLatLon(MouseEvent e) { latLon = mg.getLat(e.getY()) + "," + mg.getLon(e.getX()); infoPanel.repaint(); currentPosX = e.getX(); currentPosY = e.getY(); } void repaintPaths() { pathLayer.repaint(); mainPanel.repaint(); } void repaintRoads() { // avoid threading as there should be no updated to scale or offset while painting // (would to lead to artifacts) StopWatch sw = new StopWatch().start(); pathLayer.repaint(); roadsLayer.repaint(); mainPanel.repaint(); logger.info("roads painting took " + sw.stop().getSeconds() + " sec"); } }
try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { int frameHeight = 800; int frameWidth = 1200; JFrame frame = new JFrame("GraphHopper UI - Small&Ugly ;)"); frame.setLayout(new BorderLayout()); frame.add(mainPanel, BorderLayout.CENTER); frame.add(infoPanel, BorderLayout.NORTH); infoPanel.setPreferredSize(new Dimension(300, 100)); // scale mainPanel.addMouseWheelListener(new MouseWheelListener() { @Override public void mouseWheelMoved(MouseWheelEvent e) { mg.scale(e.getX(), e.getY(), e.getWheelRotation() < 0); repaintRoads(); } }); // listener to investigate findID behavior // MouseAdapter ml = new MouseAdapter() { // // @Override public void mouseClicked(MouseEvent e) { // findIDLat = mg.getLat(e.getY()); // findIDLon = mg.getLon(e.getX()); // findIdLayer.repaint(); // mainPanel.repaint(); // } // // @Override public void mouseMoved(MouseEvent e) { // updateLatLon(e); // } // // @Override public void mousePressed(MouseEvent e) { // updateLatLon(e); // } // }; MouseAdapter ml = new MouseAdapter() { // for routing: double fromLat, fromLon; boolean fromDone = false; boolean dragging = false; @Override public void mouseClicked(MouseEvent e) { if (!fromDone) { fromLat = mg.getLat(e.getY()); fromLon = mg.getLon(e.getX()); } else { double toLat = mg.getLat(e.getY()); double toLon = mg.getLon(e.getX()); StopWatch sw = new StopWatch().start(); logger.info("start searching from " + fromLat + "," + fromLon + " to " + toLat + "," + toLon); // get from and to node id fromRes = index.findClosest(fromLat, fromLon, EdgeFilter.ALL_EDGES); toRes = index.findClosest(toLat, toLon, EdgeFilter.ALL_EDGES); if (fromRes.isValid() && toRes.isValid()) { qGraph = QueryGraph.create(graph, fromRes, toRes); mg.setNodeAccess(qGraph); logger.info("found ids " + fromRes + " -> " + toRes + " in " + sw.stop().getSeconds() + "s"); } repaintPaths(); } fromDone = !fromDone; } @Override public void mouseDragged(MouseEvent e) { dragging = true; fastPaint = true; update(e); updateLatLon(e); } @Override public void mouseReleased(MouseEvent e) { if (dragging) { // update only if mouse release comes from dragging! (at the moment equal to fastPaint) dragging = false; fastPaint = false; update(e); } } public void update(MouseEvent e) { mg.setNewOffset(e.getX() - currentPosX, e.getY() - currentPosY); repaintRoads(); } @Override public void mouseMoved(MouseEvent e) { updateLatLon(e); } @Override public void mousePressed(MouseEvent e) { updateLatLon(e); } }; mainPanel.addMouseListener(ml); mainPanel.addMouseMotionListener(ml); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(frameWidth + 10, frameHeight + 30); frame.setVisible(true); } }); } catch (Exception ex) { throw new RuntimeException(ex); }
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/GHRequest.java
GHRequest
toString
class GHRequest { private List<GHPoint> points; private String profile = ""; private final PMap hints = new PMap(); private List<Double> headings = new ArrayList<>(); private List<String> pointHints = new ArrayList<>(); private List<String> curbsides = new ArrayList<>(); private List<String> snapPreventions = new ArrayList<>(); private List<String> pathDetails = new ArrayList<>(); private String algo = ""; private Locale locale = Locale.US; private CustomModel customModel; public GHRequest() { this(5); } public GHRequest(int size) { points = new ArrayList<>(size); } /** * Creates a routing request from one point (fromLat, fromLon) to another (toLat, toLon) */ public GHRequest(double fromLat, double fromLon, double toLat, double toLon) { this(new GHPoint(fromLat, fromLon), new GHPoint(toLat, toLon)); } public GHRequest(GHPoint startPlace, GHPoint endPlace) { if (startPlace == null) throw new IllegalStateException("'from' cannot be null"); if (endPlace == null) throw new IllegalStateException("'to' cannot be null"); points = new ArrayList<>(2); points.add(startPlace); points.add(endPlace); } /** * @param points List of stopover points in order: start, 1st stop, 2nd stop, ..., end */ public GHRequest(List<GHPoint> points) { this.points = points; } public GHRequest setPoints(List<GHPoint> points) { this.points = points; return this; } public List<GHPoint> getPoints() { return points; } /** * Add stopover point to routing request. * * @param point geographical position (see GHPoint) */ public GHRequest addPoint(GHPoint point) { if (point == null) throw new IllegalArgumentException("point cannot be null"); points.add(point); return this; } /** * Sets the headings, i.e. the direction the route should leave the starting point and the directions the route * should arrive from at the via-points and the end point. Each heading is given as north based azimuth (clockwise) * in [0, 360) or NaN if no direction shall be specified. * <p> * The number of headings must be zero (default), one (for the start point) or equal to the number of points * when sending the request. */ public GHRequest setHeadings(List<Double> headings) { this.headings = headings; return this; } public List<Double> getHeadings() { return headings; } public static boolean isAzimuthValue(double heading) { // heading must be in [0, 360) or NaN return Double.isNaN(heading) || (Double.compare(heading, 360) < 0 && Double.compare(heading, 0) >= 0); } public String getAlgorithm() { return algo; } /** * For possible values see AlgorithmOptions.* */ public GHRequest setAlgorithm(String algo) { if (algo != null) this.algo = Helper.camelCaseToUnderScore(algo); return this; } public Locale getLocale() { return locale; } public GHRequest setLocale(Locale locale) { if (locale != null) this.locale = locale; return this; } public GHRequest setLocale(String localeStr) { return setLocale(Helper.getLocale(localeStr)); } public CustomModel getCustomModel() { return customModel; } public GHRequest setCustomModel(CustomModel customModel) { this.customModel = customModel; return this; } public String getProfile() { return profile; } public GHRequest setProfile(String profile) { this.profile = profile; return this; } public PMap getHints() { return hints; } /** * This method sets a key value pair in the hints and is unrelated to the setPointHints method. * It is mainly used for deserialization with Jackson. * * @see #setPointHints(List) */ // a good trick to serialize unknown properties into the HintsMap @JsonAnySetter public GHRequest putHint(String fieldName, Object value) { this.hints.putObject(fieldName, value); return this; } public GHRequest setPointHints(List<String> pointHints) { this.pointHints = pointHints; return this; } public List<String> getPointHints() { return pointHints; } public GHRequest setCurbsides(List<String> curbsides) { this.curbsides = curbsides; return this; } public List<String> getCurbsides() { return curbsides; } public GHRequest setSnapPreventions(List<String> snapPreventions) { this.snapPreventions = snapPreventions; return this; } public List<String> getSnapPreventions() { return snapPreventions; } @JsonProperty("details") public GHRequest setPathDetails(List<String> pathDetails) { this.pathDetails = pathDetails; return this; } public List<String> getPathDetails() { return this.pathDetails; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
String res = ""; for (GHPoint point : points) { if (res.isEmpty()) { res = point.toString(); } else { res += "; " + point.toString(); } } if (!algo.isEmpty()) res += " (" + algo + ")"; if (!pathDetails.isEmpty()) res += " (PathDetails: " + pathDetails + ")"; if (!hints.isEmpty()) res += " (Hints:" + hints + ")"; return res;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/GHResponse.java
GHResponse
getErrors
class GHResponse { private final List<Throwable> errors = new ArrayList<>(4); private PMap hintsMap = new PMap(); private final List<ResponsePath> responsePaths = new ArrayList<>(5); private String debugInfo = ""; public GHResponse() { } public void add(ResponsePath responsePath) { responsePaths.add(responsePath); } /** * Returns the best path. */ public ResponsePath getBest() { if (responsePaths.isEmpty()) throw new RuntimeException("Cannot fetch best response if list is empty"); return responsePaths.get(0); } /** * This method returns the best path as well as all alternatives. */ public List<ResponsePath> getAll() { return responsePaths; } /** * This method returns true if there are alternative paths available besides the best. */ public boolean hasAlternatives() { return responsePaths.size() > 1; } public void addDebugInfo(String debugInfo) { if (debugInfo == null) throw new IllegalStateException("Debug information has to be none null"); if (!this.debugInfo.isEmpty()) this.debugInfo += "; "; this.debugInfo += debugInfo; } public String getDebugInfo() { String str = debugInfo; for (ResponsePath p : responsePaths) { if (!str.isEmpty()) str += "; "; str += p.getDebugInfo(); } return str; } /** * This method returns true if one of the paths has an error or if the response itself is * erroneous. */ public boolean hasErrors() { if (!errors.isEmpty()) return true; for (ResponsePath p : responsePaths) { if (p.hasErrors()) return true; } return false; } /** * This method returns all the explicitly added errors and the errors of all paths. */ public List<Throwable> getErrors() {<FILL_FUNCTION_BODY>} public GHResponse addErrors(List<Throwable> errors) { this.errors.addAll(errors); return this; } public GHResponse addError(Throwable error) { this.errors.add(error); return this; } @Override public String toString() { String str = ""; for (ResponsePath a : responsePaths) { str += "; " + a.toString(); } if (responsePaths.isEmpty()) str = "no paths"; if (!errors.isEmpty()) str += ", main errors: " + errors.toString(); return str; } public void setHints(PMap hints) { this.hintsMap = hints; } public PMap getHints() { return hintsMap; } public String getHeader(String key, String defaultValue) { Object val = hintsMap.getObject(key.toLowerCase(Locale.ROOT), null); if (val instanceof List && !((List) val).isEmpty()) return ((List) val).get(0).toString(); return defaultValue; } }
List<Throwable> list = new ArrayList<>(); list.addAll(errors); for (ResponsePath p : responsePaths) { list.addAll(p.getErrors()); } return list;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/Trip.java
Trip
toString
class Trip { public static abstract class Leg { public final String type; public final String departureLocation; public final Geometry geometry; public final double distance; public Leg(String type, String departureLocation, Geometry geometry, double distance) { this.type = type; this.departureLocation = departureLocation; this.geometry = geometry; this.distance = distance; } public double getDistance() { return distance; } public abstract Date getDepartureTime(); public abstract Date getArrivalTime(); } public static class Stop { public final String stop_id; public final String stop_name; public final Point geometry; public final Date arrivalTime; public final Date plannedArrivalTime; public final Date predictedArrivalTime; public final boolean arrivalCancelled; public final Date departureTime; public final Date plannedDepartureTime; public final Date predictedDepartureTime; public final boolean departureCancelled; public Stop(String stop_id, String name, Point geometry, Date arrivalTime, Date plannedArrivalTime, Date predictedArrivalTime, boolean arrivalCancelled, Date departureTime, Date plannedDepartureTime, Date predictedDepartureTime, boolean departureCancelled) { this.stop_id = stop_id; this.stop_name = name; this.geometry = geometry; this.arrivalTime = arrivalTime; this.plannedArrivalTime = plannedArrivalTime; this.predictedArrivalTime = predictedArrivalTime; this.arrivalCancelled = arrivalCancelled; this.departureTime = departureTime; this.plannedDepartureTime = plannedDepartureTime; this.predictedDepartureTime = predictedDepartureTime; this.departureCancelled = departureCancelled; } @Override public String toString() {<FILL_FUNCTION_BODY>} } public static class WalkLeg extends Leg { public final InstructionList instructions; public final Map<String, List<PathDetail>> details; private final Date departureTime; private final Date arrivalTime; public WalkLeg(String departureLocation, Date departureTime, Geometry geometry, double distance, InstructionList instructions, Map<String, List<PathDetail>> details, Date arrivalTime) { super("walk", departureLocation, geometry, distance); this.instructions = instructions; this.departureTime = departureTime; this.details = details; this.arrivalTime = arrivalTime; } @Override public Date getDepartureTime() { return departureTime; } @Override public Date getArrivalTime() { return arrivalTime; } } public static class PtLeg extends Leg { public final String feed_id; public final boolean isInSameVehicleAsPrevious; public final String trip_headsign; public final long travelTime; public final List<Stop> stops; public final String trip_id; public final String route_id; public PtLeg(String feedId, boolean isInSameVehicleAsPrevious, String tripId, String routeId, String headsign, List<Stop> stops, double distance, long travelTime, Geometry geometry) { super("pt", stops.get(0).stop_name, geometry, distance); this.feed_id = feedId; this.isInSameVehicleAsPrevious = isInSameVehicleAsPrevious; this.trip_id = tripId; this.route_id = routeId; this.trip_headsign = headsign; this.travelTime = travelTime; this.stops = stops; } @Override public Date getDepartureTime() { return stops.get(0).departureTime; } @Override public Date getArrivalTime() { return stops.get(stops.size()-1).arrivalTime; } } }
return "Stop{" + "stop_id='" + stop_id + '\'' + ", arrivalTime=" + arrivalTime + ", departureTime=" + departureTime + '}';
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/CustomModelAreasDeserializer.java
CustomModelAreasDeserializer
deserialize
class CustomModelAreasDeserializer extends JsonDeserializer<JsonFeatureCollection> { @Override public JsonFeatureCollection deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
JsonNode treeNode = jp.readValueAsTree(); JsonFeatureCollection collection = new JsonFeatureCollection(); if (treeNode.has("type") && "FeatureCollection".equals(treeNode.get("type").asText())) { // Unfortunately the simpler code ala "jp.getCodec().treeToValue(treeNode, JsonFeatureCollection.class)" results in a StackErrorException for (JsonNode node : treeNode.get("features")) { JsonFeature feature = jp.getCodec().treeToValue(node, JsonFeature.class); if (Helper.isEmpty(feature.getId())) throw new IllegalArgumentException("The JsonFeature for the CustomModel area must contain \"id\""); collection.getFeatures().add(feature); } } else { Iterator<Map.Entry<String, JsonNode>> fields = treeNode.fields(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); JsonFeature feature = jp.getCodec().treeToValue(field.getValue(), JsonFeature.class); feature.setId(field.getKey()); collection.getFeatures().add(feature); } } // duplicate "id" check Map<String, JsonFeature> index = CustomModel.getAreasAsMap(collection); if (index.size() != collection.getFeatures().size()) // redundant but cannot hurt throw new IllegalArgumentException("JsonFeatureCollection contains duplicate area"); return collection;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/GHPointSerializer.java
GHPointSerializer
serialize
class GHPointSerializer extends JsonSerializer<GHPoint> { @Override public void serialize(GHPoint ghPoint, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {<FILL_FUNCTION_BODY>} }
jsonGenerator.writeStartArray(); for (Double number : ghPoint.toGeoJson()) { jsonGenerator.writeNumber(number); } jsonGenerator.writeEndArray();
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/InstructionListSerializer.java
InstructionListSerializer
serialize
class InstructionListSerializer extends JsonSerializer<InstructionList> { @Override public void serialize(InstructionList instructions, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {<FILL_FUNCTION_BODY>} }
List<Map<String, Object>> instrList = new ArrayList<>(instructions.size()); int pointsIndex = 0; for (Instruction instruction : instructions) { Map<String, Object> instrJson = new HashMap<>(); instrList.add(instrJson); instrJson.put("text", Helper.firstBig(instruction.getTurnDescription(instructions.getTr()))); instrJson.put(STREET_NAME, instruction.getName()); instrJson.put("time", instruction.getTime()); instrJson.put("distance", Helper.round(instruction.getDistance(), 3)); instrJson.put("sign", instruction.getSign()); instrJson.putAll(instruction.getExtraInfoJSON()); int tmpIndex = pointsIndex + instruction.getLength(); instrJson.put("interval", Arrays.asList(pointsIndex, tmpIndex)); pointsIndex = tmpIndex; } jsonGenerator.writeObject(instrList);
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/JtsEnvelopeDeserializer.java
JtsEnvelopeDeserializer
deserialize
class JtsEnvelopeDeserializer extends JsonDeserializer<Envelope> { @Override public Envelope deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {<FILL_FUNCTION_BODY>} }
double[] bounds = jsonParser.readValueAs(double[].class); return new Envelope(bounds[0], bounds[2], bounds[1], bounds[3]);
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/MultiExceptionSerializer.java
MultiExceptionSerializer
serialize
class MultiExceptionSerializer extends JsonSerializer<MultiException> { @Override public void serialize(MultiException e, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {<FILL_FUNCTION_BODY>} private static String getMessage(Throwable t) { if (t.getMessage() == null) return t.getClass().getSimpleName(); else return t.getMessage(); } }
List<Throwable> errors = e.getErrors(); ObjectNode json = JsonNodeFactory.instance.objectNode(); json.put("message", getMessage(errors.get(0))); ArrayNode errorHintList = json.putArray("hints"); for (Throwable t : errors) { ObjectNode error = errorHintList.addObject(); error.put("message", getMessage(t)); error.put("details", t.getClass().getName()); if (t instanceof GHException) { ((GHException) t).getDetails().forEach(error::putPOJO); } } jsonGenerator.writeObject(json);
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/PathDetailDeserializer.java
PathDetailDeserializer
deserialize
class PathDetailDeserializer extends JsonDeserializer<PathDetail> { @Override public PathDetail deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
JsonNode pathDetail = jp.readValueAsTree(); if (pathDetail.size() != 3) throw new JsonParseException(jp, "PathDetail array must have exactly 3 entries but was " + pathDetail.size()); JsonNode from = pathDetail.get(0); JsonNode to = pathDetail.get(1); JsonNode val = pathDetail.get(2); PathDetail pd; if (val.isBoolean()) pd = new PathDetail(val.asBoolean()); else if (val.isDouble()) pd = new PathDetail(val.asDouble()); else if (val.canConvertToLong()) pd = new PathDetail(val.asLong()); else if (val.isTextual()) pd = new PathDetail(val.asText()); else if (val.isObject()) pd = new PathDetail(jp.getCodec().treeToValue(val, Map.class)); else if (val.isNull()) pd = new PathDetail(null); else throw new JsonParseException(jp, "Unsupported type of PathDetail value " + pathDetail.getNodeType().name()); pd.setFirst(from.asInt()); pd.setLast(to.asInt()); return pd;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/PathDetailSerializer.java
PathDetailSerializer
serialize
class PathDetailSerializer extends JsonSerializer<PathDetail> { @Override public void serialize(PathDetail value, JsonGenerator gen, SerializerProvider serializers) throws IOException {<FILL_FUNCTION_BODY>} }
gen.writeStartArray(); gen.writeNumber(value.getFirst()); gen.writeNumber(value.getLast()); if (value.getValue() instanceof Double) gen.writeNumber((Double) value.getValue()); else if (value.getValue() instanceof Long) gen.writeNumber((Long) value.getValue()); else if (value.getValue() instanceof Integer) gen.writeNumber((Integer) value.getValue()); else if (value.getValue() instanceof Boolean) gen.writeBoolean((Boolean) value.getValue()); else if (value.getValue() instanceof String) gen.writeString((String) value.getValue()); else if (value.getValue() instanceof Map) gen.writeObject(value.getValue()); else if (value.getValue() == null) gen.writeNull(); else throw new JsonGenerationException("Unsupported type for PathDetail.value" + value.getValue().getClass(), gen); gen.writeEndArray();
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/ResponsePathSerializer.java
ResponsePathSerializer
jsonObject
class ResponsePathSerializer { public static String encodePolyline(PointList poly, boolean includeElevation, double multiplier) { if (multiplier < 1) throw new IllegalArgumentException("multiplier cannot be smaller than 1 but was " + multiplier + " for polyline"); StringBuilder sb = new StringBuilder(Math.max(20, poly.size() * 3)); int size = poly.size(); int prevLat = 0; int prevLon = 0; int prevEle = 0; for (int i = 0; i < size; i++) { int num = (int) Math.round(poly.getLat(i) * multiplier); encodeNumber(sb, num - prevLat); prevLat = num; num = (int) Math.round(poly.getLon(i) * multiplier); encodeNumber(sb, num - prevLon); prevLon = num; if (includeElevation) { num = (int) Math.round(poly.getEle(i) * 100); encodeNumber(sb, num - prevEle); prevEle = num; } } return sb.toString(); } private static void encodeNumber(StringBuilder sb, int num) { num = num << 1; if (num < 0) { num = ~num; } while (num >= 0x20) { int nextValue = (0x20 | (num & 0x1f)) + 63; sb.append((char) (nextValue)); num >>= 5; } num += 63; sb.append((char) (num)); } public record Info(List<String> copyrights, long took, String roadDataTimeStamp) { } public static ObjectNode jsonObject(GHResponse ghRsp, Info info, boolean enableInstructions, boolean calcPoints, boolean enableElevation, boolean pointsEncoded, double pointsMultiplier) {<FILL_FUNCTION_BODY>} }
ObjectNode json = JsonNodeFactory.instance.objectNode(); json.putPOJO("hints", ghRsp.getHints().toMap()); json.putPOJO("info", info); ArrayNode jsonPathList = json.putArray("paths"); for (ResponsePath p : ghRsp.getAll()) { ObjectNode jsonPath = jsonPathList.addObject(); jsonPath.put("distance", Helper.round(p.getDistance(), 3)); jsonPath.put("weight", Helper.round6(p.getRouteWeight())); jsonPath.put("time", p.getTime()); jsonPath.put("transfers", p.getNumChanges()); if (!p.getDescription().isEmpty()) { jsonPath.putPOJO("description", p.getDescription()); } // for points and snapped_waypoints: jsonPath.put("points_encoded", pointsEncoded); if (pointsEncoded) jsonPath.put("points_encoded_multiplier", pointsMultiplier); if (calcPoints) { jsonPath.putPOJO("bbox", p.calcBBox2D()); jsonPath.putPOJO("points", pointsEncoded ? encodePolyline(p.getPoints(), enableElevation, pointsMultiplier) : p.getPoints().toLineString(enableElevation)); if (enableInstructions) { jsonPath.putPOJO("instructions", p.getInstructions()); } jsonPath.putPOJO("legs", p.getLegs()); jsonPath.putPOJO("details", p.getPathDetails()); jsonPath.put("ascend", p.getAscend()); jsonPath.put("descend", p.getDescend()); } jsonPath.putPOJO("snapped_waypoints", pointsEncoded ? encodePolyline(p.getWaypoints(), enableElevation, pointsMultiplier) : p.getWaypoints().toLineString(enableElevation)); if (p.getFare() != null) { jsonPath.put("fare", NumberFormat.getCurrencyInstance(Locale.ROOT).format(p.getFare())); } } return json;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/jackson/StatementDeserializer.java
StatementDeserializer
deserialize
class StatementDeserializer extends JsonDeserializer<Statement> { @Override public Statement deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {<FILL_FUNCTION_BODY>} }
JsonNode treeNode = p.readValueAsTree(); Statement.Op jsonOp = null; String value = null; if (treeNode.size() != 2) throw new IllegalArgumentException("Statement expects two entries but was " + treeNode.size() + " for " + treeNode); for (Statement.Op op : Statement.Op.values()) { if (treeNode.has(op.getName())) { if (jsonOp != null) throw new IllegalArgumentException("Multiple operations are not allowed. Statement: " + treeNode); jsonOp = op; value = treeNode.get(op.getName()).asText(); } } if (jsonOp == null) throw new IllegalArgumentException("Cannot find an operation in " + treeNode + ". Must be one of: " + Arrays.stream(Statement.Op.values()).map(Statement.Op::getName).collect(Collectors.joining(","))); if (value == null) throw new IllegalArgumentException("Cannot find a value in " + treeNode); if (treeNode.has(IF.getName())) return Statement.If(treeNode.get(IF.getName()).asText(), jsonOp, value); else if (treeNode.has(ELSEIF.getName())) return Statement.ElseIf(treeNode.get(ELSEIF.getName()).asText(), jsonOp, value); else if (treeNode.has(ELSE.getName())) { JsonNode elseNode = treeNode.get(ELSE.getName()); if (elseNode.isNull() || elseNode.isValueNode() && elseNode.asText().isEmpty()) return Statement.Else(jsonOp, value); throw new IllegalArgumentException("else cannot have expression but was " + treeNode.get(ELSE.getName())); } throw new IllegalArgumentException("Cannot find if, else_if or else for " + treeNode);
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/json/Statement.java
Statement
toString
class Statement { private final Keyword keyword; private final String condition; private final Op operation; private final String value; private Statement(Keyword keyword, String condition, Op operation, String value) { this.keyword = keyword; this.condition = condition; this.value = value; this.operation = operation; } public Keyword getKeyword() { return keyword; } public String getCondition() { return condition; } public Op getOperation() { return operation; } public String getValue() { return value; } public enum Keyword { IF("if"), ELSEIF("else_if"), ELSE("else"); String name; Keyword(String name) { this.name = name; } public String getName() { return name; } } public enum Op { MULTIPLY("multiply_by"), LIMIT("limit_to"); String name; Op(String name) { this.name = name; } public String getName() { return name; } public String build(String value) { switch (this) { case MULTIPLY: return "value *= " + value; case LIMIT: return "value = Math.min(value," + value + ")"; default: throw new IllegalArgumentException(); } } public MinMax apply(MinMax minMax1, MinMax minMax2) { switch (this) { case MULTIPLY: return new MinMax(minMax1.min * minMax2.min, minMax1.max * minMax2.max); case LIMIT: return new MinMax(Math.min(minMax1.min, minMax2.min), Math.min(minMax1.max, minMax2.max)); default: throw new IllegalArgumentException(); } } } @Override public String toString() {<FILL_FUNCTION_BODY>} private String str(String str) { return "\"" + str + "\""; } public static Statement If(String expression, Op op, String value) { return new Statement(Keyword.IF, expression, op, value); } public static Statement ElseIf(String expression, Op op, String value) { return new Statement(Keyword.ELSEIF, expression, op, value); } public static Statement Else(Op op, String value) { return new Statement(Keyword.ELSE, null, op, value); } }
return "{" + str(keyword.getName()) + ": " + str(condition) + ", " + str(operation.getName()) + ": " + value + "}";
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/CustomModel.java
CustomModel
addAreas
class CustomModel { public static final String KEY = "custom_model"; // 'Double' instead of 'double' is required to know if it was 0 or not specified in the request. private Double distanceInfluence; private Double headingPenalty; private boolean internal; private List<Statement> speedStatements = new ArrayList<>(); private List<Statement> priorityStatements = new ArrayList<>(); private JsonFeatureCollection areas = new JsonFeatureCollection(); public CustomModel() { } public CustomModel(CustomModel toCopy) { this.headingPenalty = toCopy.headingPenalty; this.distanceInfluence = toCopy.distanceInfluence; // do not copy "internal" boolean speedStatements = deepCopy(toCopy.getSpeed()); priorityStatements = deepCopy(toCopy.getPriority()); addAreas(toCopy.getAreas()); } public static Map<String, JsonFeature> getAreasAsMap(JsonFeatureCollection areas) { Map<String, JsonFeature> map = new HashMap<>(areas.getFeatures().size()); areas.getFeatures().forEach(f -> { if (map.put(f.getId(), f) != null) throw new IllegalArgumentException("Cannot handle duplicate area " + f.getId()); }); return map; } public void addAreas(JsonFeatureCollection externalAreas) {<FILL_FUNCTION_BODY>} /** * This method is for internal usage only! Parsing a CustomModel is expensive and so we cache the result, which is * especially important for fast landmark queries (hybrid mode). Now this method ensures that all server-side custom * models are cached in a special internal cache which does not remove seldom accessed entries. */ public CustomModel internal() { this.internal = true; return this; } public boolean isInternal() { return internal; } private <T> T deepCopy(T originalObject) { if (originalObject instanceof List) { List<Object> newList = new ArrayList<>(((List) originalObject).size()); for (Object item : (List) originalObject) { newList.add(deepCopy(item)); } return (T) newList; } else if (originalObject instanceof Map) { Map copy = originalObject instanceof LinkedHashMap ? new LinkedHashMap<>(((Map) originalObject).size()) : new HashMap<>(((Map) originalObject).size()); for (Object o : ((Map) originalObject).entrySet()) { Map.Entry entry = (Map.Entry) o; copy.put(entry.getKey(), deepCopy(entry.getValue())); } return (T) copy; } else { return originalObject; } } public List<Statement> getSpeed() { return speedStatements; } public CustomModel addToSpeed(Statement st) { getSpeed().add(st); return this; } public List<Statement> getPriority() { return priorityStatements; } public CustomModel addToPriority(Statement st) { getPriority().add(st); return this; } @JsonDeserialize(using = CustomModelAreasDeserializer.class) public CustomModel setAreas(JsonFeatureCollection areas) { this.areas = areas; return this; } public JsonFeatureCollection getAreas() { return areas; } public CustomModel setDistanceInfluence(Double distanceFactor) { this.distanceInfluence = distanceFactor; return this; } public Double getDistanceInfluence() { return distanceInfluence; } public CustomModel setHeadingPenalty(double headingPenalty) { this.headingPenalty = headingPenalty; return this; } public Double getHeadingPenalty() { return headingPenalty; } @Override public String toString() { return createContentString(); } private String createContentString() { // used to check against stored custom models, see #2026 return "distanceInfluence=" + distanceInfluence + "|headingPenalty=" + headingPenalty + "|speedStatements=" + speedStatements + "|priorityStatements=" + priorityStatements + "|areas=" + areas; } /** * A new CustomModel is created from the baseModel merged with the specified queryModel. Returns the baseModel if * queryModel is null. */ public static CustomModel merge(CustomModel baseModel, CustomModel queryModel) { // avoid changing the specified CustomModel via deep copy otherwise the server-side CustomModel would be // modified (same problem if queryModel would be used as target) CustomModel mergedCM = new CustomModel(baseModel); if (queryModel == null) return mergedCM; if (queryModel.getDistanceInfluence() != null) mergedCM.distanceInfluence = queryModel.distanceInfluence; if (queryModel.getHeadingPenalty() != null) mergedCM.headingPenalty = queryModel.headingPenalty; mergedCM.speedStatements.addAll(queryModel.getSpeed()); mergedCM.priorityStatements.addAll(queryModel.getPriority()); mergedCM.addAreas(queryModel.getAreas()); return mergedCM; } }
Set<String> indexed = areas.getFeatures().stream().map(JsonFeature::getId).collect(Collectors.toSet()); for (JsonFeature ext : externalAreas.getFeatures()) { if (!JsonFeature.isValidId("in_" + ext.getId())) throw new IllegalArgumentException("The area '" + ext.getId() + "' has an invalid id. Only letters, numbers and underscore are allowed."); if (indexed.contains(ext.getId())) throw new IllegalArgumentException("area " + ext.getId() + " already exists"); areas.getFeatures().add(ext); indexed.add(ext.getId()); }
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/JsonFeature.java
JsonFeature
isValidId
class JsonFeature { private String id; private String type = "Feature"; private Envelope bbox; private Geometry geometry; private Map<String, Object> properties; public JsonFeature() { } public JsonFeature(String id, String type, Envelope bbox, Geometry geometry, Map<String, Object> properties) { this.id = id; this.type = type; this.bbox = bbox; this.geometry = geometry; this.properties = properties; } public String getId() { return id; } public String getType() { return type; } public Envelope getBBox() { return bbox; } public Geometry getGeometry() { return geometry; } public Map<String, Object> getProperties() { return properties; } public Object getProperty(String key) { return properties.get(key); } public void setId(String id) { this.id = id; } public void setBBox(Envelope bbox) { this.bbox = bbox; } public void setGeometry(Geometry geometry) { this.geometry = geometry; } public void setProperties(Map<String, Object> properties) { this.properties = properties; } @Override public String toString() { return "id:" + getId(); } public static boolean isValidId(String name) {<FILL_FUNCTION_BODY>} }
if (name.length() <= 3 || !name.startsWith("in_") || SourceVersion.isKeyword(name)) return false; int underscoreCount = 0; for (int i = 1; i < name.length(); i++) { char c = name.charAt(i); if (c == '_') { if (underscoreCount > 0) return false; underscoreCount++; } else if (!isLetter(c) && !isDigit(c)) { return false; } else { underscoreCount = 0; } } return true;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/PMap.java
PMap
read
class PMap { private final LinkedHashMap<String, Object> map; public PMap() { this(5); } public PMap(int capacity) { this.map = new LinkedHashMap<>(capacity); } public PMap(Map<String, Object> map) { this.map = new LinkedHashMap<>(map); } public PMap(PMap map) { this.map = new LinkedHashMap<>(map.map); } public PMap(String propertiesString) { this.map = new LinkedHashMap<>(); for (String s : propertiesString.split("\\|")) { s = s.trim(); int index = s.indexOf("="); if (index < 0) continue; putObject(Helper.camelCaseToUnderScore(s.substring(0, index)), Helper.toObject(s.substring(index + 1))); } } /** * Reads a PMap from a string array consisting of key=value pairs */ public static PMap read(String[] args) {<FILL_FUNCTION_BODY>} public PMap putAll(PMap map) { this.map.putAll(map.map); return this; } public Object remove(String key) { return map.remove(key); } public boolean has(String key) { return map.containsKey(key); } public boolean getBool(String key, boolean _default) { Object object = map.get(key); return object instanceof Boolean ? (Boolean) object : _default; } public int getInt(String key, int _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).intValue() : _default; } public long getLong(String key, long _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).longValue() : _default; } public float getFloat(String key, float _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).floatValue() : _default; } public double getDouble(String key, double _default) { Object object = map.get(key); return object instanceof Number ? ((Number) object).doubleValue() : _default; } public String getString(String key, String _default) { Object object = map.get(key); return object instanceof String ? (String) object : _default; } public <T> T getObject(String key, T _default) { Object object = map.get(key); return object == null ? _default : (T) object; } public PMap putObject(String key, Object object) { map.put(key, object); return this; } /** * This method copies the underlying structure into a new Map object */ public Map<String, Object> toMap() { return new LinkedHashMap<>(map); } public boolean isEmpty() { return map.isEmpty(); } @Override public String toString() { return map.toString(); } }
PMap map = new PMap(); for (String arg : args) { int index = arg.indexOf("="); if (index <= 0) { continue; } String key = arg.substring(0, index); if (key.startsWith("-")) { key = key.substring(1); } if (key.startsWith("-")) { key = key.substring(1); } String value = arg.substring(index + 1); Object old = map.map.put(Helper.camelCaseToUnderScore(key), Helper.toObject(value)); if (old != null) throw new IllegalArgumentException("Pair '" + Helper.camelCaseToUnderScore(key) + "'='" + value + "' not possible to " + "add to the PMap-object as the key already exists with '" + old + "'"); } return map;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/RoundaboutInstruction.java
RoundaboutInstruction
getExitNumber
class RoundaboutInstruction extends Instruction { private int exitNumber = 0; // 0 undetermined, 1 clockwise, -1 counterclockwise, 2 inconsistent private int clockwise = 0; private boolean exited = false; private double radian = Double.NaN; public RoundaboutInstruction(int sign, String name, PointList pl) { super(sign, name, pl); } public RoundaboutInstruction increaseExitNumber() { this.exitNumber += 1; return this; } public RoundaboutInstruction setDirOfRotation(double deltaIn) { if (clockwise == 0) { clockwise = deltaIn > 0 ? 1 : -1; } else { int clockwise2 = deltaIn > 0 ? 1 : -1; if (clockwise != clockwise2) { clockwise = 2; } } return this; } public RoundaboutInstruction setExited() { exited = true; return this; } public boolean isExited() { return exited; } public int getExitNumber() {<FILL_FUNCTION_BODY>} public RoundaboutInstruction setExitNumber(int exitNumber) { this.exitNumber = exitNumber; return this; } /** * @return radian of angle -2PI &lt; x &lt; 2PI between roundabout entrance and exit values * <ul> * <li>&gt; 0 is for clockwise rotation</li> * <li>&lt; 0 is for counterclockwise rotation</li> * <li>NaN if direction of rotation is unclear</li> * </ul> */ public double getTurnAngle() { if (Math.abs(clockwise) != 1) return Double.NaN; else return Math.PI * clockwise - radian; } /** * The radian value between entrance (in) and exit (out) of this roundabout. */ public RoundaboutInstruction setRadian(double radian) { this.radian = radian; return this; } @Override public Map<String, Object> getExtraInfoJSON() { Map<String, Object> tmpMap = new HashMap<>(3); tmpMap.put("exit_number", getExitNumber()); tmpMap.put("exited", this.exited); double tmpAngle = getTurnAngle(); if (!Double.isNaN(tmpAngle)) tmpMap.put("turn_angle", Helper.round(tmpAngle, 2)); return tmpMap; } @Override public String getTurnDescription(Translation tr) { if (rawName) return getName(); String str; String streetName = _getName(); int indi = getSign(); if (indi == Instruction.USE_ROUNDABOUT) { if (!exited) { str = tr.tr("roundabout_enter"); } else { str = Helper.isEmpty(streetName) ? tr.tr("roundabout_exit", getExitNumber()) : tr.tr("roundabout_exit_onto", getExitNumber(), streetName); } } else { throw new IllegalStateException(indi + "no roundabout indication"); } return str; } }
if (exited && exitNumber == 0) { throw new IllegalStateException("RoundaboutInstruction must contain exitNumber>0"); } return exitNumber;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/ViaInstruction.java
ViaInstruction
getViaCount
class ViaInstruction extends Instruction { private int viaPosition = -1; public ViaInstruction(String name, PointList pl) { super(REACHED_VIA, name, pl); } public ViaInstruction(Instruction instr) { this(instr.getName(), instr.getPoints()); setDistance(instr.getDistance()); setTime(instr.getTime()); this.extraInfo = instr.extraInfo; } @Override public int getLength() { return 0; } public int getViaCount() {<FILL_FUNCTION_BODY>} public void setViaCount(int count) { this.viaPosition = count; } @Override public String getTurnDescription(Translation tr) { if (rawName) return getName(); return tr.tr("stopover", getViaCount()); } }
if (viaPosition < 0) throw new IllegalStateException("Uninitialized via count in instruction " + getName()); return viaPosition;
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/details/PathDetail.java
PathDetail
toString
class PathDetail { private final Object value; private int first; private int last; public PathDetail(Object value) { this.value = value; } /** * @return the value of this PathDetail. Can be null */ public Object getValue() { return value; } public void setFirst(int first) { this.first = first; } public int getFirst() { return first; } public void setLast(int last) { this.last = last; } public int getLast() { return last; } public int getLength() { return last - first; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return value + " [" + getFirst() + ", " + getLast() + "]";
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/shapes/GHPoint.java
GHPoint
fromString
class GHPoint { public double lat = Double.NaN; public double lon = Double.NaN; public GHPoint() { } public GHPoint(double lat, double lon) { this.lat = lat; this.lon = lon; } public static GHPoint create(Point point) { return new GHPoint(point.getY(), point.getX()); } public static GHPoint fromString(String str) { return fromString(str, false); } public static GHPoint fromStringLonLat(String str) { return fromString(str, true); } public static GHPoint fromJson(double[] xy) { return new GHPoint(xy[1], xy[0]); } private static GHPoint fromString(String str, boolean lonLatOrder) {<FILL_FUNCTION_BODY>} public double getLon() { return lon; } public double getLat() { return lat; } public boolean isValid() { return !Double.isNaN(lat) && !Double.isNaN(lon); } @Override public int hashCode() { int hash = 7; hash = 83 * hash + (int) (Double.doubleToLongBits(this.lat) ^ (Double.doubleToLongBits(this.lat) >>> 32)); hash = 83 * hash + (int) (Double.doubleToLongBits(this.lon) ^ (Double.doubleToLongBits(this.lon) >>> 32)); return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; @SuppressWarnings("unchecked") final GHPoint other = (GHPoint) obj; return NumHelper.equalsEps(lat, other.lat) && NumHelper.equalsEps(lon, other.lon); } @Override public String toString() { return lat + "," + lon; } public String toShortString() { return String.format(Locale.ROOT, "%.8f,%.8f", lat, lon); } /** * Attention: geoJson is LON,LAT */ public Double[] toGeoJson() { return new Double[]{lon, lat}; } }
String[] fromStrs = str.split(","); if (fromStrs.length != 2) throw new IllegalArgumentException("Cannot parse point '" + str + "'"); try { double fromLat = Double.parseDouble(fromStrs[0]); double fromLon = Double.parseDouble(fromStrs[1]); if (lonLatOrder) { return new GHPoint(fromLon, fromLat); } else { return new GHPoint(fromLat, fromLon); } } catch (NumberFormatException ex) { throw new IllegalArgumentException("Cannot parse point '" + str + "'"); }
graphhopper_graphhopper
graphhopper/web-api/src/main/java/com/graphhopper/util/shapes/GHPoint3D.java
GHPoint3D
equals
class GHPoint3D extends GHPoint { public double ele; public GHPoint3D(double lat, double lon, double elevation) { super(lat, lon); this.ele = elevation; } public double getEle() { return ele; } @Override public int hashCode() { int hash = 59 * super.hashCode() + (int) (Double.doubleToLongBits(this.ele) ^ (Double.doubleToLongBits(this.ele) >>> 32)); return hash; } @Override public boolean equals(Object obj) {<FILL_FUNCTION_BODY>} @Override public String toString() { return super.toString() + "," + ele; } @Override public Double[] toGeoJson() { return new Double[]{lon, lat, ele}; } }
if (obj == null) return false; @SuppressWarnings("unchecked") final GHPoint3D other = (GHPoint3D) obj; if (Double.isNaN(ele)) // very special case necessary in QueryGraph, asserted via test return NumHelper.equalsEps(lat, other.lat) && NumHelper.equalsEps(lon, other.lon); else return NumHelper.equalsEps(lat, other.lat) && NumHelper.equalsEps(lon, other.lon) && NumHelper.equalsEps(ele, other.ele);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/CORSFilter.java
CORSFilter
doFilter
class CORSFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {<FILL_FUNCTION_BODY>} @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }
HttpServletResponse rsp = (HttpServletResponse) response; rsp.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTIONS"); rsp.setHeader("Access-Control-Allow-Headers", "Origin,Accept,X-Requested-With," + "Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Range,GH-Client"); rsp.setHeader("Access-Control-Allow-Origin", "*"); chain.doFilter(request, response);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GHJerseyViolationExceptionMapper.java
GHJerseyViolationExceptionMapper
toResponse
class GHJerseyViolationExceptionMapper implements ExceptionMapper<JerseyViolationException> { private static final Logger logger = LoggerFactory.getLogger(GHJerseyViolationExceptionMapper.class); @Override public Response toResponse(final JerseyViolationException exception) {<FILL_FUNCTION_BODY>} }
logger.debug("jersey violation exception: " + (Helper.isEmpty(exception.getMessage()) ? "unknown reason" : exception.getMessage())); final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); final Invocable invocable = exception.getInvocable(); final List<String> errors = exception.getConstraintViolations().stream() .map(violation -> ConstraintMessage.getMessage(violation, invocable)) .collect(Collectors.toList()); final int status = ConstraintMessage.determineStatus(violations, invocable); return Response.status(status) .type(MediaType.APPLICATION_JSON) .entity(new JsonErrorEntity(errors)) .build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperBundle.java
GraphHopperBundle
run
class GraphHopperBundle implements ConfiguredBundle<GraphHopperBundleConfiguration> { static class TranslationMapFactory implements Factory<TranslationMap> { @Inject GraphHopper graphHopper; @Override public TranslationMap provide() { return graphHopper.getTranslationMap(); } @Override public void dispose(TranslationMap instance) { } } static class BaseGraphFactory implements Factory<BaseGraph> { @Inject GraphHopper graphHopper; @Override public BaseGraph provide() { return graphHopper.getBaseGraph(); } @Override public void dispose(BaseGraph instance) { } } static class GtfsStorageFactory implements Factory<GtfsStorage> { @Inject GraphHopperGtfs graphHopper; @Override public GtfsStorage provide() { return graphHopper.getGtfsStorage(); } @Override public void dispose(GtfsStorage instance) { } } static class EncodingManagerFactory implements Factory<EncodingManager> { @Inject GraphHopper graphHopper; @Override public EncodingManager provide() { return graphHopper.getEncodingManager(); } @Override public void dispose(EncodingManager instance) { } } static class LocationIndexFactory implements Factory<LocationIndex> { @Inject GraphHopper graphHopper; @Override public LocationIndex provide() { return graphHopper.getLocationIndex(); } @Override public void dispose(LocationIndex instance) { } } static class ProfileResolverFactory implements Factory<ProfileResolver> { @Inject GraphHopper graphHopper; @Override public ProfileResolver provide() { return new ProfileResolver(graphHopper.getProfiles()); } @Override public void dispose(ProfileResolver instance) { } } static class GHRequestTransformerFactory implements Factory<GHRequestTransformer> { @Override public GHRequestTransformer provide() { return req -> req; } @Override public void dispose(GHRequestTransformer instance) { } } static class PathDetailsBuilderFactoryFactory implements Factory<PathDetailsBuilderFactory> { @Inject GraphHopper graphHopper; @Override public PathDetailsBuilderFactory provide() { return graphHopper.getPathDetailsBuilderFactory(); } @Override public void dispose(PathDetailsBuilderFactory profileResolver) { } } static class MapMatchingRouterFactoryFactory implements Factory<MapMatchingResource.MapMatchingRouterFactory> { @Inject GraphHopper graphHopper; @Override public MapMatchingResource.MapMatchingRouterFactory provide() { return new MapMatchingResource.MapMatchingRouterFactory() { @Override public MapMatching.Router createMapMatchingRouter(PMap hints) { return MapMatching.routerFromGraphHopper(graphHopper, hints); } }; } @Override public void dispose(MapMatchingResource.MapMatchingRouterFactory mapMatchingRouterFactory) { } } static class HasElevation implements Factory<Boolean> { @Inject GraphHopper graphHopper; @Override public Boolean provide() { return graphHopper.hasElevation(); } @Override public void dispose(Boolean instance) { } } @Override public void initialize(Bootstrap<?> bootstrap) { // See #1440: avoids warning regarding com.fasterxml.jackson.module.afterburner.util.MyClassLoader bootstrap.setObjectMapper(io.dropwizard.jackson.Jackson.newMinimalObjectMapper()); // avoids warning regarding com.fasterxml.jackson.databind.util.ClassUtil bootstrap.getObjectMapper().registerModule(new Jdk8Module()); Jackson.initObjectMapper(bootstrap.getObjectMapper()); bootstrap.getObjectMapper().setDateFormat(new StdDateFormat()); // See https://github.com/dropwizard/dropwizard/issues/1558 bootstrap.getObjectMapper().enable(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING); } @Override public void run(GraphHopperBundleConfiguration configuration, Environment environment) {<FILL_FUNCTION_BODY>} }
for (Object k : System.getProperties().keySet()) { if (k instanceof String && ((String) k).startsWith("graphhopper.")) throw new IllegalArgumentException("You need to prefix system parameters with '-Ddw.graphhopper.' instead of '-Dgraphhopper.' see #1879 and #1897"); } // When Dropwizard's Hibernate Validation misvalidates a query parameter, // a JerseyViolationException is thrown. // With this mapper, we use our custom format for that (backwards compatibility), // and also coerce the media type of the response to JSON, so we can return JSON error // messages from methods that normally have a different return type. // That's questionable, but on the other hand, Dropwizard itself does the same thing, // not here, but in a different place (the custom parameter parsers). // So for the moment we have to assume that both mechanisms // a) always return JSON error messages, and // b) there's no need to annotate the method with media type JSON for that. // // However, for places that throw IllegalArgumentException or MultiException, // we DO need to use the media type JSON annotation, because // those are agnostic to the media type (could be GPX!), so the server needs to know // that a JSON error response is supported. (See below.) environment.jersey().register(new GHJerseyViolationExceptionMapper()); // If the "?type=gpx" parameter is present, sets a corresponding media type header environment.jersey().register(new TypeGPXFilter()); // Together, these two take care that MultiExceptions thrown from RouteResource // come out as JSON or GPX, depending on the media type environment.jersey().register(new MultiExceptionMapper()); environment.jersey().register(new MultiExceptionGPXMessageBodyWriter()); // This makes an IllegalArgumentException come out as a MultiException with // a single entry. environment.jersey().register(new IllegalArgumentExceptionMapper()); final GraphHopperManaged graphHopperManaged = new GraphHopperManaged(configuration.getGraphHopperConfiguration()); environment.lifecycle().manage(graphHopperManaged); final GraphHopper graphHopper = graphHopperManaged.getGraphHopper(); environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(configuration.getGraphHopperConfiguration()).to(GraphHopperConfig.class); bind(graphHopper).to(GraphHopper.class); bind(new JTSTriangulator(graphHopper.getRouterConfig())).to(Triangulator.class); bindFactory(MapMatchingRouterFactoryFactory.class).to(MapMatchingResource.MapMatchingRouterFactory.class); bindFactory(PathDetailsBuilderFactoryFactory.class).to(PathDetailsBuilderFactory.class); bindFactory(ProfileResolverFactory.class).to(ProfileResolver.class); bindFactory(GHRequestTransformerFactory.class).to(GHRequestTransformer.class); bindFactory(HasElevation.class).to(Boolean.class).named("hasElevation"); bindFactory(LocationIndexFactory.class).to(LocationIndex.class); bindFactory(TranslationMapFactory.class).to(TranslationMap.class); bindFactory(EncodingManagerFactory.class).to(EncodingManager.class); bindFactory(BaseGraphFactory.class).to(BaseGraph.class); bindFactory(GtfsStorageFactory.class).to(GtfsStorage.class); } }); environment.jersey().register(MVTResource.class); environment.jersey().register(NearestResource.class); environment.jersey().register(RouteResource.class); environment.jersey().register(IsochroneResource.class); environment.jersey().register(MapMatchingResource.class); if (configuration.getGraphHopperConfiguration().has("gtfs.file")) { // These are pt-specific implementations of /route and /isochrone, but the same API. // We serve them under different paths (/route-pt and /isochrone-pt), and forward // requests for ?vehicle=pt there. environment.jersey().register(new AbstractBinder() { @Override protected void configure() { if (configuration.getGraphHopperConfiguration().getBool("gtfs.free_walk", false)) { bind(PtRouterFreeWalkImpl.class).to(PtRouter.class); } else { bind(PtRouterImpl.class).to(PtRouter.class); } } }); environment.jersey().register(PtRouteResource.class); environment.jersey().register(PtIsochroneResource.class); environment.jersey().register(PtMVTResource.class); environment.jersey().register(PtRedirectFilter.class); } environment.jersey().register(SPTResource.class); environment.jersey().register(I18NResource.class); environment.jersey().register(InfoResource.class); environment.healthChecks().register("graphhopper", new GraphHopperHealthCheck(graphHopper)); environment.jersey().register(environment.healthChecks()); environment.jersey().register(HealthCheckResource.class);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/GraphHopperManaged.java
GraphHopperManaged
start
class GraphHopperManaged implements Managed { private final static Logger logger = LoggerFactory.getLogger(GraphHopperManaged.class); private final GraphHopper graphHopper; public GraphHopperManaged(GraphHopperConfig configuration) { if (configuration.has("gtfs.file")) { graphHopper = new GraphHopperGtfs(configuration); } else { graphHopper = new GraphHopper(); } graphHopper.init(configuration); } @Override public void start() {<FILL_FUNCTION_BODY>} public GraphHopper getGraphHopper() { return graphHopper; } @Override public void stop() { graphHopper.close(); } }
graphHopper.importOrLoad(); logger.info("loaded graph at:{}, data_reader_file:{}, encoded values:{}, {} ints for edge flags, {}", graphHopper.getGraphHopperLocation(), graphHopper.getOSMFile(), graphHopper.getEncodingManager().toEncodedValuesAsString(), graphHopper.getEncodingManager().getIntsForFlags(), graphHopper.getBaseGraph().toDetailsString());
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/IllegalArgumentExceptionMapper.java
IllegalArgumentExceptionMapper
toResponse
class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> { private static final Logger logger = LoggerFactory.getLogger(IllegalArgumentExceptionMapper.class); @Override public Response toResponse(IllegalArgumentException e) {<FILL_FUNCTION_BODY>} }
logger.info("bad request: " + (Helper.isEmpty(e.getMessage()) ? "unknown reason" : e.getMessage()), e); return Response.status(Response.Status.BAD_REQUEST) .entity(new MultiException(e)) .build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/JsonErrorEntity.java
JsonErrorEntity
jsonErrorResponse
class JsonErrorEntity { private final List<String> errors; public JsonErrorEntity(List<String> t) { this.errors = t; } @JsonValue ObjectNode jsonErrorResponse() {<FILL_FUNCTION_BODY>} }
ObjectNode json = JsonNodeFactory.instance.objectNode(); json.put("message", errors.get(0)); ArrayNode errorHintList = json.putArray("hints"); for (String t : errors) { ObjectNode error = errorHintList.addObject(); error.put("message", t); } return json;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/MultiExceptionGPXMessageBodyWriter.java
MultiExceptionGPXMessageBodyWriter
writeTo
class MultiExceptionGPXMessageBodyWriter implements MessageBodyWriter<MultiException> { @Override public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return true; } @Override public long getSize(MultiException e, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return -1; } @Override public void writeTo(MultiException e, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {<FILL_FUNCTION_BODY>} }
if (e.getErrors().isEmpty()) throw new RuntimeException("errorsToXML should not be called with an empty list"); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element gpxElement = doc.createElement("gpx"); gpxElement.setAttribute("creator", "GraphHopper"); gpxElement.setAttribute("version", "1.1"); doc.appendChild(gpxElement); Element mdElement = doc.createElement("metadata"); gpxElement.appendChild(mdElement); Element extensionsElement = doc.createElement("extensions"); mdElement.appendChild(extensionsElement); Element messageElement = doc.createElement("message"); extensionsElement.appendChild(messageElement); messageElement.setTextContent(e.getErrors().iterator().next().getMessage()); Element hintsElement = doc.createElement("hints"); extensionsElement.appendChild(hintsElement); for (Throwable t : e.getErrors()) { Element error = doc.createElement("error"); hintsElement.appendChild(error); error.setAttribute("message", t.getMessage()); error.setAttribute("details", t.getClass().getName()); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(entityStream)); } catch (ParserConfigurationException | TransformerException e2) { throw new RuntimeException(e2); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/MultiExceptionMapper.java
MultiExceptionMapper
toResponse
class MultiExceptionMapper implements ExceptionMapper<MultiException> { private static final Logger logger = LoggerFactory.getLogger(MultiExceptionMapper.class); @Override public Response toResponse(MultiException e) {<FILL_FUNCTION_BODY>} }
logger.info("bad request: " + (Helper.isEmpty(e.getMessage()) ? (e.getErrors().isEmpty() ? "unknown reason" : e.getErrors().toString()) : e.getErrors())); return Response.status(Response.Status.BAD_REQUEST) .entity(e) .build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/ProfileResolver.java
ProfileResolver
errorIfLegacyParameters
class ProfileResolver { protected final Map<String, Profile> profilesByName; public ProfileResolver(List<Profile> profiles) { profilesByName = new LinkedHashMap<>(profiles.size()); profiles.forEach(p -> { if (profilesByName.put(p.getName(), p) != null) throw new IllegalArgumentException("Profiles must have distinct names"); }); } public String resolveProfile(PMap hints) { String profileName = hints.getString("profile", ""); if (profileName.isEmpty()) throw new IllegalArgumentException("profile parameter required"); errorIfLegacyParameters(hints); String profile = doResolveProfile(profileName, hints); if (profile == null) throw new IllegalArgumentException("The requested profile '" + profileName + "' does not exist.\nAvailable profiles: " + profilesByName.keySet()); return profile; } protected String doResolveProfile(String profileName, PMap hints) { Profile profile = profilesByName.get(profileName); return profile == null ? null : profile.getName(); } public static void errorIfLegacyParameters(PMap hints) {<FILL_FUNCTION_BODY>} }
if (hints.has("weighting")) throw new IllegalArgumentException("The 'weighting' parameter is no longer supported." + " You used 'weighting=" + hints.getString("weighting", "") + "'"); if (hints.has("vehicle")) throw new IllegalArgumentException("The 'vehicle' parameter is no longer supported." + " You used 'vehicle=" + hints.getString("vehicle", "") + "'"); if (hints.has("edge_based")) throw new IllegalArgumentException("The 'edge_based' parameter is no longer supported." + " You used 'edge_based=" + hints.getBool("edge_based", false) + "'"); if (hints.has("turn_costs")) throw new IllegalArgumentException("The 'turn_costs' parameter is no longer supported." + " You used 'turn_costs=" + hints.getBool("turn_costs", false) + "'");
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/PtRedirectFilter.java
PtRedirectFilter
shouldRedirect
class PtRedirectFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { if (shouldRedirect(requestContext)) { if (requestContext.getUriInfo().getPath().equals("route")) { URI forwardURI = requestContext.getUriInfo().getRequestUriBuilder().replacePath("/route-pt") .replaceQueryParam("vehicle") .replaceQueryParam("profile") .build(); requestContext.setRequestUri(forwardURI); } else if (requestContext.getUriInfo().getPath().equals("isochrone")) { URI forwardURI = requestContext.getUriInfo().getRequestUriBuilder().replacePath("/isochrone-pt") .replaceQueryParam("vehicle") .replaceQueryParam("profile") .build(); requestContext.setRequestUri(forwardURI); } } } private boolean shouldRedirect(ContainerRequestContext requestContext) {<FILL_FUNCTION_BODY>} }
String maybeVehicle = requestContext.getUriInfo().getQueryParameters().getFirst("vehicle"); String maybeProfile = requestContext.getUriInfo().getQueryParameters().getFirst("profile"); return "pt".equals(maybeVehicle) || "pt".equals(maybeProfile);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/RealtimeBundle.java
RealtimeBundle
run
class RealtimeBundle implements ConfiguredBundle<RealtimeBundleConfiguration> { @Override public void initialize(Bootstrap<?> bootstrap) { } @Override public void run(RealtimeBundleConfiguration configuration, Environment environment) {<FILL_FUNCTION_BODY>} private static class EmptyRealtimeFeedFactory implements Factory<RealtimeFeed> { private final GtfsStorage staticGtfs; @Inject EmptyRealtimeFeedFactory(GtfsStorage staticGtfs) { this.staticGtfs = staticGtfs; } @Override public RealtimeFeed provide() { return RealtimeFeed.empty(); } @Override public void dispose(RealtimeFeed realtimeFeed) { } } }
if (configuration.gtfsrealtime().getFeeds().isEmpty()) { environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bindFactory(EmptyRealtimeFeedFactory.class).to(RealtimeFeed.class).in(Singleton.class); } }); } else { final HttpClient httpClient = new HttpClientBuilder(environment) .using(configuration.gtfsrealtime().getHttpClientConfiguration()) .build("gtfs-realtime-feed-loader"); environment.jersey().register(new AbstractBinder() { @Override protected void configure() { bind(httpClient).to(HttpClient.class); bind(configuration).to(RealtimeBundleConfiguration.class); bindFactory(RealtimeFeedLoadingCache.class, Singleton.class).to(RealtimeFeed.class); } }); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/RealtimeFeedLoadingCache.java
RealtimeFeedLoadingCache
reload
class RealtimeFeedLoadingCache implements Factory<RealtimeFeed>, Managed { private final HttpClient httpClient; private final BaseGraph baseGraph; private final EncodingManager encodingManager; private final GtfsStorage gtfsStorage; private final RealtimeBundleConfiguration bundleConfiguration; private ExecutorService executor; private LoadingCache<String, RealtimeFeed> cache; private Map<String, Transfers> transfers; @Inject RealtimeFeedLoadingCache(BaseGraph baseGraph, EncodingManager encodingManager, GtfsStorage gtfsStorage, HttpClient httpClient, RealtimeBundleConfiguration bundleConfiguration) { this.baseGraph = baseGraph; this.encodingManager = encodingManager; this.gtfsStorage = gtfsStorage; this.bundleConfiguration = bundleConfiguration; this.httpClient = httpClient; } @Override public void start() { this.transfers = new HashMap<>(); for (Map.Entry<String, GTFSFeed> entry : this.gtfsStorage.getGtfsFeeds().entrySet()) { this.transfers.put(entry.getKey(), new Transfers(entry.getValue())); } this.executor = Executors.newSingleThreadExecutor(); this.cache = CacheBuilder.newBuilder() .maximumSize(1) .refreshAfterWrite(1, TimeUnit.MINUTES) .build(new CacheLoader<String, RealtimeFeed>() { public RealtimeFeed load(String key) { return fetchFeedsAndCreateGraph(); } @Override public ListenableFuture<RealtimeFeed> reload(String key, RealtimeFeed oldValue) {<FILL_FUNCTION_BODY>} }); } @Override public RealtimeFeed provide() { try { return cache.get("pups"); } catch (ExecutionException | RuntimeException e) { e.printStackTrace(); return RealtimeFeed.empty(); } } @Override public void dispose(RealtimeFeed instance) { this.executor.shutdown(); } @Override public void stop() { } private RealtimeFeed fetchFeedsAndCreateGraph() { Map<String, GtfsRealtime.FeedMessage> feedMessageMap = new HashMap<>(); for (FeedConfiguration configuration : bundleConfiguration.gtfsrealtime().getFeeds()) { try { GtfsRealtime.FeedMessage feedMessage = GtfsRealtime.FeedMessage.parseFrom(httpClient.execute(new HttpGet(configuration.getUrl().toURI())).getEntity().getContent()); feedMessageMap.put(configuration.getFeedId(), feedMessage); } catch (IOException | URISyntaxException e) { throw new RuntimeException(e); } } return RealtimeFeed.fromProtobuf(gtfsStorage, this.transfers, feedMessageMap); } }
ListenableFutureTask<RealtimeFeed> task = ListenableFutureTask.create(() -> fetchFeedsAndCreateGraph()); executor.execute(task); return task;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/TypeGPXFilter.java
TypeGPXFilter
filter
class TypeGPXFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext rc) {<FILL_FUNCTION_BODY>} }
String maybeType = rc.getUriInfo().getQueryParameters().getFirst("type"); if (maybeType != null && maybeType.equals("gpx")) { rc.getHeaders().putSingle(HttpHeaders.ACCEPT, "application/gpx+xml"); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/http/health/GraphHopperHealthCheck.java
GraphHopperHealthCheck
check
class GraphHopperHealthCheck extends HealthCheck { private final GraphHopper graphHopper; public GraphHopperHealthCheck(GraphHopper graphHopper) { this.graphHopper = graphHopper; } @Override protected Result check() {<FILL_FUNCTION_BODY>} }
if (!graphHopper.getBaseGraph().getBounds().isValid()) { return Result.unhealthy("BaseGraph has invalid bounds."); } if (!graphHopper.getFullyLoaded()) { return Result.unhealthy("GraphHopper is not fully loaded."); } return Result.healthy();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/HealthCheckResource.java
HealthCheckResource
doGet
class HealthCheckResource { private HealthCheckRegistry registry; @Inject public HealthCheckResource(HealthCheckRegistry registry) { this.registry = registry; } @GET public Response doGet() {<FILL_FUNCTION_BODY>} }
SortedMap<String, HealthCheck.Result> results = registry.runHealthChecks(); for (HealthCheck.Result result : results.values()) { if (!result.isHealthy()) { return Response.status(500).entity("UNHEALTHY").build(); } } return Response.ok("OK").build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/I18NResource.java
I18NResource
get
class I18NResource { private final TranslationMap map; @Inject public I18NResource(TranslationMap map) { this.map = map; } public static class Response { public String locale; public Map<String, String> en; @JsonProperty("default") public Map<String, String> defaultTr; } @GET public Response getFromHeader(@HeaderParam("Accept-Language") String acceptLang) { if (acceptLang == null) return get(""); return get(acceptLang.split(",")[0]); } @GET @Path("/{locale}") public Response get(@PathParam("locale") String locale) {<FILL_FUNCTION_BODY>} }
Translation tr = map.get(locale); Response json = new Response(); if (tr != null && !Locale.US.equals(tr.getLocale())) { json.defaultTr = tr.asMap(); } json.locale = locale; json.en = map.get("en").asMap(); return json;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/InfoResource.java
InfoResource
getInfo
class InfoResource { private final GraphHopperConfig config; private final BaseGraph baseGraph; private final EncodingManager encodingManager; private final StorableProperties properties; private final boolean hasElevation; private final Set<String> privateEV; @Inject public InfoResource(GraphHopperConfig config, GraphHopper graphHopper, @Named("hasElevation") Boolean hasElevation) { this.config = config; this.encodingManager = graphHopper.getEncodingManager(); this.privateEV = new HashSet<>(Arrays.asList(config.getString("graph.encoded_values.private", "").split(","))); for (String pEV : privateEV) { if (!pEV.isEmpty() && !encodingManager.hasEncodedValue(pEV)) throw new IllegalArgumentException("A private encoded value does not exist."); } this.baseGraph = graphHopper.getBaseGraph(); this.properties = graphHopper.getProperties(); this.hasElevation = hasElevation; } public static class Info { public static class ProfileData { // for deserialization in e.g. tests public ProfileData() { } public ProfileData(String name) { this.name = name; } public String name; } public Envelope bbox; public final List<ProfileData> profiles = new ArrayList<>(); public String version = Constants.VERSION; public boolean elevation; public Map<String, List<Object>> encoded_values; public String import_date; public String data_date; } @GET public Info getInfo() {<FILL_FUNCTION_BODY>} }
final Info info = new Info(); info.bbox = new Envelope(baseGraph.getBounds().minLon, baseGraph.getBounds().maxLon, baseGraph.getBounds().minLat, baseGraph.getBounds().maxLat); for (Profile p : config.getProfiles()) { Info.ProfileData profileData = new Info.ProfileData(p.getName()); info.profiles.add(profileData); } if (config.has("gtfs.file")) info.profiles.add(new Info.ProfileData("pt")); info.elevation = hasElevation; info.import_date = properties.get("datareader.import.date"); info.data_date = properties.get("datareader.data.date"); List<EncodedValue> evList = encodingManager.getEncodedValues(); info.encoded_values = new LinkedHashMap<>(); for (EncodedValue encodedValue : evList) { List<Object> possibleValueList = new ArrayList<>(); String name = encodedValue.getName(); if (privateEV.contains(name)) { continue; } else if (encodedValue instanceof EnumEncodedValue) { for (Enum o : ((EnumEncodedValue) encodedValue).getValues()) { possibleValueList.add(o.name()); } } else if (encodedValue instanceof BooleanEncodedValue) { possibleValueList.add("true"); possibleValueList.add("false"); } else if (encodedValue instanceof DecimalEncodedValue || encodedValue instanceof IntEncodedValue) { possibleValueList.add(">number"); possibleValueList.add("<number"); } else { // we only add enum, boolean and numeric encoded values to the list continue; } info.encoded_values.put(name, possibleValueList); } return info;
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/MVTResource.java
MVTResource
doGetXyz
class MVTResource { private static final Logger logger = LoggerFactory.getLogger(MVTResource.class); private static final MediaType PBF = new MediaType("application", "x-protobuf"); private final GraphHopper graphHopper; private final EncodingManager encodingManager; @Inject public MVTResource(GraphHopper graphHopper, EncodingManager encodingManager) { this.graphHopper = graphHopper; this.encodingManager = encodingManager; } @GET @Path("{z}/{x}/{y}.mvt") @Produces("application/x-protobuf") public Response doGetXyz( @Context HttpServletRequest httpReq, @Context UriInfo uriInfo, @PathParam("z") int zInfo, @PathParam("x") int xInfo, @PathParam("y") int yInfo, @QueryParam("render_all") @DefaultValue("false") Boolean renderAll) {<FILL_FUNCTION_BODY>} Coordinate num2deg(int xInfo, int yInfo, int zoom) { // inverse web mercator projection double n = Math.pow(2, zoom); double lonDeg = xInfo / n * 360.0 - 180.0; // unfortunately latitude numbers goes from north to south double latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * yInfo / n))); double latDeg = Math.toDegrees(latRad); return new Coordinate(lonDeg, latDeg); } }
if (zInfo <= 9) { byte[] bytes = new VectorTileEncoder().encode(); return Response.fromResponse(Response.ok(bytes, PBF).build()) .header("X-GH-Took", "0") .build(); } StopWatch totalSW = new StopWatch().start(); Coordinate nw = num2deg(xInfo, yInfo, zInfo); Coordinate se = num2deg(xInfo + 1, yInfo + 1, zInfo); LocationIndexTree locationIndex = (LocationIndexTree) graphHopper.getLocationIndex(); final NodeAccess na = graphHopper.getBaseGraph().getNodeAccess(); BBox bbox = new BBox(nw.x, se.x, se.y, nw.y); if (!bbox.isValid()) throw new IllegalStateException("Invalid bbox " + bbox); final GeometryFactory geometryFactory = new GeometryFactory(); if (!encodingManager.hasEncodedValue(RoadClass.KEY)) throw new IllegalStateException("You need to configure GraphHopper to store road_class, e.g. graph.encoded_values: road_class,max_speed,... "); final EnumEncodedValue<RoadClass> roadClassEnc = encodingManager.getEnumEncodedValue(RoadClass.KEY, RoadClass.class); final AtomicInteger edgeCounter = new AtomicInteger(0); // 256x256 pixels per MVT. here we transform from the global coordinate system to the local one of the tile. AffineTransformation affineTransformation = new AffineTransformation(); affineTransformation.translate(-nw.x, -se.y); affineTransformation.scale( 256.0 / (se.x - nw.x), -256.0 / (nw.y - se.y) ); affineTransformation.translate(0, 256); // if performance of the vector tile encoding becomes an issue it might be worth to get rid of the simplification // and clipping in the no.ecc code? https://github.com/graphhopper/graphhopper/commit/0f96c2deddb24efa97109e35e0c05f1c91221f59#r90830001 VectorTileEncoder vectorTileEncoder = new VectorTileEncoder(); locationIndex.query(bbox, edgeId -> { EdgeIteratorState edge = graphHopper.getBaseGraph().getEdgeIteratorStateForKey(edgeId * 2); LineString lineString; if (renderAll) { PointList pl = edge.fetchWayGeometry(FetchMode.ALL); lineString = pl.toLineString(false); } else { RoadClass rc = edge.get(roadClassEnc); if (zInfo >= 14) { PointList pl = edge.fetchWayGeometry(FetchMode.ALL); lineString = pl.toLineString(false); } else if (rc == RoadClass.MOTORWAY || zInfo > 10 && (rc == RoadClass.PRIMARY || rc == RoadClass.TRUNK) || zInfo > 11 && (rc == RoadClass.SECONDARY) || zInfo > 12) { double lat = na.getLat(edge.getBaseNode()); double lon = na.getLon(edge.getBaseNode()); double toLat = na.getLat(edge.getAdjNode()); double toLon = na.getLon(edge.getAdjNode()); lineString = geometryFactory.createLineString(new Coordinate[]{new Coordinate(lon, lat), new Coordinate(toLon, toLat)}); } else { // skip edge for certain zoom return; } } edgeCounter.incrementAndGet(); Map<String, Object> map = new LinkedHashMap<>(); edge.getKeyValues().forEach( entry -> map.put(entry.key, entry.value) ); map.put("edge_id", edge.getEdge()); map.put("edge_key", edge.getEdgeKey()); map.put("base_node", edge.getBaseNode()); map.put("adj_node", edge.getAdjNode()); map.put("distance", edge.getDistance()); encodingManager.getEncodedValues().forEach(ev -> { if (ev instanceof EnumEncodedValue) map.put(ev.getName(), edge.get((EnumEncodedValue) ev).toString() + (ev.isStoreTwoDirections() ? " | " + edge.getReverse((EnumEncodedValue) ev).toString() : "")); else if (ev instanceof DecimalEncodedValue) map.put(ev.getName(), edge.get((DecimalEncodedValue) ev) + (ev.isStoreTwoDirections() ? " | " + edge.getReverse((DecimalEncodedValue) ev) : "")); else if (ev instanceof BooleanEncodedValue) map.put(ev.getName(), edge.get((BooleanEncodedValue) ev) + (ev.isStoreTwoDirections() ? " | " + edge.getReverse((BooleanEncodedValue) ev) : "")); else if (ev instanceof IntEncodedValue) map.put(ev.getName(), edge.get((IntEncodedValue) ev) + (ev.isStoreTwoDirections() ? " | " + edge.getReverse((IntEncodedValue) ev) : "")); }); lineString.setUserData(map); Geometry g = affineTransformation.transform(lineString); vectorTileEncoder.addFeature("roads", map, g, edge.getEdge()); }); byte[] bytes = vectorTileEncoder.encode(); totalSW.stop(); logger.debug("took: " + totalSW.getMillis() + "ms, edges:" + edgeCounter.get()); return Response.ok(bytes, PBF).header("X-GH-Took", "" + totalSW.getSeconds() * 1000) .build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/NearestResource.java
NearestResource
doGet
class NearestResource { private final DistanceCalc calc = DistanceCalcEarth.DIST_EARTH; private final LocationIndex index; private final boolean hasElevation; @Inject NearestResource(LocationIndex index, @Named("hasElevation") Boolean hasElevation) { this.index = index; this.hasElevation = hasElevation; } public static class Response { public final String type = "Point"; public final double[] coordinates; public final double distance; // Distance from input to snapped point in meters @JsonCreator Response(@JsonProperty("coordinates") double[] coordinates, @JsonProperty("distance") double distance) { this.coordinates = coordinates; this.distance = distance; } } @GET public Response doGet(@QueryParam("point") GHPoint point, @QueryParam("elevation") @DefaultValue("false") boolean elevation) {<FILL_FUNCTION_BODY>} }
Snap snap = index.findClosest(point.lat, point.lon, EdgeFilter.ALL_EDGES); if (snap.isValid()) { GHPoint3D snappedPoint = snap.getSnappedPoint(); double[] coordinates = hasElevation && elevation ? new double[]{snappedPoint.lon, snappedPoint.lat, snappedPoint.ele} : new double[]{snappedPoint.lon, snappedPoint.lat}; return new Response(coordinates, calc.calcDist(point.lat, point.lon, snappedPoint.lat, snappedPoint.lon)); } else { throw new WebApplicationException("Nearest point cannot be found!"); }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/PtIsochroneResource.java
PtIsochroneResource
doGet
class PtIsochroneResource { private static final double JTS_TOLERANCE = 0.00001; private final GraphHopperConfig config; private final GtfsStorage gtfsStorage; private final EncodingManager encodingManager; private final BaseGraph baseGraph; private final LocationIndex locationIndex; @Inject public PtIsochroneResource(GraphHopperConfig config, GtfsStorage gtfsStorage, EncodingManager encodingManager, BaseGraph baseGraph, LocationIndex locationIndex) { this.config = config; this.gtfsStorage = gtfsStorage; this.encodingManager = encodingManager; this.baseGraph = baseGraph; this.locationIndex = locationIndex; } public static class Response { public static class Info { public List<String> copyrights = new ArrayList<>(); } public List<JsonFeature> polygons = new ArrayList<>(); public Info info = new Info(); } @GET @Produces({MediaType.APPLICATION_JSON}) public Response doGet( @QueryParam("point") GHLocationParam sourceParam, @QueryParam("time_limit") @DefaultValue("600") long seconds, @QueryParam("reverse_flow") @DefaultValue("false") boolean reverseFlow, @QueryParam("pt.earliest_departure_time") @NotNull OffsetDateTimeParam departureTimeParam, @QueryParam("pt.blocked_route_types") @DefaultValue("0") int blockedRouteTypes, @QueryParam("result") @DefaultValue("multipolygon") String format) {<FILL_FUNCTION_BODY>} private Response wrap(Geometry isoline) { JsonFeature feature = new JsonFeature(); feature.setGeometry(isoline); HashMap<String, Object> properties = new HashMap<>(); properties.put("bucket", 0); feature.setProperties(properties); Response response = new Response(); response.polygons.add(feature); response.info.copyrights.addAll(config.getCopyrights()); return response; } }
Instant initialTime = departureTimeParam.get().toInstant(); GHLocation location = sourceParam.get(); double targetZ = seconds * 1000; GeometryFactory geometryFactory = new GeometryFactory(); CustomModel customModel = new CustomModel() .addToPriority(Statement.If("!" + VehicleAccess.key("foot"), Statement.Op.MULTIPLY, "0")) .addToSpeed(Statement.If("true", Statement.Op.LIMIT, VehicleSpeed.key("foot"))); final Weighting weighting = CustomModelParser.createWeighting(encodingManager, TurnCostProvider.NO_TURN_COST_PROVIDER, customModel); DefaultSnapFilter snapFilter = new DefaultSnapFilter(weighting, encodingManager.getBooleanEncodedValue(Subnetwork.key("foot"))); PtLocationSnapper.Result snapResult = new PtLocationSnapper(baseGraph, locationIndex, gtfsStorage).snapAll(Arrays.asList(location), Arrays.asList(snapFilter)); GraphExplorer graphExplorer = new GraphExplorer(snapResult.queryGraph, gtfsStorage.getPtGraph(), weighting, gtfsStorage, RealtimeFeed.empty(), reverseFlow, false, false, 5.0, reverseFlow, blockedRouteTypes); MultiCriteriaLabelSetting router = new MultiCriteriaLabelSetting(graphExplorer, reverseFlow, false, false, 0, Collections.emptyList()); Map<Coordinate, Double> z1 = new HashMap<>(); NodeAccess nodeAccess = snapResult.queryGraph.getNodeAccess(); for (Label label : router.calcLabels(snapResult.nodes.get(0), initialTime)) { if (!((label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1) <= targetZ)) { break; } if (label.node.streetNode != -1) { Coordinate nodeCoordinate = new Coordinate(nodeAccess.getLon(label.node.streetNode), nodeAccess.getLat(label.node.streetNode)); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } else if (label.edge != null && (label.edge.getType() == GtfsStorage.EdgeType.EXIT_PT || label.edge.getType() == GtfsStorage.EdgeType.ENTER_PT)) { GtfsStorage.PlatformDescriptor platformDescriptor = label.edge.getPlatformDescriptor(); Stop stop = gtfsStorage.getGtfsFeeds().get(platformDescriptor.feed_id).stops.get(platformDescriptor.stop_id); Coordinate nodeCoordinate = new Coordinate(stop.stop_lon, stop.stop_lat); z1.merge(nodeCoordinate, (double) (label.currentTime - initialTime.toEpochMilli()) * (reverseFlow ? -1 : 1), Math::min); } } if (format.equals("multipoint")) { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); return wrap(exploredPoints); } else { MultiPoint exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); // Get at least all nodes within our bounding box (I think convex hull would be enough.) // I think then we should have all possible encroaching points. (Proof needed.) locationIndex.query(BBox.fromEnvelope(exploredPoints.getEnvelopeInternal()), edgeId -> { EdgeIteratorState edge = snapResult.queryGraph.getEdgeIteratorStateForKey(edgeId * 2); z1.merge(new Coordinate(nodeAccess.getLon(edge.getBaseNode()), nodeAccess.getLat(edge.getBaseNode())), Double.MAX_VALUE, Math::min); z1.merge(new Coordinate(nodeAccess.getLon(edge.getAdjNode()), nodeAccess.getLat(edge.getAdjNode())), Double.MAX_VALUE, Math::min); }); exploredPoints = geometryFactory.createMultiPointFromCoords(z1.keySet().toArray(new Coordinate[0])); CoordinateList siteCoords = DelaunayTriangulationBuilder.extractUniqueCoordinates(exploredPoints); List<ConstraintVertex> constraintVertices = new ArrayList<>(); for (Object siteCoord : siteCoords) { Coordinate coord = (Coordinate) siteCoord; constraintVertices.add(new ConstraintVertex(coord)); } ConformingDelaunayTriangulator cdt = new ConformingDelaunayTriangulator(constraintVertices, JTS_TOLERANCE); cdt.setConstraints(new ArrayList(), new ArrayList()); cdt.formInitialDelaunay(); QuadEdgeSubdivision tin = cdt.getSubdivision(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { if (tin.isFrameVertex(vertex)) { vertex.setZ(Double.MAX_VALUE); } else { Double aDouble = z1.get(vertex.getCoordinate()); if (aDouble != null) { vertex.setZ(aDouble); } else { vertex.setZ(Double.MAX_VALUE); } } } ReadableTriangulation triangulation = ReadableTriangulation.wrap(tin); ContourBuilder contourBuilder = new ContourBuilder(triangulation); MultiPolygon isoline = contourBuilder.computeIsoline(targetZ, triangulation.getEdges()); // debugging tool if (format.equals("triangulation")) { Response response = new Response(); for (Vertex vertex : (Collection<Vertex>) tin.getVertices(true)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(geometryFactory.createPoint(vertex.getCoordinate())); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", vertex.getZ()); feature.setProperties(properties); response.polygons.add(feature); } for (QuadEdge edge : (Collection<QuadEdge>) tin.getPrimaryEdges(false)) { JsonFeature feature = new JsonFeature(); feature.setGeometry(edge.toLineSegment().toGeometry(geometryFactory)); HashMap<String, Object> properties = new HashMap<>(); feature.setProperties(properties); response.polygons.add(feature); } JsonFeature feature = new JsonFeature(); feature.setGeometry(isoline); HashMap<String, Object> properties = new HashMap<>(); properties.put("z", targetZ); feature.setProperties(properties); response.polygons.add(feature); response.info.copyrights.addAll(config.getCopyrights()); return response; } else { return wrap(isoline); } }
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/PtMVTResource.java
PtMVTResource
doGetXyz
class PtMVTResource { private static final Logger logger = LoggerFactory.getLogger(PtMVTResource.class); private static final MediaType PBF = new MediaType("application", "x-protobuf"); private final GraphHopper graphHopper; private final GtfsStorage gtfsStorage; private final Map<ByteString, MatchResult> openLRCache = new ConcurrentHashMap<>(); private final GeometryFactory geometryFactory = new GeometryFactory(); @Inject public PtMVTResource(GraphHopper graphHopper, GtfsStorage gtfsStorage) throws IOException { this.graphHopper = graphHopper; this.gtfsStorage = gtfsStorage; } @GET @Path("{z}/{x}/{y}.mvt") @Produces("application/x-protobuf") public Response doGetXyz( @Context HttpServletRequest httpReq, @Context UriInfo uriInfo, @PathParam("z") int zInfo, @PathParam("x") int xInfo, @PathParam("y") int yInfo, @QueryParam(Parameters.Details.PATH_DETAILS) List<String> pathDetails) {<FILL_FUNCTION_BODY>} Coordinate num2deg(int xInfo, int yInfo, int zoom) { double n = Math.pow(2, zoom); double lonDeg = xInfo / n * 360.0 - 180.0; // unfortunately latitude numbers goes from north to south double latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * yInfo / n))); double latDeg = Math.toDegrees(latRad); return new Coordinate(lonDeg, latDeg); } }
Coordinate nw = num2deg(xInfo, yInfo, zInfo); Coordinate se = num2deg(xInfo + 1, yInfo + 1, zInfo); BBox bbox = new BBox(nw.x, se.x, se.y, nw.y); if (!bbox.isValid()) throw new IllegalStateException("Invalid bbox " + bbox); VectorTileEncoder vectorTileEncoder = new VectorTileEncoder(); // 256x256 pixels per MVT. here we transform from the global coordinate system to the local one of the tile. AffineTransformation affineTransformation = new AffineTransformation(); affineTransformation.translate(-nw.x, -se.y); affineTransformation.scale( 256.0 / (se.x - nw.x), -256.0 / (nw.y - se.y) ); affineTransformation.translate(0, 256); gtfsStorage.getStopIndex().query(bbox, edgeId -> { for (PtGraph.PtEdge ptEdge : gtfsStorage.getPtGraph().backEdgesAround(edgeId)) { if (ptEdge.getType() == GtfsStorage.EdgeType.EXIT_PT) { GtfsStorage.PlatformDescriptor fromPlatformDescriptor = ptEdge.getAttrs().platformDescriptor; Stop stop = gtfsStorage.getGtfsFeeds().get(fromPlatformDescriptor.feed_id).stops.get(fromPlatformDescriptor.stop_id); Map<String, Object> properties = new HashMap<>(2); properties.put("feed_id", fromPlatformDescriptor.feed_id); properties.put("stop_id", fromPlatformDescriptor.stop_id); Point feature = geometryFactory.createPoint(new Coordinate(stop.stop_lon, stop.stop_lat)); feature.setUserData(properties); Geometry g = affineTransformation.transform(feature); vectorTileEncoder.addFeature("stops", properties, g); } } }); return Response.ok(vectorTileEncoder.encode(), PBF).build();
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/com/graphhopper/resources/PtRouteResource.java
PtRouteResource
route
class PtRouteResource { private final GraphHopperConfig config; private final PtRouter ptRouter; @Inject public PtRouteResource(GraphHopperConfig config, PtRouter ptRouter) { this.config = config; this.ptRouter = ptRouter; } @GET @Produces(MediaType.APPLICATION_JSON) public ObjectNode route(@QueryParam("point") @Size(min=2,max=2) List<GHLocationParam> requestPoints, @QueryParam("pt.earliest_departure_time") @NotNull OffsetDateTimeParam departureTimeParam, @QueryParam("pt.profile_duration") DurationParam profileDuration, @QueryParam("pt.arrive_by") @DefaultValue("false") boolean arriveBy, @QueryParam("locale") String localeStr, @QueryParam("pt.ignore_transfers") Boolean ignoreTransfers, @QueryParam("pt.profile") Boolean profileQuery, @QueryParam("pt.limit_solutions") Integer limitSolutions, @QueryParam("pt.limit_trip_time") DurationParam limitTripTime, @QueryParam("pt.limit_street_time") DurationParam limitStreetTime, @QueryParam("pt.access_profile") String accessProfile, @QueryParam("pt.beta_access_time") Double betaAccessTime, @QueryParam("pt.egress_profile") String egressProfile, @QueryParam("pt.beta_egress_time") Double betaEgressTime) {<FILL_FUNCTION_BODY>} }
StopWatch stopWatch = new StopWatch().start(); List<GHLocation> points = requestPoints.stream().map(AbstractParam::get).collect(toList()); Instant departureTime = departureTimeParam.get().toInstant(); Request request = new Request(points, departureTime); request.setArriveBy(arriveBy); Optional.ofNullable(profileQuery).ifPresent(request::setProfileQuery); Optional.ofNullable(profileDuration.get()).ifPresent(request::setMaxProfileDuration); Optional.ofNullable(ignoreTransfers).ifPresent(request::setIgnoreTransfers); Optional.ofNullable(localeStr).ifPresent(s -> request.setLocale(Helper.getLocale(s))); Optional.ofNullable(limitSolutions).ifPresent(request::setLimitSolutions); Optional.ofNullable(limitTripTime.get()).ifPresent(request::setLimitTripTime); Optional.ofNullable(limitStreetTime.get()).ifPresent(request::setLimitStreetTime); Optional.ofNullable(accessProfile).ifPresent(request::setAccessProfile); Optional.ofNullable(betaAccessTime).ifPresent(request::setBetaAccessTime); Optional.ofNullable(egressProfile).ifPresent(request::setEgressProfile); Optional.ofNullable(betaEgressTime).ifPresent(request::setBetaEgressTime); GHResponse route = ptRouter.route(request); return ResponsePathSerializer.jsonObject(route, new ResponsePathSerializer.Info(config.getCopyrights(), Math.round(stopWatch.stop().getMillis()), null), true, true, false, false, -1);
graphhopper_graphhopper
graphhopper/web-bundle/src/main/java/no/ecc/vectortile/VectorTileDecoder.java
VectorTileDecoder
parseFeature
class VectorTileDecoder { private boolean autoScale = true; /** * Get the autoScale setting. * * @return autoScale */ public boolean isAutoScale() { return autoScale; } /** * Set the autoScale setting. * * @param autoScale * when true, the encoder automatically scale and return all coordinates in the 0..255 range. * when false, the encoder returns all coordinates in the 0..extent-1 range as they are encoded. * */ public void setAutoScale(boolean autoScale) { this.autoScale = autoScale; } public FeatureIterable decode(byte[] data) throws IOException { return decode(data, Filter.ALL); } public FeatureIterable decode(byte[] data, String layerName) throws IOException { return decode(data, new Filter.Single(layerName)); } public FeatureIterable decode(byte[] data, Set<String> layerNames) throws IOException { return decode(data, new Filter.Any(layerNames)); } public FeatureIterable decode(byte[] data, Filter filter) throws IOException { VectorTile.Tile tile = VectorTile.Tile.parseFrom(data); return new FeatureIterable(tile, filter, autoScale); } static int zigZagDecode(int n) { return ((n >> 1) ^ (-(n & 1))); } static Geometry decodeGeometry(GeometryFactory gf, GeomType geomType, List<Integer> commands, double scale) { int x = 0; int y = 0; List<List<Coordinate>> coordsList = new ArrayList<List<Coordinate>>(); List<Coordinate> coords = null; int geometryCount = commands.size(); int length = 0; int command = 0; int i = 0; while (i < geometryCount) { if (length <= 0) { length = commands.get(i++).intValue(); command = length & ((1 << 3) - 1); length = length >> 3; } if (length > 0) { if (command == Command.MoveTo) { coords = new ArrayList<Coordinate>(); coordsList.add(coords); } if (command == Command.ClosePath) { if (geomType != VectorTile.Tile.GeomType.POINT && !coords.isEmpty()) { coords.add(new Coordinate(coords.get(0))); } length--; continue; } int dx = commands.get(i++).intValue(); int dy = commands.get(i++).intValue(); length--; dx = zigZagDecode(dx); dy = zigZagDecode(dy); x = x + dx; y = y + dy; Coordinate coord = new Coordinate(x / scale, y / scale); coords.add(coord); } } Geometry geometry = null; switch (geomType) { case LINESTRING: List<LineString> lineStrings = new ArrayList<LineString>(); for (List<Coordinate> cs : coordsList) { if (cs.size() <= 1) { continue; } lineStrings.add(gf.createLineString(cs.toArray(new Coordinate[cs.size()]))); } if (lineStrings.size() == 1) { geometry = lineStrings.get(0); } else if (lineStrings.size() > 1) { geometry = gf.createMultiLineString(lineStrings.toArray(new LineString[lineStrings.size()])); } break; case POINT: List<Coordinate> allCoords = new ArrayList<Coordinate>(); for (List<Coordinate> cs : coordsList) { allCoords.addAll(cs); } if (allCoords.size() == 1) { geometry = gf.createPoint(allCoords.get(0)); } else if (allCoords.size() > 1) { geometry = gf.createMultiPointFromCoords(allCoords.toArray(new Coordinate[allCoords.size()])); } break; case POLYGON: List<List<LinearRing>> polygonRings = new ArrayList<List<LinearRing>>(); List<LinearRing> ringsForCurrentPolygon = null; Boolean ccw = null; for (List<Coordinate> cs : coordsList) { Coordinate[] ringCoords = cs.toArray(new Coordinate[cs.size()]); double area = Area.ofRingSigned(ringCoords); if (area == 0) { continue; } boolean thisCcw = area < 0; if (ccw == null) { ccw = thisCcw; } LinearRing ring = gf.createLinearRing(ringCoords); if (ccw == thisCcw) { if (ringsForCurrentPolygon != null) { polygonRings.add(ringsForCurrentPolygon); } ringsForCurrentPolygon = new ArrayList<>(); } ringsForCurrentPolygon.add(ring); } if (ringsForCurrentPolygon != null) { polygonRings.add(ringsForCurrentPolygon); } List<Polygon> polygons = new ArrayList<Polygon>(); for (List<LinearRing> rings : polygonRings) { LinearRing shell = rings.get(0); LinearRing[] holes = rings.subList(1, rings.size()).toArray(new LinearRing[rings.size() - 1]); polygons.add(gf.createPolygon(shell, holes)); } if (polygons.size() == 1) { geometry = polygons.get(0); } if (polygons.size() > 1) { geometry = gf.createMultiPolygon(GeometryFactory.toPolygonArray(polygons)); } break; case UNKNOWN: break; default: break; } if (geometry == null) { geometry = gf.createGeometryCollection(new Geometry[0]); } return geometry; } public static final class FeatureIterable implements Iterable<Feature> { private final VectorTile.Tile tile; private final Filter filter; private boolean autoScale; public FeatureIterable(VectorTile.Tile tile, Filter filter, boolean autoScale) { this.tile = tile; this.filter = filter; this.autoScale = autoScale; } public Iterator<Feature> iterator() { return new FeatureIterator(tile, filter, autoScale); } public List<Feature> asList() { List<Feature> features = new ArrayList<VectorTileDecoder.Feature>(); for (Feature feature : this) { features.add(feature); } return features; } public Collection<String> getLayerNames() { Set<String> layerNames = new HashSet<String>(); for (VectorTile.Tile.Layer layer : tile.getLayersList()) { layerNames.add(layer.getName()); } return Collections.unmodifiableSet(layerNames); } } private static final class FeatureIterator implements Iterator<Feature> { private final GeometryFactory gf = new GeometryFactory(); private final Filter filter; private final Iterator<VectorTile.Tile.Layer> layerIterator; private Iterator<VectorTile.Tile.Feature> featureIterator; private int extent; private String layerName; private double scale; private boolean autoScale; private final List<String> keys = new ArrayList<String>(); private final List<Object> values = new ArrayList<Object>(); private Feature next; public FeatureIterator(VectorTile.Tile tile, Filter filter, boolean autoScale) { layerIterator = tile.getLayersList().iterator(); this.filter = filter; this.autoScale = autoScale; } public boolean hasNext() { findNext(); return next != null; } public Feature next() { findNext(); if (next == null) { throw new NoSuchElementException(); } Feature n = next; next = null; return n; } private void findNext() { if (next != null) { return; } while (true) { if (featureIterator == null || !featureIterator.hasNext()) { if (!layerIterator.hasNext()) { next = null; break; } Layer layer = layerIterator.next(); if (!filter.include(layer.getName())) { continue; } parseLayer(layer); continue; } next = parseFeature(featureIterator.next()); break; } } private void parseLayer(VectorTile.Tile.Layer layer) { layerName = layer.getName(); extent = layer.getExtent(); scale = autoScale ? extent / 256.0 : 1.0; keys.clear(); keys.addAll(layer.getKeysList()); values.clear(); for (VectorTile.Tile.Value value : layer.getValuesList()) { if (value.hasBoolValue()) { values.add(value.getBoolValue()); } else if (value.hasDoubleValue()) { values.add(value.getDoubleValue()); } else if (value.hasFloatValue()) { values.add(value.getFloatValue()); } else if (value.hasIntValue()) { values.add(value.getIntValue()); } else if (value.hasSintValue()) { values.add(value.getSintValue()); } else if (value.hasUintValue()) { values.add(value.getUintValue()); } else if (value.hasStringValue()) { values.add(value.getStringValue()); } else { values.add(null); } } featureIterator = layer.getFeaturesList().iterator(); } private Feature parseFeature(VectorTile.Tile.Feature feature) {<FILL_FUNCTION_BODY>} public void remove() { throw new UnsupportedOperationException(); } } public static final class Feature { private final String layerName; private final int extent; private final long id; private final Geometry geometry; private final Map<String, Object> attributes; public Feature(String layerName, int extent, Geometry geometry, Map<String, Object> attributes, long id) { this.layerName = layerName; this.extent = extent; this.geometry = geometry; this.attributes = attributes; this.id = id; } public String getLayerName() { return layerName; } public long getId() { return id; } public int getExtent() { return extent; } public Geometry getGeometry() { return geometry; } public Map<String, Object> getAttributes() { return attributes; } } }
int tagsCount = feature.getTagsCount(); Map<String, Object> attributes = new HashMap<String, Object>(tagsCount / 2); int tagIdx = 0; while (tagIdx < feature.getTagsCount()) { String key = keys.get(feature.getTags(tagIdx++)); Object value = values.get(feature.getTags(tagIdx++)); attributes.put(key, value); } Geometry geometry = decodeGeometry(gf, feature.getType(), feature.getGeometryList(), scale); if (geometry == null) { geometry = gf.createGeometryCollection(new Geometry[0]); } return new Feature(layerName, extent, geometry, Collections.unmodifiableMap(attributes), feature.getId());
graphhopper_graphhopper
graphhopper/web/src/main/java/com/graphhopper/application/GraphHopperApplication.java
GraphHopperApplication
initialize
class GraphHopperApplication extends Application<GraphHopperServerConfiguration> { public static void main(String[] args) throws Exception { new GraphHopperApplication().run(args); } @Override public void initialize(Bootstrap<GraphHopperServerConfiguration> bootstrap) {<FILL_FUNCTION_BODY>} @Override public void run(GraphHopperServerConfiguration configuration, Environment environment) { environment.jersey().register(new RootResource()); environment.jersey().register(NavigateResource.class); environment.servlets().addFilter("cors", CORSFilter.class).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "*"); } }
bootstrap.addBundle(new GraphHopperBundle()); bootstrap.addBundle(new RealtimeBundle()); bootstrap.addCommand(new ImportCommand()); bootstrap.addCommand(new MatchCommand()); bootstrap.addBundle(new AssetsBundle("/com/graphhopper/maps/", "/maps/", "index.html")); // see this link even though its outdated?! // https://www.webjars.org/documentation#dropwizard bootstrap.addBundle(new AssetsBundle("/META-INF/resources/webjars", "/webjars/", null, "webjars"));
graphhopper_graphhopper
graphhopper/web/src/main/java/com/graphhopper/application/cli/MatchCommand.java
MatchCommand
addFileArgument
class MatchCommand extends ConfiguredCommand<GraphHopperServerConfiguration> { public MatchCommand() { super("match", "map-match one or more gpx files"); } @Override public void configure(Subparser subparser) { subparser.addArgument("gpx") .type(File.class) .required(true) .nargs("+") .help("GPX file"); subparser.addArgument("--file") .required(true) .help("application configuration file"); subparser.addArgument("--profile") .type(String.class) .required(true) .help("profile to use for map-matching (must be configured in configuration file)"); subparser.addArgument("--instructions") .type(String.class) .required(false) .setDefault("") .help("Locale for instructions"); subparser.addArgument("--gps_accuracy") .type(Integer.class) .required(false) .setDefault(40); subparser.addArgument("--transition_probability_beta") .type(Double.class) .required(false) .setDefault(2.0); } @Override protected Argument addFileArgument(Subparser subparser) {<FILL_FUNCTION_BODY>} @Override protected void run(Bootstrap<GraphHopperServerConfiguration> bootstrap, Namespace args, GraphHopperServerConfiguration configuration) { GraphHopperConfig graphHopperConfiguration = configuration.getGraphHopperConfiguration(); GraphHopper hopper = new GraphHopper().init(graphHopperConfiguration); hopper.importOrLoad(); PMap hints = new PMap(); hints.putObject("profile", args.get("profile")); MapMatching mapMatching = MapMatching.fromGraphHopper(hopper, hints); mapMatching.setTransitionProbabilityBeta(args.getDouble("transition_probability_beta")); mapMatching.setMeasurementErrorSigma(args.getInt("gps_accuracy")); StopWatch importSW = new StopWatch(); StopWatch matchSW = new StopWatch(); Translation tr = new TranslationMap().doImport().getWithFallBack(Helper.getLocale(args.getString("instructions"))); final boolean withRoute = !args.getString("instructions").isEmpty(); XmlMapper xmlMapper = new XmlMapper(); for (File gpxFile : args.<File>getList("gpx")) { try { importSW.start(); Gpx gpx = xmlMapper.readValue(gpxFile, Gpx.class); if (gpx.trk == null) { throw new IllegalArgumentException("No tracks found in GPX document. Are you using waypoints or routes instead?"); } if (gpx.trk.size() > 1) { throw new IllegalArgumentException("GPX documents with multiple tracks not supported yet."); } List<Observation> measurements = GpxConversions.getEntries(gpx.trk.get(0)); importSW.stop(); matchSW.start(); MatchResult mr = mapMatching.match(measurements); matchSW.stop(); System.out.println(gpxFile); System.out.println("\tmatches:\t" + mr.getEdgeMatches().size() + ", gps entries:" + measurements.size()); System.out.println("\tgpx length:\t" + (float) mr.getGpxEntriesLength() + " vs " + (float) mr.getMatchLength()); String outFile = gpxFile.getAbsolutePath() + ".res.gpx"; System.out.println("\texport results to:" + outFile); ResponsePath responsePath = new PathMerger(mr.getGraph(), mr.getWeighting()). doWork(PointList.EMPTY, Collections.singletonList(mr.getMergedPath()), hopper.getEncodingManager(), tr); if (responsePath.hasErrors()) { System.err.println("Problem with file " + gpxFile + ", " + responsePath.getErrors()); continue; } try (BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) { long time = gpx.trk.get(0).getStartTime() .map(Date::getTime) .orElse(System.currentTimeMillis()); writer.append(GpxConversions.createGPX(responsePath.getInstructions(), gpx.trk.get(0).name != null ? gpx.trk.get(0).name : "", time, hopper.hasElevation(), withRoute, true, false, Constants.VERSION, tr)); } } catch (Exception ex) { importSW.stop(); matchSW.stop(); System.err.println("Problem with file " + gpxFile); ex.printStackTrace(System.err); } } System.out.println("gps import took:" + importSW.getSeconds() + "s, match took: " + matchSW.getSeconds()); } }
// Never called, but overridden for clarity: // In this command, we want the configuration file parameter to be a named argument, // not a positional argument, because the positional arguments are the gpx files, // and we configure it up there ^^. // Must be called "file" because superclass gets it by name. throw new RuntimeException();
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Audio.java
Audio
init
class Audio { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化 */ public Audio init() {<FILL_FUNCTION_BODY>} public AudioResponse transcriptions(File audio,Transcriptions transcriptions){ RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio); MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a); Single<AudioResponse> audioResponse = this.apiClient.audioTranscriptions(aPart,transcriptions); return audioResponse.blockingGet(); } public AudioResponse translations(File audio,Transcriptions transcriptions){ RequestBody a = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), audio); MultipartBody.Part aPart = MultipartBody.Part.createFormData("image", audio.getName(), a); Single<AudioResponse> audioResponse = this.apiClient.audioTranslations(aPart,transcriptions); return audioResponse.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPT.java
ChatGPT
init
class ChatGPT { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化:与服务端建立连接,成功后可直接与服务端进行对话 */ public ChatGPT init() {<FILL_FUNCTION_BODY>} /** * 最新版的GPT-3.5 chat completion 更加贴近官方网站的问答模型 * * @param chatCompletion 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(ChatCompletion chatCompletion) { Single<ChatCompletionResponse> chatCompletionResponse = this.apiClient.chatCompletion(chatCompletion); return chatCompletionResponse.blockingGet(); } /** * 支持多个问答参数来与服务端进行对话 * * @param messages 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public ChatCompletionResponse chatCompletion(List<Message> messages) { ChatCompletion chatCompletion = ChatCompletion.builder().messages(messages).build(); return this.chatCompletion(chatCompletion); } /** * 与服务端进行对话 * @param message 问答参数,即咨询的内容 * @return 服务端的问答响应 */ public String chat(String message) { ChatCompletion chatCompletion = ChatCompletion.builder() .messages(Arrays.asList(Message.of(message))) .build(); ChatCompletionResponse response = this.chatCompletion(chatCompletion); return response.getChoices().get(0).getMessage().getContent(); } /** * 余额查询 * * @return 余额总金额及明细 */ public CreditGrantsResponse creditGrants() { Single<CreditGrantsResponse> creditGrants = this.apiClient.creditGrants(); return creditGrants.blockingGet(); } /** * 余额查询 * * @return 余额总金额 */ public BigDecimal balance() { Single<SubscriptionData> subscription = apiClient.subscription(); SubscriptionData subscriptionData = subscription.blockingGet(); BigDecimal total = subscriptionData.getHardLimitUsd(); DateTime start = DateUtil.offsetDay(new Date(), -90); DateTime end = DateUtil.offsetDay(new Date(), 1); Single<UseageResponse> usage = apiClient.usage(formatDate(start), formatDate(end)); UseageResponse useageResponse = usage.blockingGet(); BigDecimal used = useageResponse.getTotalUsage().divide(BigDecimal.valueOf(100)); return total.subtract(used); } /** * 新建连接进行余额查询 * * @return 余额总金额 */ public static BigDecimal balance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .build() .init(); return chatGPT.balance(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("ChatGPT init error!"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ChatGPTStream.java
ChatGPTStream
streamChatCompletion
class ChatGPTStream { private String apiKey; private List<String> apiKeyList; private OkHttpClient okHttpClient; /** * 连接超时 */ @Builder.Default private long timeout = 90; /** * 网络代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 反向代理 */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; /** * 初始化 */ public ChatGPTStream init() { OkHttpClient.Builder client = new OkHttpClient.Builder(); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } okHttpClient = client.build(); return this; } /** * 流式输出 */ public void streamChatCompletion(ChatCompletion chatCompletion, EventSourceListener eventSourceListener) {<FILL_FUNCTION_BODY>} /** * 流式输出 */ public void streamChatCompletion(List<Message> messages, EventSourceListener eventSourceListener) { ChatCompletion chatCompletion = ChatCompletion.builder() .messages(messages) .stream(true) .build(); streamChatCompletion(chatCompletion, eventSourceListener); } }
chatCompletion.setStream(true); try { EventSource.Factory factory = EventSources.createFactory(okHttpClient); ObjectMapper mapper = new ObjectMapper(); String requestBody = mapper.writeValueAsString(chatCompletion); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = new Request.Builder() .url(apiHost + "v1/chat/completions") .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody)) .header("Authorization", "Bearer " + key) .build(); factory.newEventSource(request, eventSourceListener); } catch (Exception e) { log.error("请求出错:{}", e); }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/ConsoleChatGPT.java
ConsoleChatGPT
main
class ConsoleChatGPT { public static Proxy proxy = Proxy.NO_PROXY; public static void main(String[] args) {<FILL_FUNCTION_BODY>} private static BigDecimal getBalance(String key) { ChatGPT chatGPT = ChatGPT.builder() .apiKey(key) .proxy(proxy) .build() .init(); return chatGPT.balance(); } private static void check(String key) { if (key == null || key.isEmpty()) { throw new RuntimeException("请输入正确的KEY"); } } @SneakyThrows public static String getInput(String prompt) { System.out.print(prompt); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); List<String> lines = new ArrayList<>(); String line; try { while ((line = reader.readLine()) != null && !line.isEmpty()) { lines.add(line); } } catch (IOException e) { e.printStackTrace(); } return lines.stream().collect(Collectors.joining("\n")); } }
System.out.println("ChatGPT - Java command-line interface"); System.out.println("Press enter twice to submit your question."); System.out.println(); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println("按两次回车以提交您的问题!!!"); System.out.println(); System.out.println("Please enter APIKEY, press Enter twice to submit:"); String key = getInput("请输入APIKEY,按两次回车以提交:\n"); check(key); // 询问用户是否使用代理 国内需要代理 System.out.println("是否使用代理?(y/n): "); System.out.println("use proxy?(y/n): "); String useProxy = getInput("按两次回车以提交:\n"); if (useProxy.equalsIgnoreCase("y")) { // 输入代理地址 System.out.println("请输入代理类型(http/socks): "); String type = getInput("按两次回车以提交:\n"); // 输入代理地址 System.out.println("请输入代理IP: "); String proxyHost = getInput("按两次回车以提交:\n"); // 输入代理端口 System.out.println("请输入代理端口: "); String portStr = getInput("按两次回车以提交:\n"); Integer proxyPort = Integer.parseInt(portStr); if (type.equals("http")) { proxy = Proxys.http(proxyHost, proxyPort); } else { proxy = Proxys.socks5(proxyHost, proxyPort); } } // System.out.println("Inquiry balance..."); // System.out.println("查询余额中..."); // BigDecimal balance = getBalance(key); // System.out.println("API KEY balance: " + balance.toPlainString()); // // if (!NumberUtil.isGreater(balance, BigDecimal.ZERO)) { // System.out.println("API KEY 余额不足: "); // return; // } while (true) { String prompt = getInput("\nYou:\n"); ChatGPTStream chatGPT = ChatGPTStream.builder() .apiKey(key) .proxy(proxy) .build() .init(); System.out.println("AI: "); //卡住 CountDownLatch countDownLatch = new CountDownLatch(1); Message message = Message.of(prompt); ConsoleStreamListener listener = new ConsoleStreamListener() { @Override public void onError(Throwable throwable, String response) { throwable.printStackTrace(); countDownLatch.countDown(); } }; listener.setOnComplate(msg -> { countDownLatch.countDown(); }); chatGPT.streamChatCompletion(Arrays.asList(message), listener); try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Embedding.java
Embedding
init
class Embedding { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; public Embedding init() {<FILL_FUNCTION_BODY>} /** * 生成向量 */ public EmbeddingResult createEmbeddings(EmbeddingRequest request) { Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request); return embeddingResultSingle.blockingGet(); } /** * 生成向量 */ public EmbeddingResult createEmbeddings(String input, String user) { EmbeddingRequest request = EmbeddingRequest.builder() .input(Collections.singletonList(input)) .model(EmbeddingRequest.EmbeddingModelEnum.TEXT_EMBEDDING_ADA_002.getModelName()) .user(user) .build(); Single<EmbeddingResult> embeddingResultSingle = this.apiClient.createEmbeddings(request); return embeddingResultSingle.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } this.okHttpClient = client.build(); this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Images.java
Images
init
class Images { /** * keys */ private String apiKey; private List<String> apiKeyList; /** * 自定义api host使用builder的方式构造client */ @Builder.Default private String apiHost = Api.DEFAULT_API_HOST; private Api apiClient; private OkHttpClient okHttpClient; /** * 超时 默认300 */ @Builder.Default private long timeout = 300; /** * okhttp 代理 */ @Builder.Default private Proxy proxy = Proxy.NO_PROXY; /** * 初始化 */ public Images init() {<FILL_FUNCTION_BODY>} public ImagesRensponse generations(Generations generations){ Single<ImagesRensponse> imagesRensponse = this.apiClient.imageGenerations(generations); return imagesRensponse.blockingGet(); } public ImagesRensponse edits(File image,File mask,Edits edits){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); RequestBody m = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), mask); MultipartBody.Part mPart = MultipartBody.Part.createFormData("mask", mask.getName(), m); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageEdits(iPart,mPart,edits); return imagesRensponse.blockingGet(); } public ImagesRensponse variations(File image,Variations variations){ RequestBody i = RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"), image); MultipartBody.Part iPart = MultipartBody.Part.createFormData("image", image.getName(), i); Single<ImagesRensponse> imagesRensponse = this.apiClient.imageVariations(iPart,variations); return imagesRensponse.blockingGet(); } }
OkHttpClient.Builder client = new OkHttpClient.Builder(); client.addInterceptor(chain -> { Request original = chain.request(); String key = apiKey; if (apiKeyList != null && !apiKeyList.isEmpty()) { key = RandomUtil.randomEle(apiKeyList); } Request request = original.newBuilder() .header(Header.AUTHORIZATION.getValue(), "Bearer " + key) .header(Header.CONTENT_TYPE.getValue(), ContentType.JSON.getValue()) .method(original.method(), original.body()) .build(); return chain.proceed(request); }).addInterceptor(chain -> { Request original = chain.request(); Response response = chain.proceed(original); if (!response.isSuccessful()) { String errorMsg = response.body().string(); log.error("请求异常:{}", errorMsg); BaseResponse baseResponse = JSON.parseObject(errorMsg, BaseResponse.class); if (Objects.nonNull(baseResponse.getError())) { log.error(baseResponse.getError().getMessage()); throw new ChatException(baseResponse.getError().getMessage()); } throw new ChatException("error"); } return response; }); client.connectTimeout(timeout, TimeUnit.SECONDS); client.writeTimeout(timeout, TimeUnit.SECONDS); client.readTimeout(timeout, TimeUnit.SECONDS); if (Objects.nonNull(proxy)) { client.proxy(proxy); } OkHttpClient httpClient = client.build(); this.okHttpClient = httpClient; this.apiClient = new Retrofit.Builder() .baseUrl(this.apiHost) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(JacksonConverterFactory.create()) .build() .create(Api.class); return this;
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/Test.java
Test
main
class Test { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
Proxy proxys = Proxys.http("127.0.0.1",10809); Images images = Images.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("C:\\Users\\马同徽\\Pictures\\微信图片_20230606140621.png"); Variations variations = Variations.ofURL(1,"256x256"); Generations generations = Generations.ofURL("一只鲨鱼和一直蜜蜂结合成一种动物",1,"256x256"); ImagesRensponse imagesRensponse = images.variations(file,variations); System.out.println(imagesRensponse.getCreated()); System.out.println(imagesRensponse.getCode()); System.out.println(imagesRensponse.getMsg()); List<Object> data = imagesRensponse.getData(); for(Object o:data){ System.out.println(o.toString()); } /*Audio audio = Audio.builder() .proxy(proxys) .apiKey("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") .apiHost("https://api.openai.com/") .timeout(900) .build() .init(); File file = new File("D:\\Jenny.mp3"); Transcriptions transcriptions = Transcriptions.of(file, AudioModel.WHISPER1.getValue()); AudioResponse response = audio.transcriptions(transcriptions); System.out.println(response.getText());*/
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/listener/AbstractStreamListener.java
AbstractStreamListener
onEvent
class AbstractStreamListener extends EventSourceListener { protected String lastMessage = ""; /** * Called when all new message are received. * * @param message the new message */ @Setter @Getter protected Consumer<String> onComplate = s -> { }; /** * Called when a new message is received. * 收到消息 单个字 * * @param message the new message */ public abstract void onMsg(String message); /** * Called when an error occurs. * 出错时调用 * * @param throwable the throwable that caused the error * @param response the response associated with the error, if any */ public abstract void onError(Throwable throwable, String response); @Override public void onOpen(EventSource eventSource, Response response) { // do nothing } @Override public void onClosed(EventSource eventSource) { // do nothing } @Override public void onEvent(EventSource eventSource, String id, String type, String data) {<FILL_FUNCTION_BODY>} @SneakyThrows @Override public void onFailure(EventSource eventSource, Throwable throwable, Response response) { try { log.error("Stream connection error: {}", throwable); String responseText = ""; if (Objects.nonNull(response)) { responseText = response.body().string(); } log.error("response:{}", responseText); String forbiddenText = "Your access was terminated due to violation of our policies"; if (StrUtil.contains(responseText, forbiddenText)) { log.error("Chat session has been terminated due to policy violation"); log.error("检测到号被封了"); } String overloadedText = "That model is currently overloaded with other requests."; if (StrUtil.contains(responseText, overloadedText)) { log.error("检测到官方超载了,赶紧优化你的代码,做重试吧"); } this.onError(throwable, responseText); } catch (Exception e) { log.warn("onFailure error:{}", e); // do nothing } finally { eventSource.cancel(); } } }
if (data.equals("[DONE]")) { onComplate.accept(lastMessage); return; } ChatCompletionResponse response = JSON.parseObject(data, ChatCompletionResponse.class); // 读取Json List<ChatChoice> choices = response.getChoices(); if (choices == null || choices.isEmpty()) { return; } Message delta = choices.get(0).getDelta(); String text = delta.getContent(); if (text != null) { lastMessage += text; onMsg(text); }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/ChatContextHolder.java
ChatContextHolder
add
class ChatContextHolder { private static Map<String, List<Message>> context = new HashMap<>(); /** * 获取对话历史 * * @param id * @return */ public static List<Message> get(String id) { List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } return messages; } /** * 添加对话 * * @param id * @return */ public static void add(String id, String msg) { Message message = Message.builder().content(msg).build(); add(id, message); } /** * 添加对话 * * @param id * @return */ public static void add(String id, Message message) {<FILL_FUNCTION_BODY>} /** * 清除对话 * @param id */ public static void remove(String id) { context.remove(id); } }
List<Message> messages = context.get(id); if (messages == null) { messages = new ArrayList<>(); context.put(id, messages); } messages.add(message);
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/SseHelper.java
SseHelper
complete
class SseHelper { public void complete(SseEmitter sseEmitter) {<FILL_FUNCTION_BODY>} public void send(SseEmitter sseEmitter, Object data) { try { sseEmitter.send(data); } catch (Exception e) { } } }
try { sseEmitter.complete(); } catch (Exception e) { }
PlexPt_chatgpt-java
chatgpt-java/src/main/java/com/plexpt/chatgpt/util/TokensUtil.java
TokensUtil
tokens
class TokensUtil { private static final Map<String, Encoding> modelEncodingMap = new HashMap<>(); private static final EncodingRegistry encodingRegistry = Encodings.newDefaultEncodingRegistry(); static { for (ChatCompletion.Model model : ChatCompletion.Model.values()) { Optional<Encoding> encodingForModel = encodingRegistry.getEncodingForModel(model.getName()); encodingForModel.ifPresent(encoding -> modelEncodingMap.put(model.getName(), encoding)); } } /** * 计算tokens * @param modelName 模型名称 * @param messages 消息列表 * @return 计算出的tokens数量 */ public static int tokens(String modelName, List<Message> messages) {<FILL_FUNCTION_BODY>} }
Encoding encoding = modelEncodingMap.get(modelName); if (encoding == null) { throw new IllegalArgumentException("Unsupported model: " + modelName); } int tokensPerMessage = 0; int tokensPerName = 0; if (modelName.startsWith("gpt-4")) { tokensPerMessage = 3; tokensPerName = 1; } else if (modelName.startsWith("gpt-3.5-turbo")) { tokensPerMessage = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n tokensPerName = -1; // if there's a name, the role is omitted } int sum = 0; for (Message message : messages) { sum += tokensPerMessage; sum += encoding.countTokens(message.getContent()); sum += encoding.countTokens(message.getRole()); if (StrUtil.isNotBlank(message.getName())) { sum += encoding.countTokens(message.getName()); sum += tokensPerName; } } sum += 3; return sum;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/config/AliPayConfig.java
AliPayConfig
check
class AliPayConfig extends PayConfig { /** * appId */ private String appId; /** * 商户私钥 */ private String privateKey; /** * 支付宝公钥 */ private String aliPayPublicKey; public void check() {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(appId, "config param 'appId' is null."); Objects.requireNonNull(privateKey, "config param 'privateKey' is null."); Objects.requireNonNull(aliPayPublicKey, "config param 'aliPayPublicKey' is null."); if (appId.length() > 32) { throw new IllegalArgumentException("config param 'appId' is incorrect: size exceeds 32."); }
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/config/PayConfig.java
PayConfig
check
class PayConfig { /** * 支付完成后的异步通知地址. */ private String notifyUrl; /** * 支付完成后的同步返回地址. */ private String returnUrl; /** * 默认非沙箱测试 */ private boolean sandbox = false; public boolean isSandbox() { return sandbox; } public void setSandbox(boolean sandbox) { this.sandbox = sandbox; } public String getNotifyUrl() { return notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public void check() {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(notifyUrl, "config param 'notifyUrl' is null."); if (!notifyUrl.startsWith("http") && !notifyUrl.startsWith("https")) { throw new IllegalArgumentException("config param 'notifyUrl' does not start with http/https."); } if (notifyUrl.length() > 256) { throw new IllegalArgumentException("config param 'notifyUrl' is incorrect: size exceeds 256."); } if (returnUrl != null) { if (!returnUrl.startsWith("http") && !returnUrl.startsWith("https")) { throw new IllegalArgumentException("config param 'returnUrl' does not start with http/https."); } if (returnUrl.length() > 256) { throw new IllegalArgumentException("config param 'returnUrl' is incorrect: size exceeds 256."); } }
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/config/WxPayConfig.java
WxPayConfig
initSSLContext
class WxPayConfig extends PayConfig { /** * 公众号appId */ private String appId; /** * 公众号appSecret */ private String appSecret; /** * 小程序appId */ private String miniAppId; /** * app应用appid */ private String appAppId; /** * 商户号 */ private String mchId; /** * 商户密钥 */ private String mchKey; /** * 商户证书路径 */ private String keyPath; /** * 证书内容 */ private SSLContext sslContext; /** * 初始化证书 * @return */ public SSLContext initSSLContext() {<FILL_FUNCTION_BODY>} }
FileInputStream inputStream = null; try { inputStream = new FileInputStream(new File(this.keyPath)); } catch (IOException e) { throw new RuntimeException("读取微信商户证书文件出错", e); } try { KeyStore keystore = KeyStore.getInstance("PKCS12"); char[] partnerId2charArray = mchId.toCharArray(); keystore.load(inputStream, partnerId2charArray); this.sslContext = SSLContexts.custom().loadKeyMaterial(keystore, partnerId2charArray).build(); return this.sslContext; } catch (Exception e) { throw new RuntimeException("证书文件有问题,请核实!", e); } finally { IOUtils.closeQuietly(inputStream); }
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/BestPayServiceImpl.java
BestPayServiceImpl
payBank
class BestPayServiceImpl implements BestPayService { /** * TODO 重构 * 暂时先再引入一个config */ private WxPayConfig wxPayConfig; private AliPayConfig aliPayConfig; public void setWxPayConfig(WxPayConfig wxPayConfig) { this.wxPayConfig = wxPayConfig; } public void setAliPayConfig(AliPayConfig aliPayConfig) { this.aliPayConfig = aliPayConfig; } @Override public PayResponse pay(PayRequest request) { Objects.requireNonNull(request, "request params must not be null"); //微信支付 if (BestPayPlatformEnum.WX == request.getPayTypeEnum().getPlatform()) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.pay(request); } // 支付宝支付 else if (BestPayPlatformEnum.ALIPAY == request.getPayTypeEnum().getPlatform()) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(aliPayConfig); return aliPayService.pay(request); } throw new RuntimeException("错误的支付方式"); } /** * 同步返回 * * @param request * @return */ @Override public PayResponse syncNotify(HttpServletRequest request) { return null; } @Override public boolean verify(Map<String, String> toBeVerifiedParamMap, SignType signType, String sign) { return false; } /** * 异步回调 * * @return */ @Override public PayResponse asyncNotify(String notifyData) { //<xml>开头的是微信通知 if (notifyData.startsWith("<xml>")) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.asyncNotify(notifyData); } else { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(aliPayConfig); return aliPayService.asyncNotify(notifyData); } } @Override public RefundResponse refund(RefundRequest request) { if (request.getPayPlatformEnum() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.refund(request); } else if (request.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.refund(request); } throw new RuntimeException("错误的支付平台"); } /** * 查询订单 * * @param request * @return */ @Override public OrderQueryResponse query(OrderQueryRequest request) { if (request.getPlatformEnum() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.query(request); } else if (request.getPlatformEnum() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.query(request); } throw new RuntimeException("错误的支付平台"); } @Override public String downloadBill(DownloadBillRequest request) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.downloadBill(request); } @Override public String getQrCodeUrl(String productId) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.getQrCodeUrl(productId); } @Override public CloseResponse close(CloseRequest request) { if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.close(request); } throw new RuntimeException("尚未支持该种支付方式"); } @Override public PayBankResponse payBank(PayBankRequest request) {<FILL_FUNCTION_BODY>} }
if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.WX) { WxPayServiceImpl wxPayService = new WxPayServiceImpl(); wxPayService.setWxPayConfig(this.wxPayConfig); return wxPayService.payBank(request); } else if (request.getPayTypeEnum().getPlatform() == BestPayPlatformEnum.ALIPAY) { AliPayServiceImpl aliPayService = new AliPayServiceImpl(); aliPayService.setAliPayConfig(this.aliPayConfig); return aliPayService.payBank(request); } throw new RuntimeException("尚未支持该种支付方式");
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxEncryptAndDecryptServiceImpl.java
WxEncryptAndDecryptServiceImpl
decrypt
class WxEncryptAndDecryptServiceImpl extends AbstractEncryptAndDecryptServiceImpl { /** * 密钥算法 */ private static final String ALGORITHM = "AES"; /** * 加解密算法/工作模式/填充方式 */ private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding"; /** * 加密 * * @param key * @param data * @return */ @Override public Object encrypt(String key, String data) { return super.encrypt(key, data); } /** * 解密 * https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_16#menu1 * * @param key * @param data * @return */ @Override public Object decrypt(String key, String data) {<FILL_FUNCTION_BODY>} }
Security.addProvider(new BouncyCastleProvider()); SecretKeySpec aesKey = new SecretKeySpec(DigestUtils.md5Hex(key).toLowerCase().getBytes(), ALGORITHM); Cipher cipher = null; try { cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } try { cipher.init(Cipher.DECRYPT_MODE, aesKey); } catch (InvalidKeyException e) { e.printStackTrace(); } try { return new String(cipher.doFinal(Base64.getDecoder().decode(data))); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } return null;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxPaySandboxKey.java
WxPaySandboxKey
get
class WxPaySandboxKey { public void get(String mchId, String mchKey) {<FILL_FUNCTION_BODY>} @Data @Root(name = "xml") static class SandboxParam { @Element(name = "mch_id") private String mchId; @Element(name = "nonce_str") private String nonceStr; @Element(name = "sign") private String sign; public Map<String, String> buildMap() { Map<String, String> map = new HashMap<>(); map.put("mch_id", this.mchId); map.put("nonce_str", this.nonceStr); return map; } } }
Retrofit retrofit = new Retrofit.Builder() .baseUrl(WxPayConstants.WXPAY_GATEWAY) .addConverterFactory(SimpleXmlConverterFactory.create()) .build(); SandboxParam sandboxParam = new SandboxParam(); sandboxParam.setMchId(mchId); sandboxParam.setNonceStr(RandomUtil.getRandomStr()); sandboxParam.setSign(WxPaySignature.sign(sandboxParam.buildMap(), mchKey)); String xml = XmlUtil.toString(sandboxParam); RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml); Call<WxPaySandboxKeyResponse> call = retrofit.create(WxPayApi.class).getsignkey(body); Response<WxPaySandboxKeyResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【微信统一支付】发起支付,网络异常," + retrofitResponse); } Object response = retrofitResponse.body(); log.info("【获取微信沙箱密钥】response={}", JsonUtil.toJson(response));
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/WxPaySignature.java
WxPaySignature
sign
class WxPaySignature { /** * 签名 * @param params * @param signKey * @return */ public static String sign(Map<String, String> params, String signKey) {<FILL_FUNCTION_BODY>} /** * 签名for App * https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2 * @param params * @param signKey * @return */ public static String signForApp(Map<String, String> params, String signKey) { SortedMap<String, String> sortedMap = new TreeMap<>(params); StringBuilder toSign = new StringBuilder(); for (String key : sortedMap.keySet()) { String value = params.get(key); if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) { toSign.append(key.toLowerCase()).append("=").append(value).append("&"); } } toSign.append("key=").append(signKey); return DigestUtils.md5Hex(toSign.toString()).toUpperCase(); } /** * 校验签名 * @param params * @param privateKey * @return */ public static Boolean verify(Map<String, String> params, String privateKey) { String sign = sign(params, privateKey); return sign.equals(params.get("sign")); } }
SortedMap<String, String> sortedMap = new TreeMap<>(params); StringBuilder toSign = new StringBuilder(); for (String key : sortedMap.keySet()) { String value = params.get(key); if (StringUtils.isNotEmpty(value) && !"sign".equals(key) && !"key".equals(key)) { toSign.append(key).append("=").append(value).append("&"); } } toSign.append("key=").append(signKey); return DigestUtils.md5Hex(toSign.toString()).toUpperCase();
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayAppServiceImpl.java
AlipayAppServiceImpl
pay
class AlipayAppServiceImpl extends AliPayServiceImpl { private final Retrofit retrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .followRedirects(false) //禁制OkHttp的重定向操作,我们自己处理重定向 .followSslRedirects(false) .build() ) .build(); private final Retrofit devRetrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest(); aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_APP_PAY); aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId()); aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter)); aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl()); AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent(); bizContent.setOutTradeNo(request.getOrderId()); bizContent.setTotalAmount(request.getOrderAmount()); bizContent.setSubject(request.getOrderName()); bizContent.setPassbackParams(request.getAttach()); aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", "")); String sign = AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey()); aliPayOrderQueryRequest.setSign(URLEncoder.encode(sign)); Map<String, String> stringStringMap = MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest); String body = MapUtil.toUrl(stringStringMap); PayResponse payResponse = new PayResponse(); payResponse.setBody(body); return payResponse;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayBarCodeServiceImpl.java
AlipayBarCodeServiceImpl
pay
class AlipayBarCodeServiceImpl extends AliPayServiceImpl { private final Retrofit retrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); private final Retrofit devRetrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest(); aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_BARCODE_PAY); aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId()); aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter)); aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl()); AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent(); bizContent.setOutTradeNo(request.getOrderId()); bizContent.setTotalAmount(request.getOrderAmount()); bizContent.setSubject(request.getOrderName()); bizContent.setAuthCode(request.getAuthCode()); bizContent.setIsAsyncPay(true); aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", "")); aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey())); Call<AliPayOrderCreateResponse> call; if (aliPayConfig.isSandbox()) { call = devRetrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } else { call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } Response<AliPayOrderCreateResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.pay"); } assert retrofitResponse.body() != null; AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradePayResponse(); if (!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) { throw new RuntimeException("【支付宝创建订单】alipay.trade.pay. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg())); } PayResponse payResponse = new PayResponse(); payResponse.setOutTradeNo(response.getTradeNo()); payResponse.setOrderId(response.getOutTradeNo()); return payResponse;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayH5ServiceImpl.java
AlipayH5ServiceImpl
pay
class AlipayH5ServiceImpl extends AliPayServiceImpl { private Retrofit retrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest(); aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId()); aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter)); AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent(); bizContent.setOutTradeNo(request.getOrderId()); bizContent.setTotalAmount(request.getOrderAmount()); bizContent.setSubject(request.getOrderName()); bizContent.setBuyerLogonId(request.getBuyerLogonId()); bizContent.setBuyerId(request.getBuyerId()); bizContent.setPassbackParams(request.getAttach()); //必须传一个 if (StringUtil.isEmpty(bizContent.getBuyerId()) && StringUtil.isEmpty(bizContent.getBuyerLogonId())) { throw new RuntimeException("alipay.trade.create: buyer_logon_id 和 buyer_id不能同时为空"); } aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl()); aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*","")); aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey())); Call<AliPayOrderCreateResponse> call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); Response<AliPayOrderCreateResponse> retrofitResponse = null; try{ retrofitResponse = call.execute(); }catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.create"); } assert retrofitResponse.body() != null; AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradeCreateResponse(); if(!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) { throw new RuntimeException("【支付宝创建订单】alipay.trade.create. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg())); } PayResponse payResponse = new PayResponse(); payResponse.setOutTradeNo(response.getTradeNo()); payResponse.setOrderId(response.getOutTradeNo()); return payResponse;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/alipay/AlipayQRCodeServiceImpl.java
AlipayQRCodeServiceImpl
pay
class AlipayQRCodeServiceImpl extends AliPayServiceImpl { private final Retrofit retrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); private final Retrofit devRetrofit = new Retrofit.Builder() .baseUrl(AliPayConstants.ALIPAY_GATEWAY_OPEN_DEV) .addConverterFactory(GsonConverterFactory.create( //下划线驼峰互转 new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create() )) .client(new OkHttpClient.Builder() .addInterceptor((new HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY))) .build() ) .build(); @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
AliPayTradeCreateRequest aliPayOrderQueryRequest = new AliPayTradeCreateRequest(); aliPayOrderQueryRequest.setMethod(AliPayConstants.ALIPAY_TRADE_QRCODE_PAY); aliPayOrderQueryRequest.setAppId(aliPayConfig.getAppId()); aliPayOrderQueryRequest.setTimestamp(LocalDateTime.now().format(formatter)); aliPayOrderQueryRequest.setNotifyUrl(aliPayConfig.getNotifyUrl()); AliPayTradeCreateRequest.BizContent bizContent = new AliPayTradeCreateRequest.BizContent(); bizContent.setOutTradeNo(request.getOrderId()); bizContent.setTotalAmount(request.getOrderAmount()); bizContent.setSubject(request.getOrderName()); aliPayOrderQueryRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", "")); aliPayOrderQueryRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest), aliPayConfig.getPrivateKey())); Call<AliPayOrderCreateResponse> call; if (aliPayConfig.isSandbox()) { call = devRetrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } else { call = retrofit.create(AliPayApi.class).tradeCreate((MapUtil.object2MapWithUnderline(aliPayOrderQueryRequest))); } Response<AliPayOrderCreateResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【支付宝创建订单】网络异常. alipay.trade.precreate"); } assert retrofitResponse.body() != null; AliPayOrderCreateResponse.AlipayTradeCreateResponse response = retrofitResponse.body().getAlipayTradePrecreateResponse(); if (!response.getCode().equals(AliPayConstants.RESPONSE_CODE_SUCCESS)) { throw new RuntimeException("【支付宝创建订单】alipay.trade.precreate. code=" + response.getCode() + ", returnMsg=" + response.getMsg() + String.format("|%s|%s", response.getSubCode(), response.getSubMsg())); } PayResponse payResponse = new PayResponse(); payResponse.setOutTradeNo(response.getTradeNo()); payResponse.setOrderId(response.getOutTradeNo()); payResponse.setCodeUrl(response.getQrCode()); return payResponse;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/service/impl/wx/WxPayMicroServiceImpl.java
WxPayMicroServiceImpl
pay
class WxPayMicroServiceImpl extends WxPayServiceImpl { /** * 微信付款码支付 * 提交支付请求后微信会同步返回支付结果。 * 当返回结果为“系统错误 {@link WxPayConstants#SYSTEMERROR}”时,商户系统等待5秒后调用【查询订单API {@link WxPayServiceImpl#query(OrderQueryRequest)}】,查询支付实际交易结果; * 当返回结果为“正在支付 {@link WxPayConstants#USERPAYING}”时,商户系统可设置间隔时间(建议10秒)重新查询支付结果,直到支付成功或超时(建议30秒); * * @param request * @return */ @Override public PayResponse pay(PayRequest request) {<FILL_FUNCTION_BODY>} }
WxPayUnifiedorderRequest wxRequest = new WxPayUnifiedorderRequest(); wxRequest.setOutTradeNo(request.getOrderId()); wxRequest.setTotalFee(MoneyUtil.Yuan2Fen(request.getOrderAmount())); wxRequest.setBody(request.getOrderName()); wxRequest.setOpenid(request.getOpenid()); wxRequest.setAuthCode(request.getAuthCode()); wxRequest.setAppid(wxPayConfig.getAppId()); wxRequest.setMchId(wxPayConfig.getMchId()); wxRequest.setNonceStr(RandomUtil.getRandomStr()); wxRequest.setSpbillCreateIp(StringUtils.isEmpty(request.getSpbillCreateIp()) ? "8.8.8.8" : request.getSpbillCreateIp()); wxRequest.setAttach(request.getAttach()); wxRequest.setSign(WxPaySignature.sign(MapUtil.buildMap(wxRequest), wxPayConfig.getMchKey())); //对付款码支付无用的字段 wxRequest.setNotifyUrl(""); wxRequest.setTradeType(""); RequestBody body = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), XmlUtil.toString(wxRequest)); WxPayApi api = null; if (wxPayConfig.isSandbox()) { api = devRetrofit.create(WxPayApi.class); } else { api = retrofit.create(WxPayApi.class); } Call<WxPaySyncResponse> call = api.micropay(body); Response<WxPaySyncResponse> retrofitResponse = null; try { retrofitResponse = call.execute(); } catch (IOException e) { e.printStackTrace(); } assert retrofitResponse != null; if (!retrofitResponse.isSuccessful()) { throw new RuntimeException("【微信付款码支付】发起支付, 网络异常"); } return buildPayResponse(retrofitResponse.body());
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/CamelCaseUtil.java
CamelCaseUtil
toUnderlineName
class CamelCaseUtil { private static final char SEPARATOR = '_'; public static String toUnderlineName(String s) {<FILL_FUNCTION_BODY>} /** * 小驼峰 */ public static String toCamelCase(String s) { if (s == null) { return null; } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 大驼峰 */ public static String toCapitalizeCamelCase(String s) { if (null == s) { return null; } s = toCamelCase(s); return s.substring(0, 1).toUpperCase() + s.substring(1); } }
if (null == s) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i >= 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { if (i > 0) sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString();
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/HttpRequestUtil.java
HttpRequestUtil
post
class HttpRequestUtil { private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class); //日志记录 /** * post请求 * @param url url地址 * @param jsonParam 参数 * @return */ public static String post(String url,String jsonParam){<FILL_FUNCTION_BODY>} /** * 发送get请求 * @param url 路径 * @return */ public static String get(String url){ String responseString = null; try { DefaultHttpClient client = new DefaultHttpClient(); //发送get请求 HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); /**请求发送成功,并得到响应**/ if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { /**读取服务器返回过来的json字符串数据**/ return EntityUtils.toString(response.getEntity()); /**把json字符串转换成json对象**/ } else { logger.error("get请求提交失败:" + url); } } catch (IOException e) { logger.error("get请求提交失败:" + url, e); } return responseString; } }
//post请求返回结果 DefaultHttpClient httpClient = new DefaultHttpClient(); String jsonResult = null; HttpPost method = new HttpPost(url); try { if (null != jsonParam) { //解决中文乱码问题 StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); method.setEntity(entity); } HttpResponse result = httpClient.execute(method); url = URLDecoder.decode(url, "UTF-8"); /**请求发送成功,并得到响应**/ if (result.getStatusLine().getStatusCode() == 200) { String str = ""; try { /**读取服务器返回过来的json字符串数据**/ str = EntityUtils.toString(result.getEntity()); return str; /**把json字符串转换成json对象**/ // jsonResult = JSONObject.fromObject(str); } catch (Exception e) { logger.error("post请求提交失败:" + url, e); } } } catch (IOException e) { logger.error("post请求提交失败:" + url, e); } return jsonResult;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/JsonUtil.java
JsonUtil
toObject
class JsonUtil { private static final ObjectMapper mapper = new ObjectMapper(); private static GsonBuilder gsonBuilder = new GsonBuilder(); /** * Convert target object to json string. * * @param obj target object. * @return converted json string. */ public static String toJson(Object obj) { gsonBuilder.setPrettyPrinting(); return gsonBuilder.create().toJson(obj); } public static String toJsonWithUnderscores(Object obj) { gsonBuilder.setPrettyPrinting(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create().toJson(obj); } /** * Convert json string to target object. * * @param json json string. * @param valueType target object class type. * @param <T> target class type. * @return converted target object. */ public static <T> T toObject(String json, Class<T> valueType) {<FILL_FUNCTION_BODY>} }
Objects.requireNonNull(json, "json is null."); Objects.requireNonNull(valueType, "value type is null."); try { return mapper.readValue(json, valueType); } catch (IOException e) { throw new IllegalStateException("fail to convert [" + json + "] to [" + valueType + "].", e); }
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/NameValuePairUtil.java
NameValuePairUtil
convert
class NameValuePairUtil { /** * 将Map转换为List<{@link NameValuePair}>. * * @param map * @return */ public static List<NameValuePair> convert(Map<String, String> map) {<FILL_FUNCTION_BODY>} }
List<NameValuePair> nameValuePairs = new ArrayList<>(); map.forEach((key, value) -> { nameValuePairs.add(new BasicNameValuePair(key, value)); }); return nameValuePairs;
Pay-Group_best-pay-sdk
best-pay-sdk/src/main/java/com/lly835/bestpay/utils/RandomUtil.java
RandomUtil
getRandomStr
class RandomUtil { private static final String RANDOM_STR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final java.util.Random RANDOM = new java.util.Random(); public static String getRandomStr() {<FILL_FUNCTION_BODY>} }
StringBuilder sb = new StringBuilder(); for (int i = 0; i < 16; i++) { sb.append(RANDOM_STR.charAt(RANDOM.nextInt(RANDOM_STR.length()))); } return sb.toString();