01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * 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:
18: /* $Id$ */
19:
20: package org.apache.fop.util;
21:
22: import java.io.ByteArrayInputStream;
23:
24: import javax.xml.transform.Source;
25: import javax.xml.transform.TransformerException;
26: import javax.xml.transform.URIResolver;
27: import javax.xml.transform.stream.StreamSource;
28:
29: // base64 support for "data" urls
30: import org.apache.xmlgraphics.util.io.Base64DecodeStream;
31:
32: /**
33: * Resolves data URLs (described in RFC 2397) returning its data as a StreamSource.
34: *
35: * @see javax.xml.transform.URIResolver
36: * @see <a href="http://www.ietf.org/rfc/rfc2397">RFC 2397</a>
37: */
38: public class DataURIResolver implements URIResolver {
39:
40: /**
41: * {@inheritDoc}
42: */
43: public Source resolve(String href, String base)
44: throws TransformerException {
45: if (href.startsWith("data:")) {
46: return parseDataURI(href);
47: } else {
48: return null;
49: }
50: }
51:
52: /**
53: * Parses inline data URIs as generated by MS Word's XML export and FO
54: * stylesheet.
55: *
56: * @see <a href="http://www.ietf.org/rfc/rfc2397">RFC 2397</a>
57: */
58: private Source parseDataURI(String href) {
59: int commaPos = href.indexOf(',');
60: // header is of the form data:[<mediatype>][;base64]
61: String header = href.substring(0, commaPos);
62: String data = href.substring(commaPos + 1);
63: if (header.endsWith(";base64")) {
64: byte[] bytes = data.getBytes();
65: ByteArrayInputStream encodedStream = new ByteArrayInputStream(
66: bytes);
67: Base64DecodeStream decodedStream = new Base64DecodeStream(
68: encodedStream);
69: return new StreamSource(decodedStream);
70: } else {
71: // Note that this is not quite the full story here. But since we are
72: // only interested
73: // in base64-encoded binary data, the next line will probably never
74: // be called.
75: //TODO Handle un-escaping of special URL chars like %20
76: return new StreamSource(new java.io.StringReader(data));
77: }
78: }
79:
80: }
|