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

io.camunda.operate.util.MapPath Maven / Gradle / Ivy

There is a newer version: 8.6.0-alpha5
Show newest version
/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
 * one or more contributor license agreements. See the NOTICE file distributed
 * with this work for additional information regarding copyright ownership.
 * Licensed under the Camunda License 1.0. You may not use this file
 * except in compliance with the Camunda License 1.0.
 */
package io.camunda.operate.util;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

/**
 * MapPath enables retrieving values from a Map recursive tree-like data structure
 * by path
 */
public class MapPath {
  private final Map map;

  public MapPath(Map map) {
    this.map = map;
  }

  public static MapPath from(Map map) {
    return new MapPath(map);
  }

  public Optional getByPath(String... path) {
    return getByPath(Arrays.asList(path));
  }

  public Optional getByPath(List path) {
    final Supplier pathHead = () -> path.get(0);
    final Supplier> pathTail = () -> path.subList(1, path.size());
    final Supplier headItem = () -> map.get(pathHead.get());

    return switch (path.size()) {
      case 0 -> Optional.empty();
      case 1 -> Optional.ofNullable(headItem.get()).map(Convertable::from);
      default ->
          Convertable.from(headItem.get())
              .>to()
              .flatMap(map -> MapPath.from(map).getByPath(pathTail.get()));
    };
  }
}