Thomas Vachuska | ca60f2b | 2014-11-06 01:34:28 -0800 | [diff] [blame] | 1 | /* |
| 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 | */ |
Brian O'Connor | abafb50 | 2014-12-02 22:26:20 -0800 | [diff] [blame] | 16 | package org.onosproject.rest; |
Thomas Vachuska | ca60f2b | 2014-11-06 01:34:28 -0800 | [diff] [blame] | 17 | |
| 18 | import com.fasterxml.jackson.databind.ObjectMapper; |
| 19 | import com.fasterxml.jackson.databind.node.ObjectNode; |
| 20 | |
| 21 | import javax.ws.rs.Produces; |
| 22 | import javax.ws.rs.core.MediaType; |
| 23 | import javax.ws.rs.core.MultivaluedMap; |
| 24 | import javax.ws.rs.ext.MessageBodyWriter; |
| 25 | import java.io.IOException; |
| 26 | import java.io.OutputStream; |
| 27 | import java.lang.annotation.Annotation; |
| 28 | import java.lang.reflect.Type; |
| 29 | |
| 30 | /** |
| 31 | * JAX-RS Response message body writer. |
| 32 | */ |
| 33 | @Produces("application/json") |
| 34 | public 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 | } |