blob: d34e30e4e332c5da0054b27295599409b9b8385f [file] [log] [blame]
Thomas Vachuskaca60f2b2014-11-06 01:34:28 -08001/*
2 * Copyright 2014 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.onos.rest;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
20
21import javax.ws.rs.Produces;
22import javax.ws.rs.core.MediaType;
23import javax.ws.rs.core.MultivaluedMap;
24import javax.ws.rs.ext.MessageBodyWriter;
25import java.io.IOException;
26import java.io.OutputStream;
27import java.lang.annotation.Annotation;
28import java.lang.reflect.Type;
29
30/**
31 * JAX-RS Response message body writer.
32 */
33@Produces("application/json")
34public class JsonBodyWriter implements MessageBodyWriter<ObjectNode> {
35
36 private ObjectMapper mapper = new ObjectMapper();
37
38 @Override
39 public boolean isWriteable(Class<?> type, Type genericType,
40 Annotation[] annotations, MediaType mediaType) {
41 return type == ObjectNode.class;
42 }
43
44 @Override
45 public long getSize(ObjectNode node, Class<?> type, Type genericType,
46 Annotation[] annotations, MediaType mediaType) {
47 return -1;
48 }
49
50 @Override
51 public void writeTo(ObjectNode node, Class<?> type, Type genericType,
52 Annotation[] annotations, MediaType mediaType,
53 MultivaluedMap<String, Object> httpHeaders,
54 OutputStream entityStream) throws IOException {
55 mapper.writer().writeValue(entityStream, node);
56 entityStream.flush();
57 }
58}