1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.googlecode.htmlcompressor.velocity;
17
18 import com.googlecode.htmlcompressor.compressor.XmlCompressor;
19
20 import java.io.IOException;
21 import java.io.StringWriter;
22 import java.io.Writer;
23
24 import org.apache.velocity.context.InternalContextAdapter;
25 import org.apache.velocity.exception.MethodInvocationException;
26 import org.apache.velocity.exception.TemplateInitException;
27 import org.apache.velocity.runtime.RuntimeServices;
28 import org.apache.velocity.runtime.directive.Directive;
29 import org.apache.velocity.runtime.parser.node.Node;
30
31
32
33
34
35
36
37
38
39 public class XmlCompressorDirective extends Directive {
40
41
42 private static final XmlCompressor xmlCompressor = new XmlCompressor();
43
44 @Override
45 public String getName() {
46 return "compressXml";
47 }
48
49 @Override
50 public int getType() {
51 return BLOCK;
52 }
53
54 @Override
55 public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
56 super.init(rs, context, node);
57 log = rs.getLog();
58
59
60 xmlCompressor.setEnabled(rs.getBoolean("userdirective.compressXml.enabled", true));
61 xmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressXml.removeComments", true));
62 xmlCompressor.setRemoveIntertagSpaces(rs.getBoolean("userdirective.compressXml.removeIntertagSpaces", true));
63 }
64
65 @Override
66 public boolean render(InternalContextAdapter context, Writer writer, Node node)
67 throws IOException, MethodInvocationException {
68
69
70 StringWriter content = new StringWriter();
71 node.jjtGetChild(0).render(context, content);
72
73
74 try {
75 writer.write(xmlCompressor.compress(content.toString()));
76 } catch (Exception e) {
77 writer.write(content.toString());
78 String msg = "Failed to compress content: " + content.toString();
79 log.error(msg, e);
80 throw new RuntimeException(msg, e);
81
82 }
83 return true;
84
85 }
86
87 }