blob: 6bf8247545309a67672fa4ec7982c8df073c3657 [file] [log] [blame]
Thomas Vachuskaa026be72015-12-07 16:00:37 -08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Thomas Vachuskaa026be72015-12-07 16:00:37 -08003 *
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 */
16
17package org.onlab.rest;
18
19import com.fasterxml.jackson.databind.ObjectMapper;
20import com.fasterxml.jackson.databind.node.ObjectNode;
21
22import javax.ws.rs.Produces;
23import javax.ws.rs.core.MediaType;
24import javax.ws.rs.core.MultivaluedMap;
25import javax.ws.rs.ext.MessageBodyWriter;
26import javax.ws.rs.ext.Provider;
27import java.io.IOException;
28import java.io.OutputStream;
29import java.lang.annotation.Annotation;
30import java.lang.reflect.Type;
31
32/**
33 * JAX-RS Response message body writer.
34 */
35@Provider
36@Produces("application/json")
37public class JsonBodyWriter implements MessageBodyWriter<ObjectNode> {
38
39 private ObjectMapper mapper = new ObjectMapper();
40
41 @Override
42 public boolean isWriteable(Class<?> type, Type genericType,
43 Annotation[] annotations, MediaType mediaType) {
44 return type == ObjectNode.class;
45 }
46
47 @Override
48 public long getSize(ObjectNode node, Class<?> type, Type genericType,
49 Annotation[] annotations, MediaType mediaType) {
50 return -1;
51 }
52
53 @Override
54 public void writeTo(ObjectNode node, Class<?> type, Type genericType,
55 Annotation[] annotations, MediaType mediaType,
56 MultivaluedMap<String, Object> httpHeaders,
57 OutputStream entityStream) throws IOException {
58 mapper.writer().writeValue(entityStream, node);
59 entityStream.flush();
60 }
61}