blob: 7839378f58b7504cb28df710453a270a18de61f6 [file] [log] [blame]
chengfan9d60b6e2016-12-01 11:06:39 +08001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2016-present Open Networking Foundation
chengfan9d60b6e2016-12-01 11:06:39 +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.onosproject.provider.te.utils;
18
19
20import com.fasterxml.jackson.core.JsonProcessingException;
21import com.fasterxml.jackson.databind.ObjectMapper;
22import com.fasterxml.jackson.databind.ObjectWriter;
23import com.fasterxml.jackson.databind.node.ObjectNode;
24import org.slf4j.Logger;
25
26import java.io.IOException;
27import java.io.InputStream;
28
29import static org.slf4j.LoggerFactory.getLogger;
30
31
32/**
33 * Convert utility methods for IETF SB.
34 */
35public final class CodecTools {
36 private static final Logger log = getLogger(CodecTools.class);
37 private static final ObjectMapper MAPPER = new ObjectMapper();
38
39 //no instantiation
40 private CodecTools() {
41 }
42
43 /**
44 * Returns an object node from a InputStream type input which usually comes
45 * from the HTTP response.
46 *
47 * @param stream stream data comes from a HTTP response
48 * @return object node
49 */
50 public static ObjectNode toJson(InputStream stream) {
51 ObjectNode response = null;
52 try {
53 response = (ObjectNode) MAPPER.readTree(stream);
54 } catch (IOException e) {
55 log.error("Parse json string failed {}", e.getMessage());
56 }
57
58 return response;
59 }
60
61 /**
62 * Returns an object node from a string.
63 *
64 * @param jsonString string with JSON format
65 * @return object node
66 */
67 public static ObjectNode toJson(String jsonString) {
68 ObjectNode response = null;
69 try {
70 response = (ObjectNode) MAPPER.readTree(jsonString);
71 } catch (IOException e) {
72 log.error("Parse json string failed {}", e.getMessage());
73 }
74
75 return response;
76 }
77
78 /**
79 * Returns a JSON format string from a Jackson object node.
80 *
81 * @param node JSON object node
82 * @return string with JSON format
83 */
84 public static String jsonToString(ObjectNode node) {
85 ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
86 String jsonString = null;
87 try {
88 jsonString = ow.writeValueAsString(node);
89 } catch (JsonProcessingException e) {
90 log.error("Parse json to string failed {}", e.getMessage());
91 }
92
93 return jsonString;
94 }
95}