PageRenderTime 43ms CodeModel.GetById 26ms app.highlight 13ms RepoModel.GetById 1ms app.codeStats 0ms

/hippo/src/main/java/com/googlecode/hdbc/view/AbstractJsonView.java

http://hdbc.googlecode.com/
Java | 64 lines | 51 code | 11 blank | 2 comment | 6 complexity | 192ab7a64aeb9b3f1aab3611da5f2952 MD5 | raw file
 1package com.googlecode.hdbc.view;
 2
 3import java.io.ByteArrayOutputStream;
 4import java.nio.charset.Charset;
 5import java.util.Map;
 6import javax.servlet.http.HttpServletRequest;
 7import javax.servlet.http.HttpServletResponse;
 8import net.sf.json.JSONArray;
 9import net.sf.json.JSONObject;
10import org.springframework.context.support.MessageSourceAccessor;
11import org.springframework.validation.BindingResult;
12import org.springframework.validation.Errors;
13import org.springframework.validation.FieldError;
14import org.springframework.web.servlet.view.AbstractView;
15
16public abstract class AbstractJsonView extends AbstractView {
17	private String encoding;
18	
19	public AbstractJsonView(String contentType, String outputEncoding) {
20		this.setContentType(contentType);
21		if (Charset.isSupported(outputEncoding)) {
22			this.encoding = outputEncoding;
23		} else {
24			throw new IllegalArgumentException("The encoding, " + outputEncoding +
25				", is not supported on this platform");
26		}
27	}
28
29	@SuppressWarnings("unchecked")
30	@Override
31	protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
32		
33		// IE workaround: write into byte array first.
34		ByteArrayOutputStream baos = createTemporaryOutputStream();
35		
36		JSONObject json = buildJsonResponse(model, request, response);
37		byte[] output = json.toString().getBytes(encoding);
38		baos.write(output, 0, output.length);
39		
40		// Flush to HTTP response.
41		writeToResponse(response, baos);
42	}
43	
44	protected abstract JSONObject buildJsonResponse(Map<String, Object> model, HttpServletRequest request,
45			HttpServletResponse response);
46
47	protected JSONArray buildErrorArray(Map<String, Object> model) {
48		JSONArray errors = new JSONArray();
49		
50		Errors bindRslt = (BindingResult) model.get("errors");
51		if (bindRslt != null && bindRslt.hasFieldErrors()) {
52			MessageSourceAccessor msgSource = getMessageSourceAccessor();
53			for (Object error : bindRslt.getFieldErrors()) {
54				FieldError err = (FieldError) error;
55				JSONObject temp = new JSONObject();
56				temp.put(err.getField(), 
57					msgSource.getMessage(err.getCode(), err.getArguments()));
58				errors.add(temp);
59			}
60		}
61		return errors;
62	}
63
64}