2 * Copyright 2017 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.cli.fw.output.print;
19 import java.io.IOException;
20 import java.io.StringWriter;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collections;
24 import java.util.LinkedHashMap;
25 import java.util.List;
27 import java.util.StringTokenizer;
29 import org.apache.commons.csv.CSVFormat;
30 import org.apache.commons.csv.CSVPrinter;
31 import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed;
32 import org.onap.cli.fw.output.OnapCommandPrintDirection;
34 import com.google.gson.JsonParser;
35 import com.fasterxml.jackson.databind.ObjectMapper;
36 import com.fasterxml.jackson.dataformat.yaml.YAMLMapper;
38 import net.minidev.json.JSONArray;
39 import net.minidev.json.JSONObject;
40 import net.minidev.json.JSONValue;
42 * Oclip Command Table print.
45 public class OnapCommandPrint {
48 public static final int MAX_COLUMN_LENGTH = 50;
50 private OnapCommandPrintDirection direction;
52 private Map<String, List<String>> data = new LinkedHashMap<>();
54 private boolean printTitle = true;
56 public OnapCommandPrintDirection getDirection() {
60 public void setDirection(OnapCommandPrintDirection direction) {
61 this.direction = direction;
64 public void addColumn(String header, List<String> data) {
65 this.data.put(header, data);
75 public List<String> getColumn(String header) {
76 return this.data.computeIfAbsent(header, k -> new ArrayList<String>());
79 public boolean isPrintTitle() {
83 public void setPrintTitle(boolean printTitle) {
84 this.printTitle = printTitle;
87 private int findMaxRows() {
89 if (!this.isPrintTitle()) {
92 for (List<String> cols : this.data.values()) {
93 if (cols != null && max < cols.size()) {
102 * Helps to form the rows from columns.
106 * @return +--------------+-----------+-----------------------------+ | header1 | header 2 | header 3 |
107 * +--------------+-----------+-----------------------------+ | v1 | List[line| v 3 | | | 1, line2]| |
108 * +--------------+-----------+-----------------------------+ | null | yyyyyy 2 | xxxxxx 3 |
109 * +--------------+-----------+-----------------------------+
111 private List<List<Object>> formRows(boolean isNormalize) {
112 List<List<Object>> rows = new ArrayList<>();
115 if (this.isPrintTitle()) {
116 List<Object> list = new ArrayList<>();
117 for (String key : this.data.keySet()) {
118 if (isNormalize && key != null && key.length() > MAX_COLUMN_LENGTH) {
119 list.add(splitIntoList(key, MAX_COLUMN_LENGTH));
128 for (int i = 0; i < this.findMaxRows(); i++) {
129 List<Object> row = new ArrayList<>();
130 for (List<String> cols : this.data.values()) {
131 if (cols != null && cols.size() > i) {
132 String value = cols.get(i);
133 // split the cell into multiple sub rows
134 if (isNormalize && value != null && value.length() > MAX_COLUMN_LENGTH) {
135 row.add(splitIntoList(value, MAX_COLUMN_LENGTH));
137 // store as string (one entry)
141 // no value exist for this column
152 * Splits big strings into list of strings based on maxCharInLine size.
156 * @param maxCharInLine
158 * @return list of strings
160 public List<String> splitIntoList(String input, int maxCharInLine) {
164 if (inp == null || "".equals(inp) || maxCharInLine <= 0) {
165 return Collections.emptyList();
167 // new line is converted to space char
168 if (inp.contains("\n")) {
169 inp = inp.replaceAll("\n", "");
172 StringTokenizer tok = new StringTokenizer(inp, " ");
173 StringBuilder output = new StringBuilder(inp.length());
175 while (tok.hasMoreTokens()) {
176 String word = tok.nextToken();
178 while (word.length() >= maxCharInLine) {
179 output.append(word.substring(0, maxCharInLine - lineLen) + "\n");
180 word = word.substring(maxCharInLine - lineLen);
184 if (lineLen + word.length() >= maxCharInLine) {
188 output.append(word + " ");
190 lineLen += word.length() + 1;
192 String[] strArray = output.toString().split("\n");
194 return Arrays.asList(strArray);
198 * Helps to print table.
200 * @param printSeparator
201 * Prints with line separator
202 * @return +--------------+-----------+-----------------------------+ | header1 | header 2 | header 3 |
203 * +--------------+-----------+-----------------------------+ | v1 | line 1 | v 3 | | | line 2 | |
204 * +--------------+-----------+-----------------------------+ | | yyyyyy 2 | xxxxxx 3 |
205 * +--------------+-----------+-----------------------------+
207 public String printTable(boolean printSeparator) {
208 List<List<Object>> rows = this.formRows(true);
209 TableGenerator table = new TableGenerator();
210 return table.generateTable(rows, printSeparator);
214 * Print output in csv format.
217 * @throws OnapCommandOutputPrintingFailed
220 public String printCsv() throws OnapCommandOutputPrintingFailed {
221 CSVFormat formattor = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));
223 try (StringWriter writer = new StringWriter();
224 CSVPrinter printer = new CSVPrinter(writer, formattor);) {
226 List<List<Object>> rows = this.formRows(false);
228 for (int i = 0; i < this.findMaxRows(); i++) {
229 printer.printRecord(rows.get(i));
232 return writer.toString();
233 } catch (IOException e) {
234 throw new OnapCommandOutputPrintingFailed(e);
238 public Object getJsonNodeOrString(String value) {
240 return JSONValue.parse(value);
241 } catch (Exception e) {
246 public String printJson() {
247 List<List<Object>> rows = this.formRows(false);
249 if (this.direction.equals(OnapCommandPrintDirection.PORTRAIT)) {
250 JSONObject result = new JSONObject();
251 for (int i=1; i<rows.size(); i++) {
252 if (rows.get(i).get(1) != null)
253 result.put(rows.get(i).get(0).toString(), this.getJsonNodeOrString(rows.get(i).get(1).toString()));
255 return result.toJSONString();
257 JSONArray array = new JSONArray();
259 //skip first row title
260 List<Object> titleRow = rows.get(0);
262 for (int i=1; i<rows.size(); i++) {
263 JSONObject rowO = new JSONObject();
265 for (int j=0; j<titleRow.size(); j++) {
266 if (rows.get(i).get(j) != null)
267 rowO.put(titleRow.get(j).toString(), this.getJsonNodeOrString(rows.get(i).get(j).toString()));
273 return new JsonParser().parse(array.toJSONString()).toString();
274 } catch (Exception e) { // NOSONAR
275 return array.toJSONString();
281 public String printYaml() throws OnapCommandOutputPrintingFailed {
283 return new YAMLMapper().writeValueAsString(new ObjectMapper().readTree(this.printJson()));
284 } catch (IOException e) {
285 throw new OnapCommandOutputPrintingFailed(e); // NOSONAR