Changed codec for Identityref in JSON transformation
[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.ResponseException;
21 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
22 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
23 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
24
25 import com.google.gson.stream.JsonWriter;
26
27 @Provider
28 @Produces({ Draft01.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
29         MediaType.APPLICATION_JSON })
30 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
31     INSTANCE;
32
33     @Override
34     public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
35         return true;
36     }
37
38     @Override
39     public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
40         return -1;
41     }
42
43     @Override
44     public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
45             MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
46             throws IOException, WebApplicationException {
47         CompositeNode data = t.getData();
48         if (data == null) {
49             throw new ResponseException(Response.Status.NOT_FOUND, "No data exists.");
50         }
51
52         JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
53         writer.setIndent("    ");
54         JsonMapper jsonMapper = new JsonMapper();
55         jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema(), t.getMountPoint());
56         writer.flush();
57     }
58
59 }