|
| 1 | +package edu.kit.datamanager.ro_crate.util; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.JsonNode; |
| 4 | + |
| 5 | +import java.util.stream.StreamSupport; |
| 6 | + |
| 7 | +/** |
| 8 | + * Utility class for handling operations on RO-Crate graphs. |
| 9 | + * Provides methods to find entities by ID or type within a graph. |
| 10 | + * <p> |
| 11 | + * {@see JsonUtilFunctions}. |
| 12 | + */ |
| 13 | +public class Graph { |
| 14 | + /** |
| 15 | + * Finds an entity in the graph by its ID. |
| 16 | + * |
| 17 | + * @param graph The JSON node representing the graph. |
| 18 | + * @param id The ID of the entity to find. |
| 19 | + * @return The entity as a JsonNode if found, null otherwise. |
| 20 | + */ |
| 21 | + public static JsonNode findEntityById(JsonNode graph, String id) { |
| 22 | + for (JsonNode entity : graph) { |
| 23 | + if (entity.has("@id") && entity.get("@id").asText().equals(id)) { |
| 24 | + return entity; |
| 25 | + } |
| 26 | + } |
| 27 | + return null; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Finds an entity in the graph by its type. |
| 32 | + * |
| 33 | + * @param graph The JSON node representing the graph. |
| 34 | + * @param type The type of the entity to find. |
| 35 | + * @return The entity as a JsonNode if found, null otherwise. |
| 36 | + */ |
| 37 | + public static JsonNode findEntityByType(JsonNode graph, String type) { |
| 38 | + return StreamSupport.stream(graph.spliterator(), false) |
| 39 | + .filter(entity -> entity.path("@type").asText().equals(type)) |
| 40 | + .findFirst() |
| 41 | + .orElse(null); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Finds all entities in the graph by their type. |
| 46 | + * |
| 47 | + * @param graph The JSON node representing the graph. |
| 48 | + * @param type The type of the entities to find. |
| 49 | + * @return An array of JsonNode containing all entities of the specified type. |
| 50 | + */ |
| 51 | + public static JsonNode[] findEntitiesByType(JsonNode graph, String type) { |
| 52 | + return StreamSupport.stream(graph.spliterator(), false) |
| 53 | + .filter(entity -> entity.path("@type").asText().equals(type)) |
| 54 | + .toArray(JsonNode[]::new); |
| 55 | + } |
| 56 | +} |
0 commit comments