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.conf.OnapCommandConstants;
32 import org.onap.cli.fw.error.OnapCommandOutputPrintingFailed;
33 import org.onap.cli.fw.output.OnapCommandPrintDirection;
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;
41 * Oclip Command Table print.
44 public class OnapCommandPrint {
46 public static final int MAX_COLUMN_LENGTH = 50;
48 private OnapCommandPrintDirection direction;
50 private Map<String, List<String>> data = new LinkedHashMap<>();
52 private boolean printTitle = true;
54 public OnapCommandPrintDirection getDirection() {
58 public void setDirection(OnapCommandPrintDirection direction) {
59 this.direction = direction;
62 public void addColumn(String header, List<String> data) {
63 this.data.put(header, data);
73 public List<String> getColumn(String header) {
74 if (this.data.get(header) == null) {
75 this.data.put(header, new ArrayList<String>());
77 return this.data.get(header);
80 public boolean isPrintTitle() {
84 public void setPrintTitle(boolean printTitle) {
85 this.printTitle = printTitle;
88 private int findMaxRows() {
90 if (!this.isPrintTitle()) {
93 for (List<String> cols : this.data.values()) {
94 if (cols != null && max < cols.size()) {
103 * Helps to form the rows from columns.
107 * @return +--------------+-----------+-----------------------------+ | header1 | header 2 | header 3 |
108 * +--------------+-----------+-----------------------------+ | v1 | List[line| v 3 | | | 1, line2]| |
109 * +--------------+-----------+-----------------------------+ | null | yyyyyy 2 | xxxxxx 3 |
110 * +--------------+-----------+-----------------------------+
112 private List<List<Object>> formRows(boolean isNormalize) {
113 List<List<Object>> rows = new ArrayList<>();
116 if (this.isPrintTitle()) {
117 List<Object> list = new ArrayList<>();
118 for (String key : this.data.keySet()) {
119 if (isNormalize && key != null && key.length() > MAX_COLUMN_LENGTH) {
120 list.add(splitIntoList(key, MAX_COLUMN_LENGTH));
129 for (int i = 0; i < this.findMaxRows(); i++) {
130 List<Object> row = new ArrayList<>();
131 for (List<String> cols : this.data.values()) {
132 if (cols != null && cols.size() > i) {
133 String value = cols.get(i);
134 // split the cell into multiple sub rows
135 if (isNormalize && value != null && value.length() > MAX_COLUMN_LENGTH) {
136 row.add(splitIntoList(value, MAX_COLUMN_LENGTH));
138 // store as string (one entry)
142 // no value exist for this column
153 * Splits big strings into list of strings based on maxCharInLine size.
157 * @param maxCharInLine
159 * @return list of strings
161 public List<String> splitIntoList(String input, int maxCharInLine) {
165 if (inp == null || "".equals(inp) || maxCharInLine <= 0) {
166 return Collections.emptyList();
168 // new line is converted to space char
169 if (inp.contains("\n")) {
170 inp = inp.replaceAll("\n", "");
173 StringTokenizer tok = new StringTokenizer(inp, " ");
174 StringBuilder output = new StringBuilder(inp.length());
176 while (tok.hasMoreTokens()) {
177 String word = tok.nextToken();
179 while (word.length() >= maxCharInLine) {
180 output.append(word.substring(0, maxCharInLine - lineLen) + "\n");
181 word = word.substring(maxCharInLine - lineLen);
185 if (lineLen + word.length() >= maxCharInLine) {
189 output.append(word + " ");
191 lineLen += word.length() + 1;
193 String[] strArray = output.toString().split("\n");
195 return Arrays.asList(strArray);
199 * Helps to print table.
201 * @param printSeparator
202 * Prints with line separator
203 * @return +--------------+-----------+-----------------------------+ | header1 | header 2 | header 3 |
204 * +--------------+-----------+-----------------------------+ | v1 | line 1 | v 3 | | | line 2 | |
205 * +--------------+-----------+-----------------------------+ | | yyyyyy 2 | xxxxxx 3 |
206 * +--------------+-----------+-----------------------------+
208 public String printTable(boolean printSeparator) {
209 List<List<Object>> rows = this.formRows(true);
210 TableGenerator table = new TableGenerator();
211 return table.generateTable(rows, printSeparator);
215 * Print output in csv format.
218 * @throws OnapCommandOutputPrintingFailed
221 public String printCsv() throws OnapCommandOutputPrintingFailed {
222 CSVFormat formattor = CSVFormat.DEFAULT.withRecordSeparator(System.getProperty("line.separator"));
224 try (StringWriter writer = new StringWriter();
225 CSVPrinter printer = new CSVPrinter(writer, formattor);) {
227 List<List<Object>> rows = this.formRows(false);
229 for (int i = 0; i < this.findMaxRows(); i++) {
230 printer.printRecord(rows.get(i));
233 return writer.toString();
234 } catch (IOException e) {
235 throw new OnapCommandOutputPrintingFailed(e);
239 public String printJson() {
240 List<List<Object>> rows = this.formRows(false);
242 JSONArray array = new JSONArray();
244 //skip first row title
245 List<Object> titleRow = rows.get(0);
247 for (int i=1; i<rows.size(); i++) {
248 JSONObject rowO = new JSONObject();
250 for (int j=0; j<titleRow.size(); j++) {
251 if (rows.get(i).get(j) != null)
252 rowO.put(titleRow.get(j).toString(), rows.get(i).get(j).toString());
258 JSONObject json = new JSONObject();
259 json.put(OnapCommandConstants.RESULTS, array);
260 return json.toJSONString();
263 public String printYaml() throws OnapCommandOutputPrintingFailed {
265 return new YAMLMapper().writeValueAsString(new ObjectMapper().readTree(this.printJson()));
266 } catch (IOException e) {
267 throw new OnapCommandOutputPrintingFailed(e); // NOSONAR