1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.oxm.support;
18
19 import java.io.ByteArrayOutputStream;
20 import java.util.Iterator;
21 import java.util.Map;
22 import javax.servlet.ServletException;
23 import javax.servlet.ServletOutputStream;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import javax.xml.transform.stream.StreamResult;
27
28 import org.springframework.beans.BeansException;
29 import org.springframework.oxm.Marshaller;
30 import org.springframework.util.Assert;
31 import org.springframework.web.servlet.View;
32 import org.springframework.web.servlet.view.AbstractUrlBasedView;
33
34
35
36
37
38
39
40
41
42
43
44
45 public class MarshallingView extends AbstractUrlBasedView {
46
47
48 public static final String DEFAULT_CONTENT_TYPE = "application/xml";
49
50 private Marshaller marshaller;
51
52 private String modelKey;
53
54
55
56
57
58 public MarshallingView() {
59 setContentType(DEFAULT_CONTENT_TYPE);
60 }
61
62
63 public MarshallingView(Marshaller marshaller) {
64 Assert.notNull(marshaller, "'marshaller' must not be null");
65 setContentType(DEFAULT_CONTENT_TYPE);
66 this.marshaller = marshaller;
67 }
68
69
70 public void setMarshaller(Marshaller marshaller) {
71 Assert.notNull(marshaller, "'marshaller' must not be null");
72 this.marshaller = marshaller;
73 }
74
75
76
77
78
79
80
81 public void setModelKey(String modelKey) {
82 this.modelKey = modelKey;
83 }
84
85 protected void initApplicationContext() throws BeansException {
86 Assert.notNull(marshaller, "Property 'marshaller' is required");
87 }
88
89 protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
90 throws Exception {
91 Object toBeMarshalled = locateToBeMarshalled(model);
92 if (toBeMarshalled == null) {
93 throw new ServletException("Unable to locate object to be marshalled in model: " + model);
94 }
95 ByteArrayOutputStream bos = new ByteArrayOutputStream(2048);
96 marshaller.marshal(toBeMarshalled, new StreamResult(bos));
97
98 response.setContentType(getContentType());
99 response.setContentLength(bos.size());
100
101 ServletOutputStream out = response.getOutputStream();
102 bos.writeTo(out);
103 out.flush();
104 }
105
106
107
108
109
110
111
112
113
114
115
116
117 protected Object locateToBeMarshalled(Map model) throws ServletException {
118 if (this.modelKey != null) {
119 Object o = model.get(this.modelKey);
120 if (!this.marshaller.supports(o.getClass())) {
121 throw new ServletException("Model object [" + o + "] retrieved via key [" + modelKey +
122 "] is not supported by the Marshaller");
123 }
124 return o;
125 }
126 for (Iterator iterator = model.values().iterator(); iterator.hasNext();) {
127 Object o = iterator.next();
128 if (this.marshaller.supports(o.getClass())) {
129 return o;
130 }
131 }
132 return null;
133 }
134 }