Merge "Table features : modified yang model. Patch set 2: Modified match types as...
[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 java.io.IOException;
4 import java.io.OutputStream;
5 import java.io.OutputStreamWriter;
6 import java.lang.annotation.Annotation;
7 import java.lang.reflect.Type;
8
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.WebApplicationException;
11 import javax.ws.rs.core.MediaType;
12 import javax.ws.rs.core.MultivaluedMap;
13 import javax.ws.rs.core.Response;
14 import javax.ws.rs.ext.MessageBodyWriter;
15 import javax.ws.rs.ext.Provider;
16
17 import org.opendaylight.controller.sal.rest.api.Draft01;
18 import org.opendaylight.controller.sal.rest.api.Draft02;
19 import org.opendaylight.controller.sal.rest.api.RestconfService;
20 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
21 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
22 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
23
24 import com.google.gson.stream.JsonWriter;
25
26 @Provider
27 @Produces({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
28         MediaType.APPLICATION_JSON })
29 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
30     INSTANCE;
31
32     @Override
33     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
34         return true;
35     }
36
37     @Override
38     public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
39         return -1;
40     }
41
42     @Override
43     public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
44             MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
45             throws IOException, WebApplicationException {
46         CompositeNode data = t.getData();
47         if (data == null) {
48             throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build());
49         }
50
51         JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
52         writer.setIndent("    ");
53         JsonMapper jsonMapper = new JsonMapper();
54         jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema());
55         writer.flush();
56     }
57
58 }