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 public class XmlCompressorDirective extends Directive {
38
39
40 private static final XmlCompressor xmlCompressor = new XmlCompressor();
41
42 @Override
43 public String getName() {
44 return "compressXml";
45 }
46
47 @Override
48 public int getType() {
49 return BLOCK;
50 }
51
52 @Override
53 public void init(RuntimeServices rs, InternalContextAdapter context, Node node) throws TemplateInitException {
54 super.init(rs, context, node);
55 log = rs.getLog();
56
57
58 xmlCompressor.setEnabled(rs.getBoolean("userdirective.compressXml.enabled", true));
59 xmlCompressor.setRemoveComments(rs.getBoolean("userdirective.compressXml.removeComments", true));
60 xmlCompressor.setRemoveIntertagSpaces(rs.getBoolean("userdirective.compressXml.removeIntertagSpaces", true));
61 }
62
63 @Override
64 public boolean render(InternalContextAdapter context, Writer writer, Node node)
65 throws IOException, MethodInvocationException {
66
67
68 StringWriter content = new StringWriter();
69 node.jjtGetChild(0).render(context, content);
70
71
72 try {
73 writer.write(xmlCompressor.compress(content.toString()));
74 } catch (Exception e) {
75 writer.write(content.toString());
76 String msg = "Failed to compress content: " + content.toString();
77 log.error(msg, e);
78 throw new RuntimeException(msg, e);
79
80 }
81 return true;
82
83 }
84
85 }