Merge "Initial implementation of the ClusteredDataStore"
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / rest / impl / StructuredDataToJsonProvider.java
1 package org.opendaylight.controller.sal.rest.impl;
2
3 import static org.opendaylight.controller.sal.restconf.impl.MediaTypes.API;
4
5 import java.io.IOException;
6 import java.io.OutputStream;
7 import java.io.OutputStreamWriter;
8 import java.lang.annotation.Annotation;
9 import java.lang.reflect.Type;
10
11 import javax.ws.rs.Produces;
12 import javax.ws.rs.WebApplicationException;
13 import javax.ws.rs.core.MediaType;
14 import javax.ws.rs.core.MultivaluedMap;
15 import javax.ws.rs.ext.MessageBodyWriter;
16 import javax.ws.rs.ext.Provider;
17
18 import org.opendaylight.controller.sal.rest.api.RestconfService;
19 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
20 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
21
22 import com.google.gson.stream.JsonWriter;
23
24 @Provider
25 @Produces({ API + RestconfService.JSON })
26 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
27     INSTANCE;
28     
29     @Override
30     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
31         return true;
32     }
33
34     @Override
35     public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
36         return -1;
37     }
38
39     @Override
40     public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
41             MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
42             throws IOException, WebApplicationException {
43         JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
44         writer.setIndent("    ");
45         JsonMapper jsonMapper = new JsonMapper();
46         jsonMapper.write(writer, t.getData(), (DataNodeContainer) t.getSchema());
47         writer.flush();
48     }
49     
50 }