Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/util/LDIF.java

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is mozilla.org code.
17 *
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 1999
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38 package org.ietf.ldap.util;
39
40 import java.io.BufferedReader;
41 import java.io.DataInputStream;
42 import java.io.File;
43 import java.io.FileInputStream;
44 import java.io.IOException;
45 import java.io.InputStreamReader;
46 import java.io.PrintWriter;
47 import java.io.Serializable;
48 import java.net.MalformedURLException;
49 import java.net.URL;
50 import java.util.Enumeration;
51 import java.util.Hashtable;
52 import java.util.StringTokenizer;
53 import java.util.Vector;
54
55 import org.ietf.ldap.LDAPAttribute;
56 import org.ietf.ldap.LDAPControl;
57 import org.ietf.ldap.LDAPModification;
58
59 /**
60 * LDAP Data Interchange Format (LDIF) is a file format used to
61 * import and export directory data from an LDAP server and to
62 * describe a set of changes to be applied to data in a directory.
63 * This format is described in the Internet draft
64 * <A HREF="ftp://ftp.ietf.org/internet-drafts/draft-good-ldap-ldif-00.txt"
65 * TARGET="_blank">The LDAP Data Interchange Format (LDIF) -
66 * Technical Specification</A>.
67 * <P>
68 *
69 * This class implements an LDIF file parser. You can construct
70 * an object of this class to parse data in LDIF format and
71 * manipulate the data as individual <CODE>LDIFRecord</CODE> objects.
72 * <P>
73 *
74 * @version 1.0
75 * @see org.ietf.ldap.util.LDIFRecord
76 */
77 public class LDIF implements Serializable {
78
79 /**
80 * Internal constants
81 */
82 private final static char COMMENT = '#';
83 static final long serialVersionUID = -2710382547996750924L;
84
85 /**
86 * Constructs an <CODE>LDIF</CODE> object to parse the
87 * LDAP data read from stdin.
88 * @exception IOException An I/O error has occurred.
89 */
90 public LDIF() throws IOException {
91 DataInputStream ds = new DataInputStream(System.in);
92 BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8"));
93 m_reader = new LineReader(d);
94 m_source = "System.in";
95 m_decoder = new MimeBase64Decoder();
96 }
97
98 /**
99 * Constructs an <CODE>LDIF</CODE> object to parse the
100 * LDIF data read from a specified file.
101 * @param file the name of the LDIF file to parse
102 * @exception IOException An I/O error has occurred.
103 */
104 public LDIF(String file) throws IOException {
105 FileInputStream fs = new FileInputStream(file);
106 DataInputStream ds = new DataInputStream(fs);
107 BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8"));
108 m_reader = new LineReader(d);
109 m_source = file;
110 m_decoder = new MimeBase64Decoder();
111 }
112
113 /**
114 * Constructs an <CODE>LDIF</CODE> object to parse the
115 * LDIF data read from an input stream.
116 * @param dstThe input stream providing the LDIF data
117 * @exception IOException An I/O error has occurred.
118 */
119 public LDIF(DataInputStream ds) throws IOException {
120 BufferedReader d = new BufferedReader(new InputStreamReader(ds, "UTF8"));
121 m_reader = new LineReader(d);
122 m_source = ds.toString();
123 m_decoder = new MimeBase64Decoder();
124 }
125
126 /**
127 * Returns the next record in the LDIF data. You can call this
128 * method repeatedly to iterate through all records in the LDIF data.
129 * <P>
130 *
131 * @return the next record as an <CODE>LDIFRecord</CODE>
132 * object or null if there are no more records.
133 * @exception IOException An I/O error has occurred.
134 * @see org.ietf.ldap.util.LDIFRecord
135 */
136 public LDIFRecord nextRecord() throws IOException {
137 if ( m_done )
138 return null;
139 else
140 return parse_ldif_record( m_reader );
141 }
142
143 /**
144 * Parses ldif content. The list of attributes is
145 * terminated by \r\n or '-'. This function is
146 * also used to parse the attributes in modifications.
147 * @param ds data input stream
148 */
149 private LDIFRecord parse_ldif_record(LineReader d)
150 throws IOException {
151 String line = null;
152 String dn = null;
153 LDIFRecord rec = null;
154
155 // Skip past any blank lines
156 while( ((line = d.readLine()) != null) &&
157 (line.length() < 1) ) {
158 }
159 if (line == null) {
160 return null;
161 }
162
163 if (line.startsWith("version:")) {
164 m_version = Integer.parseInt(
165 line.substring("version:".length()).trim() );
166 if ( m_version != 1 ) {
167 throwLDIFException( "Unexpected " + line );
168 }
169 // Do the next record
170 line = d.readLine();
171 if ( (line != null) && (line.length() == 0) ) {
172 // Skip the newline
173 line = d.readLine();
174 }
175 if (line == null) {
176 return null;
177 }
178 }
179
180 if (!line.startsWith("dn:"))
181 throwLDIFException("expecting dn:");
182 dn = line.substring(3).trim();
183 if (dn.startsWith(":") && (dn.length() > 1)) {
184 String substr = dn.substring(1).trim();
185 dn = new String(getDecodedBytes(substr), "UTF8");
186 }
187
188 LDIFContent content = parse_ldif_content(d);
189 rec = new LDIFRecord(dn, content);
190 return rec;
191 }
192
193 /**
194 * Parses ldif content. The list of attributes is
195 * terminated by \r\n or '-'. This function is
196 * also used to parse the attributes in modifications.
197 * @param ds data input stream
198 */
199 private LDIFContent parse_ldif_content(LineReader d)
200 throws IOException {
201 String line = d.readLine();
202 if ((line == null) || (line.length() < 1) || (line.equals("-"))) {
203 // if this is empty line, then we're finished reading all
204 // the info for the current entry
205 if ((line != null) && (line.length() < 1)) {
206 m_currEntryDone = true;
207 }
208 return null;
209 }
210
211 if (line.startsWith("changetype:")) {
212 /* handles (changerecord) */
213 LDIFContent lc = null;
214 String changetype = line.substring(11).trim();
215 if (changetype.equals("modify")) {
216 lc = parse_mod_spec(d);
217 } else if (changetype.equals("add")) {
218 lc = parse_add_spec(d);
219 } else if (changetype.equals("delete")) {
220 lc = parse_delete_spec(d);
221 } else if (changetype.equals("moddn") ||
222 changetype.equals("modrdn")) {
223 lc = parse_moddn_spec(d);
224 } else {
225 throwLDIFException("change type not supported");
226 }
227 return lc;
228 }
229
230 /* handles 1*(attrval-spec) */
231 Hashtable<String, LDAPAttribute> ht = new Hashtable<>();
232 String newtype = null;
233 Object val = null;
234 LDAPAttribute newAttr = null;
235 Vector<LDAPControl> controlVector = null;
236
237 /* Read lines until we're past the record */
238 while( true ) {
239 if (line.startsWith("control:")) {
240 if ( controlVector == null ) {
241 controlVector = new Vector<>();
242 }
243 controlVector.addElement( parse_control_spec( line ) );
244 } else {
245 /* An attribute */
246 int len = line.length();
247 if ( len < 1 ) {
248 break;
249 }
250 int idx = line.indexOf(':');
251 /* Must have a colon */
252 if (idx == -1)
253 throwLDIFException("no ':' found");
254 /* attribute type */
255 newtype = line.substring(0,idx).toLowerCase();
256 val = "";
257 /* Could be :: for binary */
258 idx++;
259 if ( len > idx ) {
260 if ( line.charAt(idx) == ':' ) {
261 idx++;
262 String substr = line.substring(idx).trim();
263 val = getDecodedBytes(substr);
264 } else if (line.charAt(idx) == '<') {
265 try {
266 URL url =
267 new URL(line.substring(idx+1).trim());
268 String filename = url.getFile();
269 val = getFileContent(filename);
270 } catch (MalformedURLException ex) {
271 throwLDIFException(
272 ex +
273 ": cannot construct url "+
274 line.substring(idx+1).trim());
275 }
276 } else {
277 val = line.substring(idx).trim();
278 }
279 }
280 /* Is there a previous value for this attribute? */
281 newAttr = ht.get( newtype );
282 if ( newAttr == null ) {
283 newAttr = new LDAPAttribute( newtype );
284 }
285 if ( val instanceof String ) {
286 newAttr.addValue( (String)val );
287 } else {
288 newAttr.addValue( (byte[])val );
289 }
290 ht.put( newtype, newAttr );
291 }
292 line = d.readLine();
293 if (line == null || (line.length() < 1) ||
294 (line.equals("-"))) {
295 if ((line != null) && (line.length() < 1)) {
296 m_currEntryDone = true;
297 }
298 break;
299 }
300 }
301 LDIFAttributeContent ac = new LDIFAttributeContent();
302 // Copy over the attributes to the record
303 Enumeration<LDAPAttribute> en = ht.elements();
304 while( en.hasMoreElements() ) {
305 ac.addElement( en.nextElement() );
306 }
307 ht.clear();
308 if( controlVector != null ) {
309 LDAPControl[] controls =
310 new LDAPControl[controlVector.size()];
311 controlVector.copyInto( controls );
312 ac.setControls( controls );
313 controlVector.removeAllElements();
314 }
315 return ac;
316 }
317
318 private byte[] getDecodedBytes(String line) {
319 ByteBuf inBuf = new ByteBuf(line);
320 ByteBuf decodedBuf = new ByteBuf();
321 /* Translate from base 64 */
322 m_decoder.translate( inBuf, decodedBuf );
323 return decodedBuf.toBytes();
324 }
325
326 private byte[] getFileContent(String url) throws IOException {
327 StringTokenizer tokenizer = new StringTokenizer(url, "|");
328 String filename = url;
329 int num = tokenizer.countTokens();
330 if (num == 2) {
331 String token = (String)tokenizer.nextElement();
332 int index = token.lastIndexOf("/");
333 String drive = token.substring(index+1);
334 token = (String)tokenizer.nextElement();
335 token = token.replace('/', '\\');
336 filename = drive+":"+token;
337 }
338
339 File file = new File(filename);
340 byte[] b = new byte[(int)file.length()];
341 try (FileInputStream fi = new FileInputStream(filename)) {
342 fi.read(b);
343 }
344 return b;
345 }
346
347 /**
348 * Parses add content
349 * @param ds data input stream
350 */
351 private LDIFAddContent parse_add_spec(LineReader d)
352 throws IOException {
353 LDIFAttributeContent ac = (LDIFAttributeContent)parse_ldif_content(d);
354 if (m_currEntryDone)
355 m_currEntryDone = false;
356 LDAPAttribute attrs[] = ac.getAttributes();
357 LDIFAddContent rc = new LDIFAddContent(attrs);
358 LDAPControl[] controls = ac.getControls();
359 if ( controls != null ) {
360 rc.setControls( controls );
361 }
362 return rc;
363 }
364
365 /**
366 * Parses delete content
367 * @param ds data input stream
368 */
369 private LDIFDeleteContent parse_delete_spec(LineReader d)
370 throws IOException {
371 Vector<LDAPControl> controlVector = null;
372 LDIFDeleteContent dc = new LDIFDeleteContent();
373 String line = d.readLine();
374 while( line != null && !line.equals("") ) {
375 if (line.startsWith("control:")) {
376 if ( controlVector == null ) {
377 controlVector = new Vector<>();
378 }
379 controlVector.addElement( parse_control_spec( line ) );
380 } else {
381 throwLDIFException("invalid SEP" );
382 }
383 line = d.readLine();
384 }
385 if( controlVector != null ) {
386 LDAPControl[] controls = new LDAPControl[controlVector.size()];
387 controlVector.copyInto( controls );
388 dc.setControls( controls );
389 controlVector.removeAllElements();
390 }
391
392 return dc;
393 }
394
395 /**
396 * Parses change modification.
397 * @param ds data input stream
398 */
399 private LDIFModifyContent parse_mod_spec(LineReader d)
400 throws IOException {
401
402 Vector<LDAPControl> controlVector = null;
403 String line = null;
404 line = d.readLine();
405 LDIFModifyContent mc = new LDIFModifyContent();
406 do {
407 int oper = -1;
408 if (line.startsWith("add:")) {
409 oper = LDAPModification.ADD;
410 } else if (line.startsWith("delete:")) {
411 oper = LDAPModification.DELETE;
412 } else if (line.startsWith("replace:")) {
413 oper = LDAPModification.REPLACE;
414 } else
415 throwLDIFException("unknown modify type");
416
417 LDIFAttributeContent ac =
418 (LDIFAttributeContent)parse_ldif_content(d);
419 if (ac != null) {
420 LDAPAttribute attrs[] = ac.getAttributes();
421 for (int i = 0; i < attrs.length; i++) {
422 LDAPModification mod = new LDAPModification(oper, attrs[i]);
423 mc.addElement( mod );
424 }
425 LDAPControl[] controls = ac.getControls();
426 if ( controls != null ) {
427 if ( controlVector == null ) {
428 controlVector = new Vector<>();
429 }
430 for( int i = 0; i < controls.length; i++ ) {
431 controlVector.addElement( controls[i] );
432 }
433 }
434 // if there is no attrval-spec, go into the else statement
435 } else {
436 int index = line.indexOf(":");
437 if (index == -1)
438 throwLDIFException("colon missing in "+line);
439
440 String attrName = line.substring(index+1).trim();
441
442 if (oper == LDAPModification.ADD)
443 throwLDIFException("add operation needs the value for attribute "+attrName);
444 LDAPAttribute attr = new LDAPAttribute(attrName);
445 LDAPModification mod = new LDAPModification(oper, attr);
446 mc.addElement(mod);
447 }
448 if (m_currEntryDone) {
449 m_currEntryDone = false;
450 break;
451 }
452 line = d.readLine();
453 } while (line != null && !line.equals(""));
454
455 if( controlVector != null ) {
456 LDAPControl[] controls = new LDAPControl[controlVector.size()];
457 controlVector.copyInto( controls );
458 mc.setControls( controls );
459 controlVector.removeAllElements();
460 }
461 return mc;
462 }
463
464 /**
465 * Parses moddn/modrdn modification.
466 * @param d data input stream
467 */
468 private LDIFModDNContent parse_moddn_spec(LineReader d)
469 throws IOException {
470 Vector<LDAPControl> controlVector = null;
471 String line = null;
472 line = d.readLine();
473 LDIFModDNContent mc = new LDIFModDNContent();
474 String val = null;
475 do {
476 if (line.startsWith("newrdn:") &&
477 (line.length() > ("newrdn:".length()+1))) {
478 mc.setRDN(line.substring("newrdn:".length()).trim());
479 } else if (line.startsWith("deleteoldrdn:") &&
480 (line.length() > ("deleteoldrdn:".length()+1))) {
481 String str = line.substring("deleteoldrdn:".length()).trim();
482 if (str.equals("0"))
483 mc.setDeleteOldRDN(false);
484 else if (str.equals("1"))
485 mc.setDeleteOldRDN(true);
486 else
487 throwLDIFException("Incorrect input for deleteOldRdn ");
488 } else if (line.startsWith("newsuperior:") &&
489 (line.length() > ("newsuperior:".length()+1))) {
490 mc.setNewParent(line.substring(
491 "newsuperior:".length()).trim());
492 } else if (line.startsWith("newparent:") &&
493 (line.length() > ("newparent:".length()+1))) {
494 mc.setNewParent(line.substring(
495 "newparent:".length()).trim());
496 } else if (line.startsWith("control:")) {
497 if ( controlVector == null ) {
498 controlVector = new Vector<>();
499 }
500 controlVector.addElement( parse_control_spec( line ) );
501 }
502 line = d.readLine();
503 } while (line != null && !line.equals(""));
504
505 if( controlVector != null ) {
506 LDAPControl[] controls = new LDAPControl[controlVector.size()];
507 controlVector.copyInto( controls );
508 mc.setControls( controls );
509 controlVector.removeAllElements();
510 }
511
512 return mc;
513 }
514
515 /**
516 * Parses the specification of a control<BR>
517 *
518 * A control looks line one of the following:
519 *<BR>
520 * control: 1.2.3.4.10.210
521 *<BR>
522 * control: 1.2.3.4.10.210 true
523 *<BR>
524 * control: 1.2.3.4.10.210 true: someASCIIvalue
525 *<BR>
526 * control: 1.2.3.4.10.210: someASCIIvalue
527 *<BR>
528 * control: 1.2.3.4.10.210 true:: 44GK44GM44GV44KP44KJ
529 *<BR>
530 * control: 1.2.3.4.10.210:: 44GK44GM44GV44KP44KJ
531 *<BR>
532 * control: 1.2.3.4.10.210 true:< file:///usr/local/directory/cont.dta
533 *<BR>
534 * control: 1.2.3.4.10.210:< file:///usr/local/directory/cont.dta
535 *
536 * @param line a line containing a control spec
537 * @return a parsed control.
538 * @exception IOException if the line could not be parsed
539 */
540 protected LDAPControl parse_control_spec( String line )
541 throws IOException {
542 boolean criticality = true;
543 String OID;
544 byte[] val = null;
545 int len = line.length();
546 int idx = line.indexOf(':') + 2;
547 /* OID, must be present */
548 if ( idx >= len ) {
549 throwLDIFException("OID required for control");
550 }
551 line = line.substring(idx).trim();
552 idx = line.indexOf(' ');
553 if ( idx < 0 ) {
554 OID = line;
555 } else {
556 /* Optional criticality */
557 OID = line.substring(0, idx);
558 line = line.substring(idx+1);
559 idx = line.indexOf(':');
560 String criticalVal;
561 if (idx > 0) {
562 criticalVal = line.substring(0, idx);
563 } else {
564 criticalVal = line;
565 }
566 if ( criticalVal.compareTo("true") == 0 ) {
567 criticality = true;
568 } else if ( criticalVal.compareTo("false") == 0 ) {
569 criticality = false;
570 } else {
571 throwLDIFException(
572 "Criticality for control must be true" +
573 " or false, not " + criticalVal);
574 }
575 /* Optional value */
576 if ( idx > 0 ) {
577 /* Could be :: for binary */
578 idx++;
579 if ( line.length() > idx ) {
580 if ( line.charAt(idx) == ':' ) {
581 idx++;
582 line = line.substring(idx).trim();
583 val = getDecodedBytes(line);
584 } else if (line.charAt(idx) == '<') {
585 String urlString = line.substring(idx+1).trim();
586 try {
587 URL url = new URL(urlString);
588 String filename = url.getFile();
589 val = getFileContent(filename);
590 } catch (MalformedURLException ex) {
591 throwLDIFException(
592 ex + ": cannot construct url "+
593 urlString);
594 }
595 } else {
596 try {
597 val = line.substring(idx).trim().getBytes("UTF8");
598 } catch(Exception x) {
599 }
600 }
601 }
602 }
603 }
604 return new LDAPControl( OID, criticality, val );
605 }
606
607 /**
608 * Returns true if all the bytes in the given array are valid for output as a
609 * String according to the LDIF specification. If not, the array should
610 * output base64-encoded.
611 * @return <code>true</code> if all the bytes in the given array are valid for
612 * output as a String according to the LDIF specification; otherwise,
613 * <code>false</code>.
614 */
615 public static boolean isPrintable(byte[] b) {
616 for( int i = b.length - 1; i >= 0; i-- ) {
617 if ( (b[i] < ' ') || (b[i] > 127) ) {
618 if ( b[i] != '\t' )
619 return false;
620 }
621 }
622 return true;
623 }
624
625 /**
626 * Outputs the String in LDIF line-continuation format. No line will be longer
627 * than the given max. A continuation line starts with a single blank space.
628 * @param pw the printer writer
629 * @param value the given string being printed out
630 * @param max the maximum characters allowed in the line
631 */
632 public static void breakString( PrintWriter pw, String value, int max) {
633 int leftToGo = value.length();
634 int written = 0;
635 int maxChars = max;
636 /* Limit to 77 characters per line */
637 while( leftToGo > 0 ) {
638 int toWrite = Math.min( maxChars, leftToGo );
639 String s = value.substring( written, written+toWrite);
640 if ( written != 0 ) {
641 pw.print( " " + s );
642 } else {
643 pw.print( s );
644 maxChars -= 1;
645 }
646 written += toWrite;
647 leftToGo -= toWrite;
648 /* Don't use pw.println, because it outputs an extra CR
649 in Win32 */
650 pw.print( '\n' );
651 }
652 }
653
654 /**
655 * Gets the version of LDIF used in the data.
656 * @return version of LDIF used in the data.
657 */
658 public int getVersion() {
659 return m_version;
660 }
661
662 /**
663 * Gets the string representation of the
664 * entire LDIF file.
665 * @return the string representation of the entire LDIF data file.
666 */
667 public String toString() {
668 return "LDIF {" + m_source + "}";
669 }
670
671 /**
672 * Throws a LDIF file exception including the current line number.
673 * @param msg Error message
674 */
675 protected void throwLDIFException(String msg)throws IOException {
676 throw new IOException ("line " +
677 (m_currLineNum-m_continuationLength) + ": " + msg);
678 }
679
680 /**
681 * Internal variables
682 */
683 private int m_version = 1;
684 private boolean m_done = false;
685 private LineReader m_reader = null;
686 private String m_source = null;
687 private MimeBase64Decoder m_decoder = null;
688 private boolean m_currEntryDone = false;
689 private int m_currLineNum;
690 private int m_continuationLength;
691
692 /* Concatenate continuation lines, if present */
693 class LineReader {
694 LineReader( BufferedReader d ) {
695 _d = d;
696 }
697 /**
698 * Reads a non-comment line.
699 * @return a string or null.
700 */
701 String readLine() throws IOException {
702 String line = null;
703 String result = null;
704 int readCnt = 0, continuationLength = 0;
705 do {
706 /* Leftover line from last time? */
707 if ( _next != null ) {
708 line = _next;
709 _next = null;
710 } else {
711 line = _d.readLine();
712 }
713 if (line != null) {
714 readCnt++;
715 /* Empty line means end of record */
716 if( line.length() < 1 ) {
717 if ( result == null )
718 result = line;
719 else {
720 _next = line;
721 break;
722 }
723 } else if( line.charAt(0) == COMMENT ) {
724 /* Ignore comment lines */
725 } else if( line.charAt(0) != ' ' ) {
726 /* Not a continuation line */
727 if( result == null ) {
728 result = line;
729 } else {
730 _next = line;
731 break;
732 }
733 } else {
734 /* Continuation line */
735 if ( result == null ) {
736 m_currLineNum += readCnt;
737 throwLDIFException("continuation out of nowhere");
738 }
739 result += line.substring(1);
740 continuationLength++;
741 }
742 } else {
743 /* End of file */
744 break;
745 }
746 } while ( true );
747
748 m_done = ( line == null );
749
750 m_currLineNum += readCnt;
751 if (_next != null) {
752 // read one line ahead
753 m_currLineNum--;
754 }
755 m_continuationLength = continuationLength;
756
757 return result;
758 }
759 private BufferedReader _d;
760 String _next = null;
761 }
762
763 /**
764 * Converts a byte array to a printable string following
765 * the LDIF rules (encode in base64 if necessary)
766 *
767 * @param b the byte array to convert
768 * @return a converted string which is printable.
769 */
770 public static String toPrintableString( byte[] b ) {
771 String s = "";
772 if (isPrintable(b)) {
773 try {
774 s = new String(b, "UTF8");
775 } catch ( java.io.UnsupportedEncodingException e ) {
776 }
777 } else {
778 ByteBuf inBuf = new ByteBuf( b, 0, b.length );
779 ByteBuf encodedBuf = new ByteBuf();
780 // Translate to base 64
781 MimeBase64Encoder encoder = new MimeBase64Encoder();
782 encoder.translate( inBuf, encodedBuf );
783 int nBytes = encodedBuf.length();
784 if ( nBytes > 0 ) {
785 s = new String(encodedBuf.toBytes(), 0, nBytes);
786 }
787 }
788 return s;
789 }
790
791 /**
792 * Test driver - just reads and parses an LDIF file, printing
793 * each record as interpreted
794 *
795 * @param args name of the LDIF file to parse
796 */
797 public static void main( String[] args ) {
798 if ( args.length != 1 ) {
799 System.out.println( "Usage: java LDIF <FILENAME>" );
800 System.exit( 1 );
801 }
802 LDIF ldif = null;
803 try {
804 ldif = new LDIF( args[0] );
805 } catch (Exception e) {
806 System.err.println("Failed to read LDIF file " + args[0] +
807 ", " + e.toString());
808 System.exit(1);
809 }
810 try {
811 for( LDIFRecord rec = ldif.nextRecord();
812 rec != null; rec = ldif.nextRecord() ) {
813 System.out.println( rec.toString() + '\n' );
814 }
815 } catch ( IOException ex ) {
816 System.out.println( ex );
817 System.exit( 1 );
818 }
819 System.exit( 0 );
820 }
821 }