summaryrefslogtreecommitdiff
path: root/src/de/lmu/ifi/dbs/elki/result/textwriter/TextWriterStream.java
blob: 542be0998c873ea42af8eb43545a42557571801f (plain)
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
package de.lmu.ifi.dbs.elki.result.textwriter;

/*
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universität München
 Lehr- und Forschungseinheit für Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.PrintStream;

import de.lmu.ifi.dbs.elki.result.textwriter.writers.TextWriterObjectComment;
import de.lmu.ifi.dbs.elki.utilities.HandlerList;

/**
 * Representation of an output stream to a text file.
 * 
 * @author Erich Schubert
 * 
 * @apiviz.uses de.lmu.ifi.dbs.elki.result.textwriter.StreamFactory oneway - -
 *              wraps
 */
public class TextWriterStream {
  /**
   * Actual stream to write to.
   */
  private PrintStream outStream;

  /**
   * Buffer for inline data to output.
   */
  private StringBuilder inline;

  /**
   * Buffer for comment data to output.
   */
  private StringBuilder comment;

  /**
   * Handlers for various object types.
   */
  private HandlerList<TextWriterWriterInterface<?>> writers;

  /**
   * String to separate different entries while printing.
   */
  public static final String SEPARATOR = " ";

  /**
   * String to separate different entries while printing.
   */
  public static final String QUOTE = "# ";

  /**
   * Comment separator line. Since this will be printed without {@link #QUOTE}
   * infront, it should be quoted string itself.
   */
  public static final String COMMENTSEP = "###############################################################";

  /**
   * System newline character(s)
   */
  private static final String NEWLINE = System.getProperty("line.separator");

  /**
   * Marker used in text serialization (and re-parsing)
   */
  public static final String SER_MARKER = "Serialization class:";

  /**
   * Force incomments flag
   */
  // TODO: solve this more gracefully
  private boolean forceincomments = false;

  /**
   * Fallback writer, using toString.
   */
  private TextWriterObjectComment fallbackwriter = new TextWriterObjectComment();

  /**
   * Constructor.
   * 
   * @param out Actual stream to write to
   * @param writers Handlers for various data types
   */
  public TextWriterStream(PrintStream out, HandlerList<TextWriterWriterInterface<?>> writers) {
    this.outStream = out;
    this.writers = writers;
    inline = new StringBuilder();
    comment = new StringBuilder();
  }

  /**
   * Print an object into the comments section
   * 
   * @param line object to print into commments
   */
  public void commentPrint(Object line) {
    comment.append(line);
  }

  /**
   * Print an object into the comments section with trailing newline.
   * 
   * @param line object to print into comments
   */
  public void commentPrintLn(Object line) {
    comment.append(line);
    comment.append(NEWLINE);
  }

  /**
   * Print a newline into the comments section.
   */
  public void commentPrintLn() {
    comment.append(NEWLINE);
  }

  /**
   * Print a separator line in the comments section.
   */
  public void commentPrintSeparator() {
    comment.append(COMMENTSEP + NEWLINE);
  }

  /**
   * Print data into the inline part of the file. Data is sanitized: newlines
   * are replaced with spaces, and text containing separators is put in quotes.
   * Quotes and escape characters are escaped.
   * 
   * @param o object to print
   */
  public void inlinePrint(Object o) {
    if (forceincomments) {
      commentPrint(o);
      return;
    }
    if (inline.length() > 0) {
      inline.append(SEPARATOR);
    }
    // remove newlines
    String str = o.toString().replace(NEWLINE, " ");
    // escaping
    str = str.replace("\\", "\\\\").replace("\"", "\\\"");
    // when needed, add quotes.
    if (str.contains(SEPARATOR)) {
      str = "\"" + str + "\"";
    }
    inline.append(str);
  }

  /**
   * Print data into the inline part of the file WITHOUT checking for separators
   * (and thus quoting).
   * 
   * @param o object to print.
   */
  public void inlinePrintNoQuotes(Object o) {
    if (forceincomments) {
      commentPrint(o);
      return;
    }
    if (inline.length() > 0) {
      inline.append(SEPARATOR);
    }
    // remove newlines
    String str = o.toString().replace(NEWLINE, " ");
    // escaping
    str = str.replace("\\", "\\\\").replace("\"", "\\\"");
    inline.append(str);
  }

  /**
   * Flush output: write inline data, then write comment section. Reset streams.
   */
  public void flush() {
    if (inline.length() > 0) {
      outStream.println(inline);
    }
    inline.setLength(0);
    if (comment.length() > 0) {
      quotePrintln(outStream, comment.toString());
    }
    comment.setLength(0);
  }

  /**
   * Quoted println. All lines written will be prefixed with {@link #QUOTE}
   * 
   * @param outStream output stream to write to
   * @param data data to print
   */
  private void quotePrintln(PrintStream outStream, String data) {
    String[] lines = data.split("\r\n|\r|\n");
    for (String line : lines) {
      if (line.equals(COMMENTSEP)) {
        outStream.println(COMMENTSEP);
      } else {
        outStream.println(QUOTE + line);
      }
    }
  }

  /**
   * Retrieve an appropriate writer from the handler list.
   * 
   * @param o query object
   * @return appropriate write, if available
   */
  public TextWriterWriterInterface<?> getWriterFor(Object o) {
    if (o == null) {
      return null;
    }
    TextWriterWriterInterface<?> writer = writers.getHandler(o);
    if (writer == null) {
      try {
        if (o.getClass().getMethod("toString").getDeclaringClass() != Object.class) {
          return fallbackwriter;
        }
      } catch (Exception e) {
        return null;
      }
    }
    return writer;
  }

  /**
   * Restore a vector undoing any normalization that was applied. (This class
   * does not support normalization, it is only provided by derived classes,
   * which will then have to use generics.)
   * 
   * @param <O> Object class
   * @param v vector to restore
   * @return restored value.
   */
  public <O> O normalizationRestore(O v) {
    return v;
  }

  /**
   * Test force-in-comments flag.
   * 
   * @return flag value
   */
  protected boolean isForceincomments() {
    return forceincomments;
  }

  /**
   * Set the force-in-comments flag.
   * 
   * @param forceincomments the new flag value
   */
  protected void setForceincomments(boolean forceincomments) {
    this.forceincomments = forceincomments;
  }
}