All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.airlift.bootstrap.ColumnPrinter Maven / Gradle / Ivy

There is a newer version: 284
Show newest version
/*
 * Copyright 2010 Proofpoint, Inc.
 *
 * 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
 *
 *     http://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 io.airlift.bootstrap;

import com.google.common.collect.ImmutableList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Strings.repeat;
import static java.lang.Math.max;
import static java.util.stream.Collectors.toCollection;

/**
 * A utility for outputting columnar text
 */
class ColumnPrinter
{
    private static final int DEFAULT_MARGIN = 2;

    private final Collection> data = new LinkedHashSet<>();
    private final List columnNames;
    private final List columnWidths;
    private final int margin;

    public ColumnPrinter(String... columnNames)
    {
        this(DEFAULT_MARGIN, columnNames);
    }

    public ColumnPrinter(int margin, String... columnNames)
    {
        this.margin = margin;
        this.columnNames = ImmutableList.copyOf(columnNames);
        this.columnWidths = Arrays.stream(columnNames)
                .map(String::length)
                .collect(toCollection(ArrayList::new));
    }

    public void addValues(String... values)
    {
        checkArgument(values.length == columnNames.size(), "wrong value count");
        for (int i = 0; i < values.length; i++) {
            columnWidths.set(i, max(values[i].length(), columnWidths.get(i)));
        }
        data.add(ImmutableList.copyOf(values));
    }

    public List generateOutput()
    {
        List lines = new ArrayList<>();
        lines.add(printRow(columnNames));
        for (List row : data) {
            lines.add(printRow(row));
        }
        return lines;
    }

    private String printRow(List values)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < values.size(); i++) {
            sb.append(value(values.get(i), columnWidths.get(i) + margin));
        }
        return sb.toString().trim();
    }

    private static String value(String value, int width)
    {
        return value + repeat(" ", width - value.length());
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy