1 package org.simantics.diagram.svg.export;
4 import java.io.ByteArrayInputStream;
5 import java.io.IOException;
6 import java.io.UnsupportedEncodingException;
7 import java.util.HashMap;
10 import javax.xml.parsers.DocumentBuilder;
11 import javax.xml.parsers.DocumentBuilderFactory;
12 import javax.xml.parsers.ParserConfigurationException;
14 import org.apache.batik.svggen.SVGGeneratorContext;
15 import org.apache.batik.svggen.SVGShape;
16 import org.simantics.db.common.utils.Logger;
17 import org.simantics.scenegraph.utils.SVGPassthruShape;
18 import org.w3c.dom.Document;
19 import org.w3c.dom.Element;
20 import org.w3c.dom.Node;
21 import org.xml.sax.SAXException;
23 public class SVGShapeWithPassthruSupport extends SVGShape {
24 private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
26 public SVGShapeWithPassthruSupport(SVGGeneratorContext generatorCtx) {
28 dbf.setValidating(false);
29 dbf.setExpandEntityReferences(false);
31 dbf.setFeature("http://xml.org/sax/features/namespaces", false);
32 dbf.setFeature("http://xml.org/sax/features/validation", false);
33 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
34 dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
35 } catch (ParserConfigurationException e) {
36 Logger.defaultLogError(e);
40 public Element toSVG(Shape shape) {
41 if (shape instanceof SVGPassthruShape) {
42 String source = ((SVGPassthruShape) shape).getSource();
46 Document owner = generatorContext.getDOMFactory();
48 @SuppressWarnings("unchecked")
49 Map<String, String> defsMap = (Map<String, String>)owner.getUserData("defs-map");
50 if (defsMap == null) {
51 defsMap = new HashMap<String, String>();
52 owner.setUserData("defs-map", defsMap, null);
55 synchronized (defsMap) {
56 String symbolId = defsMap.get(source);
57 if (symbolId == null) {
58 symbolId = "S" + defsMap.size();
59 defsMap.put(source, symbolId);
61 DocumentBuilder db = dbf.newDocumentBuilder();
63 Document doc = db.parse(new ByteArrayInputStream(source.getBytes("UTF-8")));
64 Node node = doc.getDocumentElement();
65 Node localNode = owner.importNode(node, true);
67 if (localNode instanceof Element) {
68 Element g = generatorContext.getDOMFactory().createElementNS(SVG_NAMESPACE_URI, SVG_G_TAG);
69 Element e = (Element)localNode;
70 e.setAttribute("id", symbolId);
71 g.appendChild(localNode);
77 Element element = owner.createElement("use");
78 element.setAttribute("xlink:href", "#" + symbolId);
82 } catch (UnsupportedEncodingException e) {
83 Logger.defaultLogError(e);
85 } catch (IOException e) {
86 Logger.defaultLogError(e);
88 } catch (ParserConfigurationException e) {
89 Logger.defaultLogError(e);
91 } catch (SAXException e) {
92 Logger.defaultLogError(e);
96 return super.toSVG(shape);