org.tomitribe.crest.table.Formatting Maven / Gradle / Ivy
/*
* Copyright 2021 Tomitribe and community
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tomitribe.crest.table;
import org.tomitribe.crest.api.PrintOutput;
import org.tomitribe.crest.term.Screen;
import org.tomitribe.util.collect.ObjectMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Formatting {
private Formatting() {
}
static Data asTable(final Iterable> iterable, final Options options) {
final String[] sort = getSortArray(options);
String[] fields = getFieldsArray(options);
final List> rows = new ArrayList<>();
for (final Object item : iterable) {
final CaseInsensitiveMap map = asMap(item);
if (fields == null) {
final Set keys = new LinkedHashSet<>(map.keySet());
if (map.isObject()) {
// Do not show class in any default contexts
// People can select it explicitly if they want it
keys.remove("class");
fields = keys.toArray(new String[0]);
} else {
fields = keys.stream()
.map(Parts::escape)
.toArray(String[]::new);
}
}
final List- row = new ArrayList<>();
for (final String field : fields) {
row.add(resolve(map, field));
}
rows.add(row);
}
if (sort != null && sort.length > 0) {
rows.sort(compareFields(fields, sort));
}
final Data.Builder data = Data.builder();
if (options.header()) {
// Add the headers
data.headings(true);
data.row(unescape(fields));
}
for (final List
- row : rows) {
final String[] a = new String[fields.length];
for (int i = 0; i < a.length; i++) {
a[i] = row.get(i).getString();
}
data.row(a);
}
return data.build();
}
private static String[] unescape(final String[] fields) {
final String[] headings = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
headings[i] = Parts.unescape(fields[i]);
}
return headings;
}
private static CaseInsensitiveMap asMap(final Object item) {
if (item instanceof CaseInsensitiveMap) {
return (CaseInsensitiveMap) item;
}
if (item instanceof Map) {
final Map, ?> map = (Map, ?>) item;
return new CaseInsensitiveMap(map, false);
}
/*
* Convert the object to a map
*/
final LinkedHashMap
© 2015 - 2025 Weber Informatics LLC | Privacy Policy