mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Fabio Pistolesi
21.55.2015 d1b4e9a4680072beb3c83135e47c25549fbf8f7d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2007-2008 Sun Microsystems, Inc.
 *      Portions Copyright 2014-2015 ForgeRock AS
 */
package com.forgerock.opendj.cli;
 
import static com.forgerock.opendj.cli.Utils.MAX_LINE_WIDTH;
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * An interface for creating a text based table.
 * Tables have configurable column widths, padding, and column separators.
 */
public final class TextTablePrinter extends TablePrinter {
 
    /**
     * Table serializer implementation.
     */
    private final class Serializer extends TableSerializer {
 
        /**The real column widths taking into account size constraints but
         not including padding or separators.*/
        private final List<Integer> columnWidths = new ArrayList<>();
 
        /** The cells in the current row. */
        private final List<String> currentRow = new ArrayList<>();
 
        /** Width of the table in columns. */
        private int totalColumns;
 
        /** The padding to use for indenting the table. */
        private final String indentPadding;
 
        /** Private constructor. */
        private Serializer() {
            // Compute the indentation padding.
            final StringBuilder builder = new StringBuilder();
            for (int i = 0; i < indentWidth; i++) {
                builder.append(' ');
            }
            this.indentPadding = builder.toString();
        }
 
        /** {@inheritDoc} */
        @Override
        public void addCell(String s) {
            currentRow.add(s);
        }
 
        /** {@inheritDoc} */
        @Override
        public void addColumn(int width) {
            columnWidths.add(width);
            totalColumns++;
        }
 
        /** {@inheritDoc} */
        @Override
        public void addHeading(String s) {
            if (displayHeadings) {
                addCell(s);
            }
        }
 
        /** {@inheritDoc} */
        @Override
        public void endHeader() {
            if (displayHeadings) {
                endRow();
 
                // Print the header separator.
                final StringBuilder builder = new StringBuilder(indentPadding);
                for (int i = 0; i < totalColumns; i++) {
                    int width = columnWidths.get(i);
                    if (totalColumns > 1) {
                        if (i == 0 || i == (totalColumns - 1)) {
                            // Only one lot of padding for first and last columns.
                            width += padding;
                        } else {
                            width += padding * 2;
                        }
                    }
 
                    for (int j = 0; j < width; j++) {
                        if (headingSeparatorStartColumn > 0) {
                            if (i < headingSeparatorStartColumn) {
                                builder.append(' ');
                            } else if (i == headingSeparatorStartColumn && j < padding) {
                                builder.append(' ');
                            } else {
                                builder.append(headingSeparator);
                            }
                        } else {
                            builder.append(headingSeparator);
                        }
                    }
 
                    if ((i >= headingSeparatorStartColumn) && i < (totalColumns - 1)) {
                        builder.append(columnSeparator);
                    }
                }
                writer.println(builder.toString());
            }
        }
 
        /** {@inheritDoc} */
        @Override
        public void endRow() {
            boolean isRemainingText;
            do {
                StringBuilder builder = new StringBuilder(indentPadding);
                isRemainingText = false;
                for (int i = 0; i < currentRow.size(); i++) {
                    int width = columnWidths.get(i);
                    String contents = currentRow.get(i);
 
                    // Determine what parts of contents can be displayed on this line.
                    String head;
                    String tail = null;
 
                    if (contents == null) {
                        // This cell has been displayed fully.
                        head = "";
                    } else if (contents.length() > width) {
                        // We're going to have to split the cell on next word boundary.
                        int endIndex = contents.lastIndexOf(' ', width);
                        if (endIndex == -1) {
                            endIndex = width;
                            head = contents.substring(0, endIndex);
                            tail = contents.substring(endIndex);
 
                        } else {
                            head = contents.substring(0, endIndex);
                            tail = contents.substring(endIndex + 1);
                        }
                    } else {
                        // The contents fits ok.
                        head = contents;
                    }
 
                    // Add this cell's contents to the current line.
                    if (i > 0) {
                        // Add right padding for previous cell.
                        for (int j = 0; j < padding; j++) {
                            builder.append(' ');
                        }
 
                        // Add separator.
                        builder.append(columnSeparator);
 
                        // Add left padding for this cell.
                        for (int j = 0; j < padding; j++) {
                            builder.append(' ');
                        }
                    }
 
                    // Add cell contents.
                    builder.append(head);
 
                    // Now pad with extra space to make up the width.
                    // Only if it's not the last cell (see issue #3210)
                    if (i != currentRow.size() - 1) {
                        for (int j = head.length(); j < width; j++) {
                            builder.append(' ');
                        }
                    }
 
                    // Update the row contents.
                    currentRow.set(i, tail);
                    if (tail != null) {
                        isRemainingText = true;
                    }
                }
 
                // Output the line.
                writer.println(builder.toString());
 
            } while (isRemainingText);
        }
 
