Debian Codegraph @

net/sf/saxon/functions/OptionsParameter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8
9 package net.sf.saxon.functions;
10
11 import net.sf.saxon.expr.XPathContext;
12 import net.sf.saxon.expr.parser.ExplicitLocation;
13 import net.sf.saxon.expr.parser.RoleDiagnostic;
14 import net.sf.saxon.lib.ConversionRules;
15 import net.sf.saxon.ma.map.MapItem;
16 import net.sf.saxon.om.Sequence;
17 import net.sf.saxon.om.StructuredQName;
18 import net.sf.saxon.trans.Err;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.type.AtomicType;
21 import net.sf.saxon.type.BuiltInAtomicType;
22 import net.sf.saxon.type.Converter;
23 import net.sf.saxon.type.TypeHierarchy;
24 import net.sf.saxon.value.AtomicValue;
25 import net.sf.saxon.value.QNameValue;
26 import net.sf.saxon.value.SequenceType;
27 import net.sf.saxon.value.StringValue;
28
29 import java.util.*;
30
31 /**
32 * This class implements the rules for options parameters, as used in functions such as parse-json, serialize,
33 * json-to-XML, map:merge. It provides a convenient way of ensuring that the options parameter conventions
34 * are enforced.
35 */
36 public class OptionsParameter {
37
38 private Map<String, SequenceType> allowedOptions = new HashMap<>(8);
39 private Map<String, Sequence<?>> defaultValues = new HashMap<>(8);
40 private Set<String> requiredOptions = new HashSet<>(4);
41 private Map<String, Set<String>> allowedValues = new HashMap<>(8);
42 private String errorCodeForDisallowedValue;
43 private String errorCodeForAbsentValue = "SXJE9999";
44 private boolean allowCastFromString = false;
45
46 public OptionsParameter() {}
47
48 /**
49 * Register a permitted option keyword, and the associated type of value, without defining
50 * a default value
51 * @param name the option keyword
52 * @param type the required type
53 */
54 public void addAllowedOption(String name, SequenceType type) {
55 allowedOptions.put(name, type);
56 }
57
58 /**
59 * Register a required option keyword, and the associated type of value, where omitting
60 * the value is an error
61 *
62 * @param name the option keyword
63 * @param type the required type
64 */
65 public void addRequiredOption(String name, SequenceType type) {
66 allowedOptions.put(name, type);
67 requiredOptions.add(name);
68 }
69
70 /**
71 * Register a permitted option keyword, and the associated type of value, with a default value
72 *
73 * @param name the option keyword
74 * @param type the required type
75 * @param defaultValue the default value if the option is not specified; or null
76 * if no default is defined
77 */
78 public void addAllowedOption(String name, SequenceType type, Sequence<?> defaultValue) {
79 allowedOptions.put(name, type);
80 if (defaultValue != null) {
81 defaultValues.put(name, defaultValue);
82 }
83 }
84
85 /**
86 * Enumerate the permitted values for an option keyword
87 * @param name the option keyword
88 * @param errorCode the error to be reported if the supplied value is not one of those permitted
89 * @param values the permitted values
90 */
91
92 public void setAllowedValues(String name, String errorCode, String... values) {
93 HashSet<String> valueSet = new HashSet<>(Arrays.asList(values));
94 allowedValues.put(name, valueSet);
95 errorCodeForDisallowedValue = errorCode;
96 }
97
98 /**
99 * Process an XPath map containing the supplied values. Options that are recognized are copied
100 * into the result map, after validation and expansion of defaults. Unrecognized options are
101 * ignored, in accordance with the option parameter conventions
102 * @param supplied the supplied options as an XPath map object
103 * @param context the dynamic evaluation context
104 * @return the validated options as a Java map
105 * @throws XPathException if any supplied options are invalid
106 */
107
108 public Map<String, Sequence<?>> processSuppliedOptions(MapItem supplied, XPathContext context) throws XPathException {
109 Map<String, Sequence<?>> result = new HashMap<>();
110 TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
111
112 for (String req : requiredOptions) {
113 if (supplied.get(new StringValue(req)) == null) {
114 throw new XPathException("No value supplied for required option: " + req, errorCodeForAbsentValue);
115 }
116 }
117
118 for (Map.Entry<String, SequenceType> allowed : allowedOptions.entrySet()) {
119 String nominalKey = allowed.getKey();
120 AtomicValue actualKey;
121 if (nominalKey.startsWith("Q{")) {
122 actualKey = new QNameValue(StructuredQName.fromEQName(nominalKey), BuiltInAtomicType.QNAME);
123 } else {
124 actualKey = new StringValue(nominalKey);
125 }
126 SequenceType required = allowed.getValue();
127 Sequence<?> actual = supplied.get(actualKey);
128 if (actual != null) {
129 if (!required.matches(actual, th)) {
130 boolean ok = false;
131 if (actual instanceof StringValue && allowCastFromString
132 && required.getPrimaryType() instanceof AtomicType) {
133 try {ConversionRules rules = context.getConfiguration().getConversionRules();
134 actual = Converter.convert((StringValue)actual, (AtomicType)required.getPrimaryType(), rules);
135 ok = true;
136 } catch (XPathException err) {
137 ok = false;
138 }
139 }
140 if (!ok) {
141 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.OPTION, nominalKey, 0);
142 role.setErrorCode("XPTY0004");
143 actual = th.applyFunctionConversionRules(
144 actual, required, role, ExplicitLocation.UNKNOWN_LOCATION);
145 }
146 }
147 actual = actual.materialize();
148 Set<String> permitted = allowedValues.get(nominalKey);
149 if (permitted != null) {
150 if (!(actual instanceof AtomicValue) || !permitted.contains(((AtomicValue)actual).getStringValue())) {
151 StringBuilder message = new StringBuilder("Invalid option " + nominalKey + "=" + Err.depictSequence(actual) + ". Valid values are:");
152 int i = 0;
153 for (String v : permitted) {
154 message.append(i++ == 0 ? " " : ", ").append(v);
155 }
156 throw new XPathException(message.toString(), errorCodeForDisallowedValue);
157 }
158 }
159 result.put(nominalKey, actual);
160 } else {
161 Sequence<?> def = defaultValues.get(nominalKey);
162 if (def != null) {
163 result.put(nominalKey, def);
164 }
165 }
166 }
167
168 return result;
169
170 }
171
172 /**
173 * Get a Java map containing the default values of registered options
174 * @return a map containing the default values
175 */
176
177 public Map<String, Sequence<?>> getDefaultOptions() {
178 Map<String, Sequence<?>> result = new HashMap<>();
179 for (Map.Entry<String, Sequence<?>> entry : defaultValues.entrySet()) {
180 result.put(entry.getKey(), entry.getValue());
181 }
182 return result;
183 }
184
185 /**
186 * Get the error code to be used when a required option is not supplied
187 * @return the local part of the error code to be used
188 */
189
190 public String getErrorCodeForAbsentValue() {
191 return errorCodeForAbsentValue;
192 }
193
194 /**
195 * Set the error code to be used when a required option is not supplied
196 * @param errorCodeForAbsentValue the local part of the error code to be used
197 */
198
199 public void setErrorCodeForAbsentValue(String errorCodeForAbsentValue) {
200 this.errorCodeForAbsentValue = errorCodeForAbsentValue;
201 }
202
203 /**
204 * Ask whether it is is permissible to supply the value as a string, which is cast to the
205 * required type, rather than supplying the required type directly. Normally false.
206 * @return true if is is permitted to supply the value as a string
207 */
208
209 public boolean isAllowCastFromString() {
210 return allowCastFromString;
211 }
212
213 /**
214 * Say whether it is is permissible to supply the value as a string, which is cast to the
215 * required type, rather than supplying the required type directly. Normally false.
216 * @param allowCastFromString true if is is permitted to supply the value as a string
217 */
218
219 public void setAllowCastFromString(boolean allowCastFromString) {
220 this.allowCastFromString = allowCastFromString;
221 }
222
223
224 }
225