1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id$ */
package org.apache.fop.util.text;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import org.apache.xmlgraphics.util.Service;
/**
* Formats messages based on a template and with a set of named parameters. This is similar to
* {@link java.util.MessageFormat} but uses named parameters and supports conditional sub-groups.
* <p>
* Example:
* </p>
* <p><code>Missing field "{fieldName}"[ at location: {location}]!</code></p>
* <ul>
* <li>Curly brackets ("{}") are used for fields.</li>
* <li>Square brackets ("[]") are used to delimit conditional sub-groups. A sub-group is
* conditional when all fields inside the sub-group have a null value. In the case, everything
* between the brackets is skipped.</li>
* </ul>
*/
public class AdvancedMessageFormat {
/** Regex that matches "," but not "\," (escaped comma) */
static final Pattern COMMA_SEPARATOR_REGEX = Pattern.compile("(?<!\\\\),");
private static final Map PART_FACTORIES = new java.util.HashMap();
private static final List OBJECT_FORMATTERS = new java.util.ArrayList();
private static final Map FUNCTIONS = new java.util.HashMap();
private CompositePart rootPart;
static {
Iterator iter;
iter = Service.providers(PartFactory.class, true);
while (iter.hasNext()) {
PartFactory factory = (PartFactory)iter.next();
PART_FACTORIES.put(factory.getFormat(), factory);
}
iter = Service.providers(ObjectFormatter.class, true);
while (iter.hasNext()) {
OBJECT_FORMATTERS.add((ObjectFormatter)iter.next());
}
iter = Service.providers(Function.class, true);
while (iter.hasNext()) {
Function function = (Function)iter.next();
FUNCTIONS.put(function.getName(), function);
}
}
/**
* Construct a new message format.
* @param pattern the message format pattern.
*/
public AdvancedMessageFormat(CharSequence pattern) {
parsePattern(pattern);
}
private void parsePattern(CharSequence pattern) {
rootPart = new CompositePart(false);
StringBuffer sb = new StringBuffer();
parseInnerPattern(pattern, rootPart, sb, 0);
}
private int parseInnerPattern(CharSequence pattern, CompositePart parent,
StringBuffer sb, int start) {
assert sb.length() == 0;
int i = start;
int len = pattern.length();
loop:
while (i < len) {
char ch = pattern.charAt(i);
switch (ch) {
case '{':
if (sb.length() > 0) {
parent.addChild(new TextPart(sb.toString()));
sb.setLength(0);
}
i++;
int nesting = 1;
while (i < len) {
ch = pattern.charAt(i);
if (ch == '{') {
nesting++;
} else if (ch == '}') {
nesting--;
if (nesting == 0) {
i++;
break;
}
}
sb.append(ch);
i++;
}
parent.addChild(parseField(sb.toString()));
sb.setLength(0);
break;
case ']':
i++;
break loop; //Current composite is finished
case '[':
if (sb.length() > 0) {
parent.addChild(new TextPart(sb.toString()));
sb.setLength(0);
}
i++;
CompositePart composite = new CompositePart(true);
parent.addChild(composite);
i += parseInnerPattern(pattern, composite, sb, i);
break;
case '|':
if (sb.length() > 0) {
parent.addChild(new TextPart(sb.toString()));
sb.setLength(0);
}
parent.newSection();
i++;
break;
case '\\':
if (i < len - 1) {
i++;
ch = pattern.charAt(i);
}
//no break here! Must be right before "default" section
default:
sb.append(ch);
i++;
}
}
if (sb.length() > 0) {
parent.addChild(new TextPart(sb.toString()));
sb.setLength(0);
}
return i - start;
}
private Part parseField(String field) {
String[] parts = COMMA_SEPARATOR_REGEX.split(field, 3);
String fieldName = parts[0];
if (parts.length == 1) {
if (fieldName.startsWith("#")) {
return new FunctionPart(fieldName.substring(1));
} else {
return new SimpleFieldPart(fieldName);
}
} else {
String format = parts[1];
PartFactory factory = (PartFactory)PART_FACTORIES.get(format);
if (factory == null) {
throw new IllegalArgumentException(
"No PartFactory available under the name: " + format);
}
if (parts.length == 2) {
return factory.newPart(fieldName, null);
} else {
return factory.newPart(fieldName, parts[2]);
}
}
}
private static Function getFunction(String functionName) {
return (Function)FUNCTIONS.get(functionName);
}
/**
* Formats a message with the given parameters.
* @param params a Map of named parameters (Contents: <String, Object>)
* @return the formatted message
*/
public String format(Map params) {
StringBuffer sb = new StringBuffer();
format(params, sb);
return sb.toString();
}
/**
* Formats a message with the given parameters.
* @param params a Map of named parameters (Contents: <String, Object>)
* @param target the target StringBuffer to write the formatted message to
*/
public void format(Map params, StringBuffer target) {
rootPart.write(target, params);
}
/**
* Represents a message template part. This interface is implemented by various variants of
* the single curly braces pattern ({field}, {field,if,yes,no} etc.).
*/
public interface Part {
/**
* Writes the formatted part to a string buffer.
* @param sb the target string buffer
* @param params the parameters to work with
*/
void write(StringBuffer sb, Map params);
/**
* Indicates whether there is any content that is generated by this message part.
* @param params the parameters to work with
* @return true if the part has content
*/
boolean isGenerated(Map params);
}
/**
* Implementations of this interface parse a field part and return message parts.
*/
public interface PartFactory {
/**
* Creates a new part by parsing the values parameter to configure the part.
* @param fieldName the field name
* @param values the unparsed parameter values
* @return the new message part
*/
Part newPart(String fieldName, String values);
/**
* Returns the name of the message part format.
* @return the name of the message part format
*/
String getFormat();
}
/**
* Implementations of this interface format certain objects to strings.
*/
public interface ObjectFormatter {
/**
* Formats an object to a string and writes the result to a string buffer.
* @param sb the target string buffer
* @param obj the object to be formatted
*/
void format(StringBuffer sb, Object obj);
/**
* Indicates whether a given object is supported.
* @param obj the object
* @return true if the object is supported by the formatter
*/
boolean supportsObject(Object obj);
}
/**
* Implementations of this interface do some computation based on the message parameters
* given to it. Note: at the moment, this has to be done in a local-independent way since
* there is no locale information.
*/
public interface Function {
/**
* Executes the function.
* @param params the message parameters
* @return the function result
*/
Object evaluate(Map params);
/**
* Returns the name of the function.
* @return the name of the function
*/
Object getName();
}
private static class TextPart implements Part {
private String text;
public TextPart(String text) {
this.text = text;
}
public void write(StringBuffer sb, Map params) {
sb.append(text);
}
public boolean isGenerated(Map params) {
return true;
}
/** {@inheritDoc} */
public String toString() {
return this.text;
}
}
private static class SimpleFieldPart implements Part {
private String fieldName;
public SimpleFieldPart(String fieldName) {
this.fieldName = fieldName;
}
public void write(StringBuffer sb, Map params) {
if (!params.containsKey(fieldName)) {
throw new IllegalArgumentException(
"Message pattern contains unsupported field name: " + fieldName);
}
Object obj = params.get(fieldName);
formatObject(obj, sb);
}
public boolean isGenerated(Map params) {
Object obj = params.get(fieldName);
return obj != null;
}
/** {@inheritDoc} */
public String toString() {
return "{" + this.fieldName + "}";
}
}
/**
* Formats an object to a string and writes the result to a string buffer. This method
* usually uses the object's <code>toString()</code> method unless there is an
* {@link ObjectFormatter} that supports the object. {@link ObjectFormatter}s are registered
* through the service provider mechanism defined by the JAR specification.
* @param obj the object to be formatted
* @param target the target string buffer
*/
public static void formatObject(Object obj, StringBuffer target) {
if (obj instanceof String) {
target.append(obj);
} else {
boolean handled = false;
Iterator iter = OBJECT_FORMATTERS.iterator();
while (iter.hasNext()) {
ObjectFormatter formatter = (ObjectFormatter)iter.next();
if (formatter.supportsObject(obj)) {
formatter.format(target, obj);
handled = true;
break;
}
}
if (!handled) {
target.append(String.valueOf(obj));
}
}
}
private static class FunctionPart implements Part {
private Function function;
public FunctionPart(String functionName) {
this.function = getFunction(functionName);
if (this.function == null) {
throw new IllegalArgumentException("Unknown function: " + functionName);
}
}
public void write(StringBuffer sb, Map params) {
Object obj = this.function.evaluate(params);
formatObject(obj, sb);
}
public boolean isGenerated(Map params) {
Object obj = this.function.evaluate(params);
return obj != null;
}
/** {@inheritDoc} */
public String toString() {
return "{#" + this.function.getName() + "}";
}
}
private static class CompositePart implements Part {
protected List parts = new java.util.ArrayList();
private boolean conditional;
private boolean hasSections = false;
public CompositePart(boolean conditional) {
this.conditional = conditional;
}
private CompositePart(List parts) {
this.parts.addAll(parts);
this.conditional = true;
}
public void addChild(Part part) {
if (part == null) {
throw new NullPointerException("part must not be null");
}
if (hasSections) {
CompositePart composite = (CompositePart)this.parts.get(this.parts.size() - 1);
composite.addChild(part);
} else {
this.parts.add(part);
}
}
public void newSection() {
if (!hasSections) {
List p = this.parts;
//Dropping into a different mode...
this.parts = new java.util.ArrayList();
this.parts.add(new CompositePart(p));
hasSections = true;
}
this.parts.add(new CompositePart(true));
}
public void write(StringBuffer sb, Map params) {
if (hasSections) {
Iterator iter = this.parts.iterator();
while (iter.hasNext()) {
CompositePart part = (CompositePart)iter.next();
if (part.isGenerated(params)) {
part.write(sb, params);
break;
}
}
} else {
if (isGenerated(params)) {
Iterator iter = this.parts.iterator();
while (iter.hasNext()) {
Part part = (Part)iter.next();
part.write(sb, params);
}
}
}
}
public boolean isGenerated(Map params) {
if (hasSections) {
Iterator iter = this.parts.iterator();
while (iter.hasNext()) {
Part part = (Part)iter.next();
if (part.isGenerated(params)) {
return true;
}
}
return false;
} else {
if (conditional) {
Iterator iter = this.parts.iterator();
while (iter.hasNext()) {
Part part = (Part)iter.next();
if (!part.isGenerated(params)) {
return false;
}
}
}
return true;
}
}
/** {@inheritDoc} */
public String toString() {
return this.parts.toString();
}
}
static String unescapeComma(String string) {
return string.replaceAll("\\\\,", ",");
}
}
|