1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.mycore.mods.enrichment;
20
21 import java.io.IOException;
22 import java.net.URLEncoder;
23 import java.nio.charset.StandardCharsets;
24 import java.text.MessageFormat;
25 import java.util.Locale;
26
27 import org.apache.logging.log4j.LogManager;
28 import org.apache.logging.log4j.Logger;
29 import org.jdom2.Document;
30 import org.jdom2.Element;
31 import org.mycore.common.xml.MCRURIResolver;
32 import org.mycore.common.xml.MCRXMLHelper;
33 import org.mycore.mods.MCRMODSCommands;
34 import org.xml.sax.SAXException;
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 class MCRIdentifierResolver {
54
55 private static final Logger LOGGER = LogManager.getLogger(MCRIdentifierResolver.class);
56
57 private MCRDataSource ds;
58
59 private MCRIdentifierType idType;
60
61 private String uriPattern;
62
63 MCRIdentifierResolver(MCRDataSource ds, MCRIdentifierType idType, String uriPattern) {
64 this.ds = ds;
65 this.idType = idType;
66 this.uriPattern = uriPattern;
67 }
68
69 MCRIdentifierType getType() {
70 return idType;
71 }
72
73
74
75
76
77
78
79 Element resolve(String identifier) {
80 Object[] params = new Object[] { identifier, URLEncoder.encode(identifier, StandardCharsets.UTF_8) };
81 String uri = new MessageFormat(uriPattern, Locale.ROOT).format(params);
82
83 Element resolved = null;
84 try {
85 resolved = MCRURIResolver.instance().resolve(uri);
86 } catch (Exception ex) {
87 LOGGER.warn("Exception resolving " + uri, ex);
88 return null;
89 }
90
91
92 if (resolved == null || !"mods".equals(resolved.getName()) || resolved.getChildren().isEmpty()) {
93 LOGGER.warn(ds + " returned none or empty MODS for " + idType + " " + identifier);
94 return null;
95 }
96
97 try {
98 ensureIsValidMODS(resolved);
99 return resolved;
100 } catch (Exception ex) {
101 LOGGER.warn(ds + " returned invalid MODS for " + identifier + ": " + ex.getMessage(), ex);
102 return null;
103 }
104 }
105
106 void ensureIsValidMODS(Element mods) throws SAXException, IOException {
107 MCRXMLHelper.validate(new Document().addContent(mods.detach()), MCRMODSCommands.MODS_V3_XSD_URI);
108 }
109 }