001package io.avaje.http.api;
002
003import java.util.HashMap;
004import java.util.Map;
005
006/**
007 * A path segment that can simple like value like <code>chair</code>
008 * or contain matrix parameter values using semi-colon delimitation
009 * like <code>chair;vendor=ikea;size=small</code>.
010 * <p>
011 * Matrix parameters are optional 'qualifiers' of the path segment.
012 * </p>
013 */
014public class PathSegment {
015
016  private final String val;
017
018  private Map<String, String> matrixValues;
019
020  /**
021   * Create with a given value that may contain matrix parameters.
022   */
023  public static PathSegment of(String value) {
024    return new PathSegment(value);
025  }
026
027  /**
028   * Create with a given value that may contain matric parameters.
029   */
030  public PathSegment(String value) {
031    String[] vals = value.split(";");
032    this.val = vals[0];
033    if (vals.length > 1) {
034      matrixValues = new HashMap<>();
035      for (String val : vals) {
036        String[] keyVal = val.split("=");
037        if (keyVal.length == 2) {
038          matrixValues.put(keyVal[0], keyVal[1]);
039        }
040      }
041    }
042  }
043
044  /**
045   * Return the main segment value.
046   * <p>
047   * For "chair" this returns "chair"
048   * </p>
049   * <p>
050   * For "chair;vendor=ikea;size=small" this returns "chair"
051   * </p>
052   */
053  public String val() {
054    return val;
055  }
056
057  /**
058   * Return a metric value for the given key.
059   * <p>
060   * For example, given "chair;vendor=ikea;size=small"
061   * </p>
062   * <p>
063   * metric("vendor") returns "ikea".
064   * </p>
065   *
066   * @param key The metric key
067   * @return The metric value if supplied or null
068   */
069  public String matrix(String key) {
070    return matrixValues == null ? null : matrixValues.get(key);
071  }
072
073}