• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

knowledgepixels / nanopub-registry / 20441087941

22 Dec 2025 06:51PM UTC coverage: 1.591% (+0.04%) from 1.554%
20441087941

push

github

ashleycaselli
refactor(exceptions): replace RuntimeExceptions with custom exception classes

6 of 592 branches covered (1.01%)

Branch coverage included in aggregate %.

32 of 1797 relevant lines covered (1.78%)

0.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.47
src/main/java/com/knowledgepixels/registry/Utils.java
1
package com.knowledgepixels.registry;
2

3
import com.github.jsonldjava.shaded.com.google.common.base.Charsets;
4
import com.github.jsonldjava.shaded.com.google.common.reflect.TypeToken;
5
import com.google.common.hash.Hashing;
6
import com.google.gson.Gson;
7
import com.google.gson.JsonIOException;
8
import com.google.gson.JsonSyntaxException;
9
import com.mongodb.client.ClientSession;
10
import io.vertx.ext.web.RoutingContext;
11
import net.trustyuri.TrustyUriUtils;
12
import org.apache.commons.lang.StringUtils;
13
import org.commonjava.mimeparse.MIMEParse;
14
import org.eclipse.rdf4j.common.exception.RDF4JException;
15
import org.eclipse.rdf4j.model.IRI;
16
import org.eclipse.rdf4j.model.Resource;
17
import org.eclipse.rdf4j.model.Statement;
18
import org.eclipse.rdf4j.model.ValueFactory;
19
import org.eclipse.rdf4j.model.impl.SimpleValueFactory;
20
import org.nanopub.MalformedNanopubException;
21
import org.nanopub.Nanopub;
22
import org.nanopub.NanopubImpl;
23
import org.nanopub.NanopubUtils;
24
import org.nanopub.extra.setting.NanopubSetting;
25
import org.nanopub.vocabulary.NPX;
26
import org.slf4j.Logger;
27
import org.slf4j.LoggerFactory;
28

29
import java.io.File;
30
import java.io.IOException;
31
import java.io.InputStreamReader;
32
import java.lang.reflect.Type;
33
import java.net.URI;
34
import java.net.URISyntaxException;
35
import java.net.URLEncoder;
36
import java.nio.charset.StandardCharsets;
37
import java.util.*;
38

