blob: 646965b61bc91ae5e9ce8f3c8413c3d5793c9f93 [file] [log] [blame]
Jian Lib230e07c2020-12-21 11:25:12 +09001/*
2 * Copyright 2020-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.kubevirtnode.util;
17
18import com.fasterxml.jackson.databind.ObjectMapper;
19import org.slf4j.Logger;
20import org.slf4j.LoggerFactory;
21
22import java.io.IOException;
23import java.util.List;
24
25/**
26 * An utility that used in KubeVirt node app.
27 */
28public final class KubevirtNodeUtil {
29
30 private static final Logger log = LoggerFactory.getLogger(KubevirtNodeUtil.class);
31
32 private static final String COLON_SLASH = "://";
33 private static final String COLON = ":";
34
35 private static final int HEX_LENGTH = 16;
36 private static final String OF_PREFIX = "of:";
37 private static final String ZERO = "0";
38
39 /**
40 * Prevents object installation from external.
41 */
42 private KubevirtNodeUtil() {
43 }
44
45 /**
46 * Generates a DPID (of:0000000000000001) from an index value.
47 *
48 * @param index index value
49 * @return generated DPID
50 */
51 public static String genDpid(long index) {
52 if (index < 0) {
53 return null;
54 }
55
56 String hexStr = Long.toHexString(index);
57
58 StringBuilder zeroPadding = new StringBuilder();
59 for (int i = 0; i < HEX_LENGTH - hexStr.length(); i++) {
60 zeroPadding.append(ZERO);
61 }
62
63 return OF_PREFIX + zeroPadding.toString() + hexStr;
64 }
65
66 /**
67 * Generates string format based on the given string length list.
68 *
69 * @param stringLengths a list of string lengths
70 * @return string format (e.g., %-28s%-15s%-24s%-20s%-15s)
71 */
72 public static String genFormatString(List<Integer> stringLengths) {
73 StringBuilder fsb = new StringBuilder();
74 stringLengths.forEach(length -> {
75 fsb.append("%-");
76 fsb.append(length);
77 fsb.append("s");
78 });
79 return fsb.toString();
80 }
81
82 /**
83 * Prints out the JSON string in pretty format.
84 *
85 * @param mapper Object mapper
86 * @param jsonString JSON string
87 * @return pretty formatted JSON string
88 */
89 public static String prettyJson(ObjectMapper mapper, String jsonString) {
90 try {
91 Object jsonObject = mapper.readValue(jsonString, Object.class);
92 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
93 } catch (IOException e) {
94 log.debug("Json string parsing exception caused by {}", e);
95 }
96 return null;
97 }
98}