001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.plugins.streetside.utils.api;
003
004import java.text.ParseException;
005import java.text.SimpleDateFormat;
006import java.util.Collection;
007import java.util.HashSet;
008import java.util.Locale;
009import java.util.function.Function;
010
011import javax.json.JsonArray;
012import javax.json.JsonNumber;
013import javax.json.JsonObject;
014import javax.json.JsonValue;
015
016import org.openstreetmap.josm.data.coor.LatLon;
017import org.openstreetmap.josm.tools.Logging;
018
019public final class JsonStreetsideDecoder {
020  private JsonStreetsideDecoder() {
021    // Private constructor to avoid instantiation
022  }
023
024  /**
025   * Parses a given {@link JsonObject} as a GeoJSON FeatureCollection into a {@link Collection}
026   * of the desired Java objects. The method, which converts the GeoJSON features into Java objects
027   * is given as a parameter to this method.
028   * @param <T> feature type
029   * @param json the {@link JsonObject} to be parsed
030   * @param featureDecoder feature decoder which transforms JSON objects to Java objects
031   * @return a {@link Collection} which is parsed from the given {@link JsonObject}, which contains GeoJSON.
032   *         Currently a {@link HashSet} is used, but please don't rely on it, this could change at any time without
033   *         prior notice. The return value will not be <code>null</code>.
034   */
035  public static <T> Collection<T> decodeFeatureCollection(final JsonObject json, Function<JsonObject, T> featureDecoder) {
036    final Collection<T> result = new HashSet<>();
037    if (
038      json != null && "FeatureCollection".equals(json.getString("type", null)) && json.containsKey("features")
039    ) {
040      final JsonValue features = json.get("features");
041      for (int i = 0; features instanceof JsonArray && i < ((JsonArray) features).size(); i++) {
042        final JsonValue val = ((JsonArray) features).get(i);
043        if (val instanceof JsonObject) {
044          final T feature = featureDecoder.apply((JsonObject) val);
045          if (feature != null) {
046            result.add(feature);
047          }
048        }
049      }
050    }
051    return result;
052  }
053
054  /**
055   * Decodes a {@link JsonArray} of exactly size 2 to a {@link LatLon} instance.
056   * The first value in the {@link JsonArray} is treated as longitude, the second one as latitude.
057   * @param json the {@link JsonArray} containing the two numbers
058   * @return the decoded {@link LatLon} instance, or <code>null</code> if the parameter is
059   *         not a {@link JsonArray} of exactly size 2 containing two {@link JsonNumber}s.
060   */
061  static LatLon decodeLatLon(final JsonArray json) {
062    final double[] result = decodeDoublePair(json);
063    if (result != null) {
064      return new LatLon(result[1], result[0]);
065    }
066    return null;
067  }
068
069  /**
070   * Decodes a pair of double values, which are stored in a {@link JsonArray} of exactly size 2.
071   * @param json the {@link JsonArray} containing the two values
072   * @return a double array which contains the two values in the same order, or <code>null</code>
073   *         if the parameter was not a {@link JsonArray} of exactly size 2 containing two {@link JsonNumber}s
074   */
075  @SuppressWarnings("PMD.ReturnEmptyArrayRatherThanNull")
076  static double[] decodeDoublePair(final JsonArray json) {
077    if (
078      json != null &&
079      json.size() == 2 &&
080      json.get(0) instanceof JsonNumber &&
081      json.get(1) instanceof JsonNumber
082    ) {
083      return new double[]{json.getJsonNumber(0).doubleValue(), json.getJsonNumber(1).doubleValue()};
084    }
085    return null;
086  }
087
088  /**
089   * Decodes a timestamp formatted as a {@link String} to the equivalent UNIX epoch timestamp
090   * (number of milliseconds since 1970-01-01T00:00:00.000+0000).
091   * @param timestamp the timestamp formatted according to the format <code>yyyy-MM-dd'T'HH:mm:ss.SSSX</code>
092   * @return the point in time as a {@link Long} value representing the UNIX epoch time, or <code>null</code> if the
093   *   parameter does not match the required format (this also triggers a warning via
094   *   {@link Logging#warn(Throwable)}), or the parameter is <code>null</code>.
095   */
096  static Long decodeTimestamp(final String timestamp) {
097    if (timestamp != null) {
098      try {
099        return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.UK).parse(timestamp).getTime();
100      } catch (ParseException e) {
101        StackTraceElement calledBy = e.getStackTrace()[Math.min(e.getStackTrace().length - 1, 2)];
102        Logging.log(Logging.LEVEL_WARN,String.format(
103          "Could not decode time from the timestamp `%s` (called by %s.%s:%d)",
104          timestamp, calledBy.getClassName(), calledBy.getMethodName(), calledBy.getLineNumber()
105        ), e);
106      }
107    }
108    return null;
109  }
110}