Skip to content

Method: IdentifierUtils()

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