Line data Source code
1 : // Copyright (C) 2012 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.server.ioutil; 16 : 17 : import java.io.PrintWriter; 18 : 19 : /** 20 : * Simple output formatter for column-oriented data, writing its output to a {@link 21 : * java.io.PrintWriter} object. Handles escaping of the column data so that the resulting output is 22 : * unambiguous and reasonably safe and machine parsable. 23 : */ 24 : public class ColumnFormatter { 25 : private char columnSeparator; 26 : private boolean firstColumn; 27 : private final PrintWriter out; 28 : 29 : /** 30 : * @param out The writer to which output should be sent. 31 : * @param columnSeparator A character that should serve as the separator token between columns of 32 : * output. As only non-printable characters in the column text are ever escaped, the column 33 : * separator must be a non-printable character if the output needs to be unambiguously parsed. 34 : */ 35 1 : public ColumnFormatter(PrintWriter out, char columnSeparator) { 36 1 : this.out = out; 37 1 : this.columnSeparator = columnSeparator; 38 1 : this.firstColumn = true; 39 1 : } 40 : 41 : /** 42 : * Adds a text string as a new column in the current line of output, taking care of escaping as 43 : * necessary. 44 : * 45 : * @param content the string to add. 46 : */ 47 : public void addColumn(String content) { 48 1 : if (!firstColumn) { 49 1 : out.print(columnSeparator); 50 : } 51 1 : out.print(StringUtil.escapeString(content)); 52 1 : firstColumn = false; 53 1 : } 54 : 55 : /** 56 : * Finishes the output by flushing the current line and takes care of any other cleanup action. 57 : */ 58 : public void finish() { 59 1 : nextLine(); 60 1 : out.flush(); 61 1 : } 62 : 63 : /** 64 : * Flushes the current line of output and makes the formatter ready to start receiving new column 65 : * data for a new line (or end-of-file). If the current line is empty nothing is done, i.e. 66 : * consecutive calls to this method without intervening calls to {@link #addColumn} will be 67 : * squashed. 68 : */ 69 : public void nextLine() { 70 1 : if (!firstColumn) { 71 1 : out.print('\n'); 72 1 : firstColumn = true; 73 : } 74 1 : } 75 : }