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

Matthew Swift
21.30.2013 f51e4456baf7d5538f8d5e06dddba6aa25c67b33
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
/*
 * 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 2009 Sun Microsystems, Inc.
 *      Portions copyright 2011-2013 ForgeRock AS
 */
 
package org.forgerock.opendj.ldif;
 
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import java.util.regex.Pattern;
 
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.controls.Control;
 
import com.forgerock.opendj.util.Validator;
 
/**
 * Common LDIF writer functionality.
 */
abstract class AbstractLDIFWriter extends AbstractLDIFStream {
 
    /**
     * LDIF writer implementation interface.
     */
    interface LDIFWriterImpl {
 
        /**
         * Closes any resources associated with this LDIF writer implementation.
         *
         * @throws IOException
         *             If an error occurs while closing.
         */
        void close() throws IOException;
 
        /**
         * Flushes this LDIF writer implementation so that any buffered data is
         * written immediately to underlying stream, flushing the stream if it
         * is also {@code Flushable}.
         * <p>
         * If the intended destination of this stream is an abstraction provided
         * by the underlying operating system, for example a file, then flushing
         * the stream guarantees only that bytes previously written to the
         * stream are passed to the operating system for writing; it does not
         * guarantee that they are actually written to a physical device such as
         * a disk drive.
         *
         * @throws IOException
         *             If an error occurs while flushing.
         */
        void flush() throws IOException;
 
        /**
         * Prints the provided {@code CharSequence}. Implementations must not
         * add a new-line character sequence.
         *
         * @param s
         *            The {@code CharSequence} to be printed.
         * @throws IOException
         *             If an error occurs while printing {@code s}.
         */
        void print(CharSequence s) throws IOException;
 
        /**
         * Prints a new-line character sequence.
         *
         * @throws IOException
         *             If an error occurs while printing the new-line character
         *             sequence.
         */
        void println() throws IOException;
    }
 
    /**
     * LDIF string list writer implementation.
     */
    private static final class LDIFWriterListImpl implements LDIFWriterImpl {
        private final StringBuilder builder = new StringBuilder();
        private final List<String> ldifLines;
 
        LDIFWriterListImpl(final List<String> ldifLines) {
            this.ldifLines = ldifLines;
        }
 
        @Override
        public void close() throws IOException {
            // Nothing to do.
        }
 
        @Override
        public void flush() throws IOException {
            // Nothing to do.
        }
 
        @Override
        public void print(final CharSequence s) throws IOException {
            builder.append(s);
        }
 
        @Override
        public void println() throws IOException {
            ldifLines.add(builder.toString());
            builder.setLength(0);
        }
    }
 
    /**
     * LDIF output stream writer implementation.
     */
    private static final class LDIFWriterOutputStreamImpl implements LDIFWriterImpl {
        private final BufferedWriter writer;
 
        LDIFWriterOutputStreamImpl(final Writer writer) {
            this.writer =
                    writer instanceof BufferedWriter ? (BufferedWriter) writer
                            : new BufferedWriter(writer);
        }
 
        @Override
        public void close() throws IOException {
            writer.close();
        }
 
        @Override
        public void flush() throws IOException {
            writer.flush();
        }
 
        @Override
        public void print(final CharSequence s) throws IOException {
            writer.append(s);
        }
 
        @Override
        public void println() throws IOException {
            writer.newLine();
        }
    }
 
    /*
     * Regular expression used for splitting comments on line-breaks.
     */
    private static final Pattern SPLIT_NEWLINE = Pattern.compile("\\r?\\n");
    boolean addUserFriendlyComments = false;
    final LDIFWriterImpl impl;
    int wrapColumn = 0;
    private final StringBuilder builder = new StringBuilder(80);
 
    AbstractLDIFWriter(final List<String> ldifLines) {
        this.impl = new LDIFWriterListImpl(ldifLines);
    }
 
    AbstractLDIFWriter(final OutputStream out) {
        this(new OutputStreamWriter(out));
    }
 
    AbstractLDIFWriter(final Writer writer) {
        this.impl = new LDIFWriterOutputStreamImpl(writer);
    }
 
    final void close0() throws IOException {
        flush0();
        impl.close();
    }
 
    final void flush0() throws IOException {
        impl.flush();
    }
 
