2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.sal.rest.impl;
10 import com.google.common.base.Charsets;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.OutputStreamWriter;
14 import java.lang.annotation.Annotation;
15 import java.lang.reflect.Type;
16 import javax.ws.rs.Produces;
17 import javax.ws.rs.WebApplicationException;
18 import javax.ws.rs.core.MediaType;
19 import javax.ws.rs.core.MultivaluedMap;
20 import javax.ws.rs.core.Response;
21 import javax.ws.rs.ext.MessageBodyWriter;
22 import javax.ws.rs.ext.Provider;
23 import org.opendaylight.controller.sal.rest.api.Draft02;
24 import org.opendaylight.controller.sal.rest.api.RestconfService;
25 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
26 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
27 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
28 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
30 import org.opendaylight.yangtools.yang.data.codec.gson.JSONNormalizedNodeStreamWriter;
33 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
34 Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
35 public class NormalizedNodeJsonBodyWriter implements MessageBodyWriter<NormalizedNodeContext> {
38 public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
39 return type.equals(NormalizedNodeContext.class);
43 public long getSize(final NormalizedNodeContext t, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
48 public void writeTo(final NormalizedNodeContext t, final Class<?> type, final Type genericType, final Annotation[] annotations,
49 final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream)
50 throws IOException, WebApplicationException {
51 if (t.getData() == null) {
52 throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
55 InstanceIdentifierContext pathContext = t.getInstanceIdentifierContext();
56 OutputStreamWriter ouWriter = new OutputStreamWriter(entityStream, Charsets.UTF_8);
57 NormalizedNodeStreamWriter jsonWriter = JSONNormalizedNodeStreamWriter.create(pathContext.getSchemaContext(),ouWriter);
58 NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(jsonWriter);
60 nnWriter.write(t.getData());