|
| 1 | +/* |
| 2 | + * Copyright 2021 the original author or authors. |
| 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 | + * https://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 | + |
| 17 | +package org.springframework.cli.util; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | +import java.util.stream.Stream; |
| 21 | + |
| 22 | +import org.springframework.shell.table.ArrayTableModel; |
| 23 | +import org.springframework.shell.table.BorderStyle; |
| 24 | +import org.springframework.shell.table.Table; |
| 25 | +import org.springframework.shell.table.TableBuilder; |
| 26 | +import org.springframework.shell.table.TableModel; |
| 27 | + |
| 28 | +/** |
| 29 | + * Utility class for building tables to display data in the CLI. |
| 30 | + */ |
| 31 | +public final class TableUtils { |
| 32 | + |
| 33 | + // Private constructor to prevent instantiation |
| 34 | + private TableUtils() { |
| 35 | + throw new AssertionError("Utility class - do not instantiate"); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Builds a table with a single-column layout for displaying a list of items. |
| 40 | + * @param data the list of items to display in the table |
| 41 | + * @param header the header for the table column |
| 42 | + * @return a formatted Table object |
| 43 | + */ |
| 44 | + public static Table buildTable(List<String> data, String header) { |
| 45 | + Stream<String[]> headerStream = Stream.<String[]>of(new String[] { header }); |
| 46 | + Stream<String[]> rows = (data != null) ? data.stream().map(item -> new String[] { item }) : Stream.empty(); |
| 47 | + String[][] tableData = Stream.concat(headerStream, rows).toArray(String[][]::new); |
| 48 | + TableModel model = new ArrayTableModel(tableData); |
| 49 | + TableBuilder tableBuilder = new TableBuilder(model); |
| 50 | + return tableBuilder.addFullBorder(BorderStyle.fancy_light).build(); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments