You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AdvancedMessageFormat.java 15KB

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