        /** {@inheritDoc} */
        @Override
        public void endTable() {
            writer.flush();
        }
 
        /** {@inheritDoc} */
        @Override
        public void startHeader() {
            determineColumnWidths();
            currentRow.clear();
        }
 
        /** {@inheritDoc} */
        @Override
        public void startRow() {
            currentRow.clear();
        }
 
        /** We need to calculate the effective width of each column. */
        private void determineColumnWidths() {
            // First calculate the minimum width so that we know how much
            // expandable columns can expand.
            int minWidth = indentWidth;
            int expandableColumnSize = 0;
 
            for (int i = 0; i < totalColumns; i++) {
                int actualSize = columnWidths.get(i);
 
                if (fixedColumns.containsKey(i)) {
                    int requestedSize = fixedColumns.get(i);
 
                    if (requestedSize == 0) {
                        expandableColumnSize += actualSize;
                    } else {
                        columnWidths.set(i, requestedSize);
                        minWidth += requestedSize;
                    }
                } else {
                    minWidth += actualSize;
                }
 
                // Must also include padding and separators.
                if (i > 0) {
                    minWidth += padding * 2 + columnSeparator.length();
                }
            }
 
            if (minWidth > totalWidth) {
                // The table is too big: leave expandable columns at their
                // requested width, as there's not much else that can be done.
            } else {
                int available = totalWidth - minWidth;
 
                if (expandableColumnSize > available) {
                    // Only modify column sizes if necessary.
                    for (int i = 0; i < totalColumns; i++) {
                        int actualSize = columnWidths.get(i);
 
                        if (fixedColumns.containsKey(i)) {
                            int requestedSize = fixedColumns.get(i);
                            if (requestedSize == 0) {
                                // Calculate size based on requested actual size as a
                                // proportion of the total.
                                requestedSize = (actualSize * available) / expandableColumnSize;
                                columnWidths.set(i, requestedSize);
                            }
                        }
                    }
                }
            }
        }
    }
 
    /**
     * The default string which should be used to separate one column from the next (not including padding).
     */
    private static final String DEFAULT_COLUMN_SEPARATOR = "";
 
    /**
     * The default character which should be used to separate the table heading row from the rows beneath.
     */
    private static final char DEFAULT_HEADING_SEPARATOR = '-';
 
    /**
     * The default padding which will be used to separate a cell's contents from its adjacent column separators.
     */
    private static final int DEFAULT_PADDING = 1;
 
    /**
     * The string which should be used to separate one column
     * from the next (not including padding).
     */
    private String columnSeparator = DEFAULT_COLUMN_SEPARATOR;
 
    /** Indicates whether or not the headings should be output. */
    private boolean displayHeadings = true;
 
    /** Table indicating whether or not a column is fixed width. */
    private final Map<Integer, Integer> fixedColumns = new HashMap<>();
 
    /** The number of characters the table should be indented. */
    private int indentWidth;
 
    /**
     * The character which should be used to separate the table
     * heading row from the rows beneath.
     */
    private char headingSeparator = DEFAULT_HEADING_SEPARATOR;
 
    /** The column where the heading separator should begin. */
    private int headingSeparatorStartColumn;
 
    /**
     * The padding which will be used to separate a cell's
     * contents from its adjacent column separators.
     */
    private int padding = DEFAULT_PADDING;
 
