blob: ec976c445508cd22d5e3187e9e33dae994041025 [file] [log] [blame]
Jian Li091d8d22018-02-20 10:42:06 +09001/*
2 * Copyright 2018-present Open Networking Foundation
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.onosproject.openstacknetworking.util;
17
18import com.fasterxml.jackson.databind.JsonNode;
19import com.fasterxml.jackson.databind.ObjectMapper;
20import org.openstack4j.core.transport.ObjectMapperSingleton;
21import org.openstack4j.model.ModelEntity;
22import org.slf4j.Logger;
23import org.slf4j.LoggerFactory;
24
25import java.io.InputStream;
26
27import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
28
29/**
30 * An utility that used in openstack networking app.
31 */
32public final class OpenstackUtil {
33
34 protected static final Logger log = LoggerFactory.getLogger(OpenstackUtil.class);
35
36 /**
37 * Prevents object instantiation from external.
38 */
39 private OpenstackUtil() {
40 }
41
42 /**
43 * Interprets JSON string to corresponding openstack model entity object.
44 *
45 * @param input JSON string
46 * @param entityClazz openstack model entity class
47 * @return openstack model entity object
48 */
49 public static ModelEntity jsonToModelEntity(InputStream input, Class entityClazz) {
50 ObjectMapper mapper = new ObjectMapper();
51 try {
52 JsonNode jsonTree = mapper.enable(INDENT_OUTPUT).readTree(input);
53 log.trace(new ObjectMapper().writeValueAsString(jsonTree));
54 return ObjectMapperSingleton.getContext(entityClazz)
55 .readerFor(entityClazz)
56 .readValue(jsonTree);
57 } catch (Exception e) {
58 throw new IllegalArgumentException();
59 }
60 }
61}