01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: XhtmlFormatter.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.cmf.format;
09:
10: import com.uwyn.rife.cmf.Content;
11: import com.uwyn.rife.cmf.format.exceptions.FormatException;
12: import com.uwyn.rife.cmf.format.exceptions.InvalidContentDataTypeException;
13: import com.uwyn.rife.cmf.format.exceptions.UnreadableDataFormatException;
14: import com.uwyn.rife.cmf.loader.XhtmlContentLoader;
15: import com.uwyn.rife.cmf.transform.ContentTransformer;
16: import com.uwyn.rife.tools.StringUtils;
17: import java.util.HashSet;
18: import java.util.Set;
19:
20: /**
21: * Formats raw <code>Content</code> data as valid Xhtml.
22: * <p>No content attributes are supported:
23: *
24: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
25: * @version $Revision: 3634 $
26: * @since 1.0
27: * @see Formatter
28: */
29: public class XhtmlFormatter implements Formatter<String, String> {
30: public String format(Content content,
31: ContentTransformer<String> transformer)
32: throws FormatException {
33: if (!(content.getData() instanceof String)) {
34: throw new InvalidContentDataTypeException(this , content
35: .getMimeType(), String.class, content.getData()
36: .getClass());
37: }
38:
39: String data = null;
40:
41: // check if the content contains a cached value of the loaded data
42: if (content.hasCachedLoadedData()) {
43: data = (String) content.getCachedLoadedData();
44: }
45:
46: if (null == data) {
47: // get an image
48: Set<String> errors = new HashSet<String>();
49: data = new XhtmlContentLoader().load(content.getData(),
50: content.isFragment(), errors);
51: if (null == data) {
52: throw new UnreadableDataFormatException(content
53: .getMimeType(), errors);
54: }
55: }
56:
57: // ensure that as much as possible entities are encoded
58: data = StringUtils.encodeHtmlDefensive(data);
59:
60: // transform the content, if needed
61: if (transformer != null) {
62: data = transformer.transform(data, content.getAttributes());
63: }
64:
65: return data;
66: }
67: }
|