39
public class Utils {
40

41
    private static final Logger logger = LoggerFactory.getLogger(Utils.class);
9✔
42

43
    private Utils() {
44
    }  // no instances allowed
45

46
    public static String getMimeType(RoutingContext context, String supported) {
47
        List<String> supportedList = Arrays.asList(StringUtils.split(supported, ','));
×
48
        String mimeType = supportedList.getFirst();
×
49
        try {
50
            mimeType = MIMEParse.bestMatch(supportedList, context.request().getHeader("Accept"));
×
51
        } catch (Exception ex) {
×
52
        }
×
53
        return mimeType;
×
54
    }
55

56
    public static String urlEncode(Object o) {
57
        return URLEncoder.encode((o == null ? "" : o.toString()), StandardCharsets.UTF_8);
×
58
    }
59

60
    public static String getHash(String s) {
61
        return Hashing.sha256().hashString(s, Charsets.UTF_8).toString();
18✔
62
    }
63

64
    public static Set<IRI> getInvalidatedNanopubIds(Nanopub np) {
65
        Set<IRI> l = new HashSet<IRI>();
×
66
        for (Statement st : NanopubUtils.getStatements(np)) {
×
67
            if (!(st.getObject() instanceof IRI)) continue;
×
68
            Resource s = st.getSubject();
×
69
            IRI p = st.getPredicate();
×
70
            if ((p.equals(NPX.RETRACTS) || p.equals(NPX.INVALIDATES)) || (p.equals(NPX.SUPERSEDES) && s.equals(np.getUri()))) {
×
71
                if (TrustyUriUtils.isPotentialTrustyUri(st.getObject().stringValue())) {
×
72
                    l.add((IRI) st.getObject());
×
73
                }
74
            }
75
        }
×
76
        return l;
×
77
    }
78

79
    public static String getEnv(String name, String defaultValue) {
80
        String value = System.getenv(name);
9✔
81
        if (value == null) value = defaultValue;
12!
82
        return value;
6✔
83
    }
84

85
    public static String getTypeHash(ClientSession mongoSession, Object type) {
86
        String typeHash = Utils.getHash(type.toString());
×
87
        if (type.toString().equals("$")) {
×
88
            typeHash = "$";
×
89
        } else {
90
            RegistryDB.recordHash(mongoSession, type.toString());
×
91
        }
92
        return typeHash;
×
93
    }
94

95
    public static String getAgentLabel(String agentId) {
96
        if (agentId == null || agentId.isBlank()) {
15✔
97
            throw new IllegalArgumentException("Agent ID cannot be null or blank");
15✔
98
        }
99
        agentId = agentId.replaceFirst("^https://orcid\\.org/", "orcid:");
15✔
100
        if (agentId.length() > 55) {
12!
101
            return agentId.substring(0, 50) + "...";
×
102
        }
103
        return agentId;
6✔
104
    }
105

106
    public static boolean isUnloadedStatus(String status) {
107
        if (status.equals("seen")) return true;  // only exists in "accounts_loading"?
×
108
        if (status.equals("skipped")) return true;
×
109
        return false;
×
110
    }
111

112
    public static boolean isCoreLoadedStatus(String status) {
113
        if (status.equals("visited")) return true;  // only exists in "accounts_loading"?
×
114
        if (status.equals("expanded")) return true;  // only exists in "accounts_loading"?
×
115
        if (status.equals("processed")) return true;  // only exists in "accounts_loading"?
×
116
        if (status.equals("aggregated")) return true;  // only exists in "accounts_loading"?
×
117
        if (status.equals("approved")) return true;  // only exists in "accounts_loading"?
×
118
        if (status.equals("contested")) return true;
×
119
        if (status.equals("toLoad")) return true;  // only exists in "accounts_loading"?
×
120
        if (status.equals("loaded")) return true;
×
121
        return false;
×
122
    }
123

124
    public static boolean isFullyLoadedStatus(String status) {
125
        if (status.equals("loaded")) return true;
×
126
        return false;
×
127
    }
128

129
    private static ValueFactory vf = SimpleValueFactory.getInstance();
6✔
130
    public static final IRI APPROVES_OF = vf.createIRI("http://purl.org/nanopub/x/approvesOf");
12✔
131

132
    public static final String TYPE_JSON = "application/json";
133
    public static final String TYPE_TRIG = "application/trig";
134
    public static final String TYPE_JELLY = "application/x-jelly-rdf";
135
    public static final String TYPE_JSONLD = "application/ld+json";
136
    public static final String TYPE_NQUADS = "application/n-quads";
137
    public static final String TYPE_TRIX = "application/trix";
138
    public static final String TYPE_HTML = "text/html";
139

140
    // Content types supported on a ListPage
141
    public static final String SUPPORTED_TYPES_LIST = TYPE_JSON + "," + TYPE_JELLY + "," + TYPE_HTML;
142
    // Content types supported on a NanopubPage
143
    public static final String SUPPORTED_TYPES_NANOPUB = TYPE_TRIG + "," + TYPE_JELLY + "," + TYPE_JSONLD + "," + TYPE_NQUADS + "," + TYPE_TRIX + "," + TYPE_HTML;
144

145
    private static Map<String, String> extensionTypeMap;
146

147
    public static String getType(String extension) {
148
        if (extension == null) {
×
149
            return null;
×
150
        }
151
        if (extensionTypeMap == null) {
×
152
            extensionTypeMap = new HashMap<>();
×
153
            extensionTypeMap.put("trig", TYPE_TRIG);
×
154
            extensionTypeMap.put("jelly", TYPE_JELLY);
×
155
            extensionTypeMap.put("jsonld", TYPE_JSONLD);
×
156
            extensionTypeMap.put("nq", TYPE_NQUADS);
×
157
            extensionTypeMap.put("xml", TYPE_TRIX);
×
158
            extensionTypeMap.put("html", TYPE_HTML);
×
159
            extensionTypeMap.put("json", TYPE_JSON);
×
160
        }
161
        return extensionTypeMap.get(extension);
×
162
    }
163

164
    private static List<String> peerUrls;
165

166
    public static List<String> getPeerUrls() {
167
        if (peerUrls == null) {
×
168
            String envPeerUrls = getEnv("REGISTRY_PEER_URLS", "");
×
169
            String thisRegistryUrl = getEnv("REGISTRY_SERVICE_URL", "");
×
170
            if (!envPeerUrls.isEmpty()) {
×
171
                peerUrls = new ArrayList<>();
×
172
                for (String peerUrl : envPeerUrls.split(";")) {
×
173
                    if (thisRegistryUrl.equals(peerUrl)) continue;
×
174
                    peerUrls.add(peerUrl);
×
175
                }
176
            } else {
177
                NanopubSetting setting;
178
                try {
179
                    setting = getSetting();
×
180
                } catch (MalformedNanopubException | IOException ex) {
×
181
                    logger.error("Error loading registry setting", ex);
×
182
                    throw new RuntimeException(ex);
×
183
                }
×
184
                peerUrls = new ArrayList<>();
×
185
                for (IRI iri : setting.getBootstrapServices()) {
×
186
                    String peerUrl = iri.stringValue();
×
187
                    if (thisRegistryUrl.equals(peerUrl)) continue;
×
188
                    peerUrls.add(peerUrl);
×
189
                }
×
190
            }
191
        }
192
        return peerUrls;
×
193
    }
194

195
    private static final String SETTING_FILE_PATH = Utils.getEnv("REGISTRY_SETTING_FILE", "/data/setting.trig");
12✔
196
    private static NanopubSetting settingNp;
197

198
    public static NanopubSetting getSetting() throws RDF4JException, MalformedNanopubException, IOException {
199
        if (settingNp == null) {
×
200
            settingNp = new NanopubSetting(new NanopubImpl(new File(SETTING_FILE_PATH)));
×
201
        }
202
        return settingNp;
×
203
    }
204

205
    public static String getRandomPeer() throws RDF4JException {
206
        List<String> peerUrls = getPeerUrls();
×
207
        return peerUrls.get(random.nextInt(peerUrls.size()));
×
208
    }
209

210
    private static Random random = new Random();
12✔
211

212
    public static Random getRandom() {
213
        return random;
×
214
    }
215

216
    private static Gson g = new Gson();
12✔
217
    private static Type listType = new TypeToken<List<String>>() {
21✔
218
    }.getType();
6✔
219

220
    public static List<String> retrieveListFromJsonUrl(String url) throws JsonIOException, JsonSyntaxException, IOException, URISyntaxException {
221
        return g.fromJson(new InputStreamReader(new URI(url).toURL().openStream()), listType);
×
222
    }
223

224
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc