Debian Codegraph @

build-system/manifest-merger/src/main/java/com/android/manifmerger/AttributeModel.java

raw
1 /*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.manifmerger;
18
19 import com.android.annotations.NonNull;
20 import com.android.annotations.Nullable;
21 import com.google.common.base.Joiner;
22 import com.google.common.base.Preconditions;
23
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
26
27 /**
28 * Describes an attribute characteristics like if it supports smart package name replacement, has
29 * a default value and a validator for its values.
30 */
31 class AttributeModel {
32
33 @NonNull private final XmlNode.NodeName mName;
34 private final boolean mIsPackageDependent;
35 @Nullable private final String mDefaultValue;
36 @Nullable private final Validator mOnReadValidator;
37 @Nullable private final Validator mOnWriteValidator;
38 @NonNull private final MergingPolicy mMergingPolicy;
39
40 /**
41 * Define a new attribute with specific characteristics.
42 *
43 * @param name name of the attribute, so far assumed to be in the
44 * {@link com.android.SdkConstants#ANDROID_URI} namespace.
45 * @param isPackageDependent true if the attribute support smart substitution of package name.
46 * @param defaultValue an optional default value.
47 * @param onReadValidator an optional validator to validate values against.
48 */
49 private AttributeModel(@NonNull XmlNode.NodeName name,
50 boolean isPackageDependent,
51 @Nullable String defaultValue,
52 @Nullable Validator onReadValidator,
53 @Nullable Validator onWriteValidator,
54 @NonNull MergingPolicy mergingPolicy) {
55 mName = name;
56 mIsPackageDependent = isPackageDependent;
57 mDefaultValue = defaultValue;
58 mOnReadValidator = onReadValidator;
59 mOnWriteValidator = onWriteValidator;
60 mMergingPolicy = mergingPolicy;
61 }
62
63 @NonNull
64 XmlNode.NodeName getName() {
65 return mName;
66 }
67
68 /**
69 * Return true if the attribute support smart substitution of partially fully qualified
70 * class names with package settings as provided by the manifest node's package attribute
71 * {@link <a href=http://developer.android.com/guide/topics/manifest/manifest-element.html>}
72 *
73 * @return true if this attribute supports smart substitution or false if not.
74 */
75 boolean isPackageDependent() {
76 return mIsPackageDependent;
77 }
78
79 /**
80 * Returns the attribute's default value or null if none.
81 */
82 @Nullable
83 String getDefaultValue() {
84 return mDefaultValue;
85 }
86
87 /**
88 * Returns the attribute's {@link com.android.manifmerger.AttributeModel.Validator} to
89 * validate its value when read from xml files or null if no validation is necessary.
90 */
91 @Nullable
92 public Validator getOnReadValidator() {
93 return mOnReadValidator;
94 }
95
96 /**
97 * Returns the attribute's {@link com.android.manifmerger.AttributeModel.Validator} to
98 * validate its value when the merged file is about to be persisted.
99 */
100 @Nullable
101 public Validator getOnWriteValidator() {
102 return mOnWriteValidator;
103 }
104
105 /**
106 * Returns the {@link com.android.manifmerger.AttributeModel.MergingPolicy} for this
107 * attribute.
108 */
109 @NonNull
110 public MergingPolicy getMergingPolicy() {
111 return mMergingPolicy;
112 }
113
114 /**
115 * Creates a new {@link Builder} to describe an attribute.
116 * @param attributeName the to be described attribute name
117 */
118 @NonNull
119 static Builder newModel(String attributeName) {
120 return new Builder(attributeName);
121 }
122
123
124 static class Builder {
125
126 private final String mName;
127 private boolean mIsPackageDependent = false;
128 private String mDefaultValue;
129 private Validator mOnReadValidator;
130 private Validator mOnWriteValidator;
131 @NonNull
132 private MergingPolicy mMergingPolicy = STRICT_MERGING_POLICY;
133
134 Builder(String name) {
135 this.mName = name;
136 }
137
138 /**
139 * Sets the attribute support for smart substitution of partially fully qualified
140 * class names with package settings as provided by the manifest node's package attribute
141 * {@link <a href=http://developer.android.com/guide/topics/manifest/manifest-element.html>}
142 */
143 @NonNull
144 Builder setIsPackageDependent() {
145 mIsPackageDependent = true;
146 return this;
147 }
148
149 /**
150 * Sets the attribute default value.
151 */
152 @NonNull
153 Builder setDefaultValue(String value) {
154 mDefaultValue = value;
155 return this;
156 }
157
158 /**
159 * Sets a {@link com.android.manifmerger.AttributeModel.Validator} to validate the
160 * attribute's values coming from xml files.
161 */
162 @NonNull
163 Builder setOnReadValidator(Validator validator) {
164 mOnReadValidator = validator;
165 return this;
166 }
167
168 /**
169 * Sets a {@link com.android.manifmerger.AttributeModel.Validator} to validate values
170 * before they are written to the final merged document.
171 */
172 @NonNull
173 Builder setOnWriteValidator(Validator validator) {
174 mOnWriteValidator = validator;
175 return this;
176 }
177
178 @NonNull
179 Builder setMergingPolicy(@NonNull MergingPolicy mergingPolicy) {
180 mMergingPolicy = mergingPolicy;
181 return this;
182 }
183
184 /**
185 * Build an immutable {@link com.android.manifmerger.AttributeModel}
186 */
187 @NonNull
188 AttributeModel build() {
189 return new AttributeModel(
190 XmlNode.fromXmlName("android:" + mName),
191 mIsPackageDependent,
192 mDefaultValue,
193 mOnReadValidator,
194 mOnWriteValidator,
195 mMergingPolicy);
196 }
197 }
198
199 /**
200 * Defines a merging policy between two attribute values. Example of merging policies can be
201 * strict when it is illegal to try to merge or override a value by another. Another example
202 * is a OR merging policy on boolean attribute values.
203 */
204 interface MergingPolicy {
205
206 /**
207 * Returns true if it should be attempted to merge this attribute value with
208 * the attribute default value when merging with a node that does not contain
209 * the attribute declaration.
210 */
211 boolean shouldMergeDefaultValues();
212
213 /**
214 * Merges the two attributes values and returns the merged value. If the values cannot be
215 * merged, return null.
216 */
217 @Nullable
218 String merge(@NonNull String higherPriority, @NonNull String lowerPriority);
219 }
220
221 /**
222 * Standard attribute value merging policy, generates an error unless both values are equal.
223 */
224 @NonNull
225 static final MergingPolicy STRICT_MERGING_POLICY = new MergingPolicy() {
226
227 @Override
228 public boolean shouldMergeDefaultValues() {
229 return false;
230 }
231
232 @Nullable
233 @Override
234 public String merge(@NonNull String higherPriority, @NonNull String lowerPriority) {
235 // it's ok if the values are equal, otherwise it's not.
236 return higherPriority.equals(lowerPriority)
237 ? higherPriority
238 : null;
239 }
240 };
241
242 /**
243 * Boolean OR merging policy.
244 */
245 static final MergingPolicy OR_MERGING_POLICY = new MergingPolicy() {
246 @Override
247 public boolean shouldMergeDefaultValues() {
248 return true;
249 }
250
251 @Nullable
252 @Override
253 public String merge(@NonNull String higherPriority, @NonNull String lowerPriority) {
254 return Boolean.toString(BooleanValidator.isTrue(higherPriority) ||
255 BooleanValidator.isTrue(lowerPriority));
256 }
257 };
258
259 /**
260 * Merging policy that will return the higher priority value regardless of the lower priority
261 * value
262 */
263 static final MergingPolicy NO_MERGING_POLICY = new MergingPolicy() {
264
265 @Override
266 public boolean shouldMergeDefaultValues() {
267 return true;
268 }
269
270 @Nullable
271 @Override
272 public String merge(@NonNull String higherPriority, @NonNull String lowerPriority) {
273 return higherPriority;
274 }
275 };
276
277 /**
278 * Decode a decimal or hexadecimal {@link String} into an {@link Integer}.
279 * String starting with 0 will be considered decimal, not octal.
280 */
281 private static int decodeDecOrHexString(@NonNull String s) {
282 long decodedValue = s.startsWith("0x") || s.startsWith("0X")
283 ? Long.decode(s)
284 : Long.parseLong(s);
285 if (decodedValue < 0xFFFFFFFFL) {
286 return (int) decodedValue;
287 } else {
288 throw new IllegalArgumentException("Value " + s + " too big for 32 bits.");
289 }
290 }
291
292 /**
293 * Validates an attribute value.
294 *
295 * The validator can be called when xml documents are read to ensure the xml file contains
296 * valid statements.
297 *
298 * This is a poor-mans replacement for not having a proper XML Schema do perform such
299 * validations.
300 */
301 interface Validator {
302
303 /**
304 * Validates a value, issuing a warning or error in case of failure through the passed
305 * merging report.
306 * @param mergingReport to report validation warnings or error
307 * @param attribute the attribute to validate.
308 * @param value the proposed or existing attribute value.
309 * @return true if the value is legal for this attribute.
310 */
311 boolean validates(@NonNull MergingReport.Builder mergingReport,
312 @NonNull XmlAttribute attribute,
313 @NonNull String value);
314 }
315
316 /**
317 * Validates a boolean attribute type.
318 */
319 static class BooleanValidator implements Validator {
320
321 // TODO: check with @xav where to find the acceptable values by runtime.
322 private static final Pattern TRUE_PATTERN = Pattern.compile("true|True|TRUE");
323 private static final Pattern FALSE_PATTERN = Pattern.compile("false|False|FALSE");
324
325 private static boolean isTrue(@NonNull String value) {
326 return TRUE_PATTERN.matcher(value).matches();
327 }
328
329 @Override
330 public boolean validates(@NonNull MergingReport.Builder mergingReport,
331 @NonNull XmlAttribute attribute,
332 @NonNull String value) {
333 boolean matches = TRUE_PATTERN.matcher(value).matches() ||
334 FALSE_PATTERN.matcher(value).matches();
335 if (!matches) {
336 attribute.addMessage(mergingReport, MergingReport.Record.Severity.ERROR,
337 String.format(
338 "Attribute %1$s at %2$s has an illegal value=(%3$s), "
339 + "expected 'true' or 'false'",
340 attribute.getId(),
341 attribute.printPosition(),
342 value
343 )
344 );
345 }
346 return matches;
347 }
348 }
349
350 /**
351 * A {@link com.android.manifmerger.AttributeModel.Validator} for verifying that a proposed
352 * value is part of the acceptable list of possible values.
353 */
354 static class MultiValueValidator implements Validator {
355
356 @NonNull
357 private final String[] multiValues;
358 @NonNull
359 private final String allValues;
360
361 MultiValueValidator(@NonNull String... multiValues) {
362 this.multiValues = multiValues;
363 allValues = Joiner.on(',').join(multiValues);
364 }
365
366 @Override
367 public boolean validates(@NonNull MergingReport.Builder mergingReport,
368 @NonNull XmlAttribute attribute, @NonNull String value) {
369 for (String multiValue : multiValues) {
370 if (multiValue.equals(value)) {
371 return true;
372 }
373 }
374 attribute.addMessage(mergingReport, MergingReport.Record.Severity.ERROR,
375 String.format(
376 "Invalid value for attribute %1$s at %2$s, value=(%3$s), "
377 + "acceptable values are (%4$s)",
378 attribute.getId(),
379 attribute.printPosition(),
380 value,
381 allValues
382 )
383 );
384 return false;
385 }
386 }
387
388 /**
389 * A {@link com.android.manifmerger.AttributeModel.Validator} for verifying that a proposed
390 * value is a numerical integer value.
391 */
392 static class IntegerValueValidator implements Validator {
393
394 @Override
395 public boolean validates(@NonNull MergingReport.Builder mergingReport,
396 @NonNull XmlAttribute attribute, @NonNull String value) {
397 try {
398 return Integer.parseInt(value) > 0;
399 } catch (NumberFormatException e) {
400 attribute.addMessage(mergingReport, MergingReport.Record.Severity.ERROR,
401 String.format(
402 "Attribute %1$s at %2$s must be an integer, found %3$s",
403 attribute.getId(),
404 attribute.printPosition(),
405 value)
406 );
407 return false;
408 }
409 }
410 }
411
412 /**
413 * A {@link com.android.manifmerger.AttributeModel.Validator} to validate that a string is
414 * a valid 32 bits hexadecimal representation.
415 */
416 static class Hexadecimal32Bits implements Validator {
417 protected static final Pattern PATTERN = Pattern.compile("0[xX]([0-9a-fA-F]+)");
418
419 @Override
420 public boolean validates(@NonNull MergingReport.Builder mergingReport,
421 @NonNull XmlAttribute attribute, @NonNull String value) {
422 Matcher matcher = PATTERN.matcher(value);
423 boolean valid = matcher.matches() && matcher.group(1).length() <= 8;
424 if (!valid) {
425 attribute.addMessage(mergingReport, MergingReport.Record.Severity.ERROR,
426 String.format(
427 "Attribute %1$s at %2$s is not a valid hexadecimal 32 bit value,"
428 + " found %3$s",
429 attribute.getId(),
430 attribute.printPosition(),
431 value
432 ));
433 }
434 return valid;
435 }
436 }
437
438 /**
439 * A {@link com.android.manifmerger.AttributeModel.Validator} to validate that a string is
440 * a valid 32 positive hexadecimal representation with a minimum value requirement.
441 */
442 static class Hexadecimal32BitsWithMinimumValue extends Hexadecimal32Bits {
443
444 private final int mMinimumValue;
445
446 Hexadecimal32BitsWithMinimumValue(int minimumValue) {
447 mMinimumValue = minimumValue;
448 }
449
450 @Override
451 public boolean validates(@NonNull MergingReport.Builder mergingReport,
452 @NonNull XmlAttribute attribute, @NonNull String value) {
453 boolean valid = super.validates(mergingReport, attribute, value);
454 if (valid) {
455 try {
456 Long decodedValue = Long.decode(value);
457 valid = decodedValue >= mMinimumValue && decodedValue < 0xFFFFFFFFL;
458 } catch(NumberFormatException e) {
459 valid = false;
460 }
461 if (!valid) {
462 attribute.addMessage(mergingReport, MergingReport.Record.Severity.ERROR,
463 String.format(
464 "Attribute %1$s at %2$s is not a valid hexadecimal value,"
465 + " minimum is 0x%3$08X, maximum is 0x%4$08X, found %5$s",
466 attribute.getId(),
467 attribute.printPosition(),
468 mMinimumValue,
469 Integer.MAX_VALUE,
470 value
471 ));
472 }
473 return valid;
474 }
475 return false;
476 }
477 }
478 }