    /**
     * Total permitted width for the table which expandable columns
     * can use up.
     */
    private int totalWidth = MAX_LINE_WIDTH;
 
    /** The output destination. */
    private PrintWriter writer;
 
    /**
     * Creates a new text table printer for the specified output stream. The text table printer will have the following
     * initial settings:
     * <ul>
     * <li>headings will be displayed
     * <li>no separators between columns
     * <li>columns are padded by one character
     * </ul>
     *
     * @param stream
     *            The stream to output tables to.
     */
    public TextTablePrinter(OutputStream stream) {
        this(new BufferedWriter(new OutputStreamWriter(stream)));
    }
 
    /**
     * Creates a new text table printer for the specified writer. The text table printer will have the following initial
     * settings:
     * <ul>
     * <li>headings will be displayed
     * <li>no separators between columns
     * <li>columns are padded by one character
     * </ul>
     *
     * @param writer
     *            The writer to output tables to.
     */
    public TextTablePrinter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }
 
    /**
     * Sets the column separator which should be used to separate one column from the next (not including padding).
     *
     * @param columnSeparator
     *            The column separator.
     */
    public void setColumnSeparator(String columnSeparator) {
        this.columnSeparator = columnSeparator;
    }
 
    /**
     * Set the maximum width for a column. If a cell is too big to fit in its column then it will be wrapped.
     *
     * @param column
     *            The column to make fixed width (0 is the first column).
     * @param width
     *            The width of the column (this should not include column separators or padding), or <code>0</code> to
     *            indicate that this column should be expandable.
     * @throws IllegalArgumentException
     *             If column is less than 0.
     */
    public void setColumnWidth(int column, int width) {
        if (column < 0) {
            throw new IllegalArgumentException("Negative column " + column);
        }
 
        if (width < 0) {
            throw new IllegalArgumentException("Negative width " + width);
        }
 
        fixedColumns.put(column, width);
    }
 
    /**
     * Specify whether the column headings should be displayed or not.
     *
     * @param displayHeadings
     *            <code>true</code> if column headings should be displayed.
     */
    public void setDisplayHeadings(boolean displayHeadings) {
        this.displayHeadings = displayHeadings;
    }
 
    /**
     * Sets the heading separator which should be used to separate the table heading row from the rows beneath.
     *
     * @param headingSeparator
     *            The heading separator.
     */
    public void setHeadingSeparator(char headingSeparator) {
        this.headingSeparator = headingSeparator;
    }
 
    /**
     * Sets the heading separator start column. The heading separator will only be display in the specified column and
     * all subsequent columns. Usually this should be left at zero (the default) but sometimes it useful to indent the
     * heading separate in order to provide additional emphasis (for example in menus).
     *
     * @param startColumn
     *            The heading separator start column.
     */
    public void setHeadingSeparatorStartColumn(int startColumn) {
        if (startColumn < 0) {
            throw new IllegalArgumentException("Negative start column " + startColumn);
        }
        this.headingSeparatorStartColumn = startColumn;
    }
 
    /**
     * Sets the amount of characters that the table should be indented. By default the table is not indented.
     *
     * @param indentWidth
     *            The number of characters the table should be indented.
     * @throws IllegalArgumentException
     *             If indentWidth is less than 0.
     */
    public void setIndentWidth(int indentWidth) {
        if (indentWidth < 0) {
            throw new IllegalArgumentException("Negative indentation width " + indentWidth);
        }
 
        this.indentWidth = indentWidth;
    }
 
    /**
     * Sets the padding which will be used to separate a cell's contents from its adjacent column separators.
     *
     * @param padding
     *            The padding.
     */
    public void setPadding(int padding) {
        this.padding = padding;
    }
 
    /**
     * Sets the total permitted width for the table which expandable columns can use up.
     *
     * @param totalWidth
     *            The total width.
     */
    public void setTotalWidth(int totalWidth) {
        this.totalWidth = totalWidth;
    }
 
    /** {@inheritDoc} */
    @Override
    protected TableSerializer getSerializer() {
        return new Serializer();
    }
}