1 package org.onap.sdc.dcae.catalog.commons;
3 import java.io.IOException;
4 import java.io.InputStreamReader;
5 import java.io.OutputStreamWriter;
8 import java.lang.reflect.Type;
9 import java.nio.charset.Charset;
11 import org.springframework.http.HttpHeaders;
12 import org.springframework.http.HttpInputMessage;
13 import org.springframework.http.HttpOutputMessage;
14 import org.springframework.http.MediaType;
15 import org.springframework.http.converter.AbstractHttpMessageConverter;
16 import org.springframework.http.converter.HttpMessageNotReadableException;
17 import org.springframework.http.converter.HttpMessageNotWritableException;
19 import org.json.JSONObject;
20 import org.json.JSONArray;
21 import org.json.JSONTokener;
22 import org.json.JSONException;
26 public class JSONHttpMessageConverter extends AbstractHttpMessageConverter<Object> {
28 public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
31 public JSONHttpMessageConverter() {
32 super(new MediaType("application", "json", DEFAULT_CHARSET));
36 public boolean canRead(Class<?> theClazz, MediaType theMediaType) {
37 return canRead(theMediaType);
41 public boolean canWrite(Class<?> theClazz, MediaType theMediaType) {
42 return canWrite(theMediaType);
46 protected boolean supports(Class<?> theClazz) {
47 return theClazz.equals(JSONObject.class) ||
48 theClazz.equals(JSONArray.class);
52 protected Object readInternal(Class<?> theClazz, HttpInputMessage theInputMessage)
53 throws IOException, HttpMessageNotReadableException {
55 Reader json = new InputStreamReader(theInputMessage.getBody(), getCharset(theInputMessage.getHeaders()));
58 if (theClazz.equals(JSONObject.class))
59 return new JSONObject(new JSONTokener(json));
60 if (theClazz.equals(JSONArray.class))
61 return new JSONArray(new JSONTokener(json));
63 throw new HttpMessageNotReadableException("Could not process input, cannot handle " + theClazz);
65 catch (JSONException jsonx) {
66 throw new HttpMessageNotReadableException("Could not read JSON: " + jsonx.getMessage(), jsonx);
71 protected void writeInternal(Object theObject, HttpOutputMessage theOutputMessage)
72 throws IOException, HttpMessageNotWritableException {
74 Writer writer = new OutputStreamWriter(theOutputMessage.getBody(), getCharset(theOutputMessage.getHeaders()));
77 if (theObject instanceof JSONObject) {
78 ((JSONObject)theObject).write(writer);
80 else if (theObject instanceof JSONArray) {
81 ((JSONArray)theObject).write(writer);
86 catch(JSONException jsonx) {
87 throw new HttpMessageNotWritableException("Could not write JSON: " + jsonx.getMessage(), jsonx);
91 private Charset getCharset(HttpHeaders theHeaders) {
92 if (theHeaders != null &&
93 theHeaders.getContentType() != null &&
94 theHeaders.getContentType().getCharSet() != null) {
95 return theHeaders.getContentType().getCharSet();
97 return DEFAULT_CHARSET;