1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package gov.nist.secauto.metaschema.core.metapath.item;
7   
8   import gov.nist.secauto.metaschema.core.metapath.item.node.INodeItem;
9   import gov.nist.secauto.metaschema.core.metapath.type.TypeMetapathException;
10  
11  import edu.umd.cs.findbugs.annotations.NonNull;
12  import edu.umd.cs.findbugs.annotations.Nullable;
13  
14  /**
15   * Provides a variety of utilities for working with Metapath items.
16   */
17  public final class ItemUtils {
18  
19    private ItemUtils() {
20      // disable construction
21    }
22  
23    /**
24     * Checks that the item is a node item.
25     *
26     * @param item
27     *          the item to check
28     * @return the item cast to a {@link INodeItem}
29     * @throws TypeMetapathException
30     *           if the item is {@code null} or not an {@link INodeItem}
31     */
32    // FIXME: make this a method on the type implementation
33    @NonNull
34    public static INodeItem checkItemIsNodeItemForStep(@Nullable IItem item) {
35      if (item instanceof INodeItem) {
36        return (INodeItem) item;
37      }
38      if (item == null) {
39        throw new TypeMetapathException(TypeMetapathException.NOT_A_NODE_ITEM_FOR_STEP,
40            "Item is null.");
41      }
42      throw new TypeMetapathException(TypeMetapathException.NOT_A_NODE_ITEM_FOR_STEP,
43          String.format(
44              "The item of type '%s' is not a INodeItem.",
45              item.getClass().getName()));
46    }
47  
48    /**
49     * Check that the item is the type specified by {@code clazz}.
50     *
51     * @param <TYPE>
52     *          the Java type the item is required to match
53     * @param item
54     *          the item to check
55     * @param clazz
56     *          the Java class to check the item against
57     * @return the item cast to the required class value
58     * @throws TypeMetapathException
59     *           if the item is {@code null} or does not match the type specified by
60     *           {@code clazz}
61     */
62    // FIXME: make this a method on the type implementation
63    @SuppressWarnings("unchecked")
64    @NonNull
65    public static <TYPE> TYPE checkItemType(@NonNull IItem item, @NonNull Class<TYPE> clazz) {
66      if (clazz.isInstance(item)) {
67        return (TYPE) item;
68      }
69      throw new TypeMetapathException(TypeMetapathException.INVALID_TYPE_ERROR,
70          String.format(
71              "The item of type '%s' is not the required type '%s'.",
72              item.getClass().getName(),
73              clazz.getName()));
74    }
75  }