1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package edu.internet2.middleware.shibboleth.common.profile.provider;
18
19 import java.io.IOException;
20 import java.io.OutputStreamWriter;
21
22 import org.apache.velocity.Template;
23 import org.apache.velocity.VelocityContext;
24 import org.apache.velocity.app.VelocityEngine;
25 import org.apache.velocity.runtime.resource.util.StringResourceRepository;
26 import org.opensaml.ws.transport.InTransport;
27 import org.opensaml.ws.transport.OutTransport;
28 import org.opensaml.xml.util.DatatypeHelper;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import edu.internet2.middleware.shibboleth.common.profile.AbstractErrorHandler;
33 import edu.internet2.middleware.shibboleth.common.util.StringResourceLoader;
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53 public class VelocityErrorHandler extends AbstractErrorHandler {
54
55
56 private final Logger log = LoggerFactory.getLogger(VelocityErrorHandler.class);
57
58
59 private VelocityEngine velocityEngine;
60
61
62 private String templatePath;
63
64
65
66
67
68
69
70 public VelocityErrorHandler(VelocityEngine engine, String template) {
71 if (engine == null) {
72 log.error("Velocity engine may not be null");
73 throw new IllegalArgumentException("Velocity engine may not be null");
74 }
75 velocityEngine = engine;
76
77 templatePath = DatatypeHelper.safeTrimOrNullString(template);
78 if (templatePath == null) {
79 log.error("Velocity template path may not be null or empty");
80 throw new IllegalArgumentException("Velocity template path may not be null or empty");
81 }
82 }
83
84
85
86
87
88
89 public void initialize() throws IOException {
90 String templateString = DatatypeHelper.inputstreamToString(getClass().getResourceAsStream(templatePath), null);
91 StringResourceRepository repository = StringResourceLoader.getRepository();
92
93 repository.putStringResource(templatePath, templateString);
94 }
95
96
97 public void processRequest(InTransport in, OutTransport out) {
98 VelocityContext context = new VelocityContext();
99 context.put("requestError", in.getAttribute(AbstractErrorHandler.ERROR_KEY));
100
101 try {
102 OutputStreamWriter responseWriter = new OutputStreamWriter(out.getOutgoingStream());
103 Template template = velocityEngine.getTemplate(templatePath);
104 template.merge(context, responseWriter);
105 responseWriter.flush();
106 } catch (Throwable t) {
107 log.error("Unable to evaluate velocity error template", t);
108 }
109
110 return;
111 }
112 }