Skip to content

Method: generateIdentifier(URI)

1: /*
2: * JOPA
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.ontodriver.util;
19:
20: import cz.cvut.kbss.ontodriver.model.NamedResource;
21:
22: import java.net.URI;
23: import java.net.URL;
24: import java.util.Objects;
25: import java.util.Random;
26: import java.util.Set;
27:
28: /**
29: * Utility for working with resource identifiers.
30: */
31: public class IdentifierUtils {
32:
33: public static final Set<Class<?>> IDENTIFIER_TYPES = Set.of(NamedResource.class, URI.class, URL.class);
34:
35: private static final Random RANDOM = new Random();
36:
37: private IdentifierUtils() {
38: throw new AssertionError();
39: }
40:
41: /**
42: * Generates a (pseudo) random identifier based on the specified class URI.
43: * <p>
44: * The identifier consists of the class URI and then contains the string 'instance' and a random integer to ensure
45: * uniqueness. The 'instance' part is appended after a slash or a _, if the class URI contains a hash fragment.
46: *
47: * @param classUri Class URI used as identifier base
48: * @return Generated identifier
49: */
50: public static URI generateIdentifier(URI classUri) {
51: Objects.requireNonNull(classUri);
52:• if (classUri.getFragment() != null) {
53: return URI.create(classUri + "_instance" + RANDOM.nextInt());
54: } else {
55: String base = classUri.toString();
56:• if (base.endsWith("/")) {
57: return URI.create(base + "instance" + RANDOM.nextInt());
58: } else {
59: return URI.create(base + "/instance" + RANDOM.nextInt());
60: }
61: }
62: }
63:
64: /**
65: * Checks if the specified class represents a resource identifier.
66: *
67: * @param cls Class to check
68: * @return {@code true} if instances of the specified class represent resource identifiers, {@code false} otherwise
69: * @see #IDENTIFIER_TYPES
70: */
71: public static boolean isResourceIdentifierType(Class<?> cls) {
72: return IDENTIFIER_TYPES.contains(cls);
73: }
74: }