    final void writeComment0(final CharSequence comment) throws IOException {
        Validator.ensureNotNull(comment);
 
        /*
         * First, break up the comment into multiple lines to preserve the
         * original spacing that it contained.
         */
        final String[] lines = SPLIT_NEWLINE.split(comment);
 
        /*
         * Now iterate through the lines and write them out, prefixing and
         * wrapping them as necessary.
         */
        for (final String line : lines) {
            if (!shouldWrap()) {
                impl.print("# ");
                impl.print(line);
                impl.println();
            } else {
                final int breakColumn = wrapColumn - 2;
                if (line.length() <= breakColumn) {
                    impl.print("# ");
                    impl.print(line);
                    impl.println();
                } else {
                    int startPos = 0;
                outerLoop:
                    while (startPos < line.length()) {
                        if (startPos + breakColumn >= line.length()) {
                            impl.print("# ");
                            impl.print(line.substring(startPos));
                            impl.println();
                            startPos = line.length();
                        } else {
                            final int endPos = startPos + breakColumn;
                            int i = endPos - 1;
                            while (i > startPos) {
                                if (line.charAt(i) == ' ') {
                                    impl.print("# ");
                                    impl.print(line.substring(startPos, i));
                                    impl.println();
 
                                    startPos = i + 1;
                                    continue outerLoop;
                                }
                                i--;
                            }
 
                            /*
                             * If we've gotten here, then there are no spaces on
                             * the entire line. If that happens, then we'll have
                             * to break in the middle of a word.
                             */
                            impl.print("# ");
                            impl.print(line.substring(startPos, endPos));
                            impl.println();
                            startPos = endPos;
                        }
                    }
                }
            }
        }
    }
 
    final void writeControls(final List<Control> controls) throws IOException {
        for (final Control control : controls) {
            final StringBuilder key = new StringBuilder("control: ");
            key.append(control.getOID());
            key.append(control.isCritical() ? " true" : " false");
            if (control.hasValue()) {
                writeKeyAndValue(key, control.getValue());
            } else {
                writeLine(key);
            }
        }
    }
 
    final void writeKeyAndValue(final CharSequence key, final ByteSequence value)
            throws IOException {
        builder.setLength(0);
 
        /*
         * If the value is empty, then just append a single colon and a single
         * space.
         */
        if (value.length() == 0) {
            builder.append(key);
            builder.append(": ");
        } else if (needsBase64Encoding(value)) {
            if (addUserFriendlyComments) {
                /*
                 * TODO: Only display comments for valid UTF-8 values, not
                 * binary values.
                 */
            }
            builder.setLength(0);
            builder.append(key);
            builder.append(":: ");
            builder.append(value.toBase64String());
        } else {
            builder.append(key);
            builder.append(": ");
            builder.append(value.toString());
        }
        writeLine(builder);
    }
 
    final void writeKeyAndValue(final CharSequence key, final CharSequence value)
            throws IOException {
        // FIXME: We should optimize this at some point.
        writeKeyAndValue(key, ByteString.valueOf(value.toString()));
    }
 
    final void writeLine(final CharSequence line) throws IOException {
        final int length = line.length();
        if (shouldWrap() && length > wrapColumn) {
            impl.print(line.subSequence(0, wrapColumn));
            impl.println();
            int pos = wrapColumn;
            while (pos < length) {
                final int writeLength = Math.min(wrapColumn - 1, length - pos);
                impl.print(" ");
                impl.print(line.subSequence(pos, pos + writeLength));
                impl.println();
                pos += wrapColumn - 1;
            }
        } else {
            impl.print(line);
            impl.println();
        }
    }
 
    private boolean needsBase64Encoding(final ByteSequence bytes) {
        final int length = bytes.length();
        if (length == 0) {
            return false;
        }
 
        /*
         * If the value starts with a space, colon, or less than, then it needs
         * to be base64 encoded.
         */
        switch (bytes.byteAt(0)) {
        case 0x20: // Space
        case 0x3A: // Colon
        case 0x3C: // Less-than
            return true;
        }
 
        /*
         * If the value ends with a space, then it needs to be base64 encoded.
         */
        if (length > 1 && bytes.byteAt(length - 1) == 0x20) {
            return true;
        }
 
        /*
         * If the value contains a null, newline, or return character, then it
         * needs to be base64 encoded.
         */
        byte b;
        for (int i = 0; i < bytes.length(); i++) {
            b = bytes.byteAt(i);
            if (b > 127 || b < 0) {
                return true;
            }
 
            switch (b) {
            case 0x00: // Null
            case 0x0A: // New line
            case 0x0D: // Carriage return
                return true;
            }
        }
 
        /* If we've made it here, then there's no reason to base64 encode. */
        return false;
    }
 
    private boolean shouldWrap() {
        return wrapColumn > 1;
    }
 
    @SuppressWarnings("unused")
    private void writeKeyAndURL(final CharSequence key, final CharSequence url) throws IOException {
        builder.setLength(0);
        builder.append(key);
        builder.append(":: ");
        builder.append(url);
        writeLine(builder);
    }
}