]> git.argeo.org Git - lgpl/argeo-commons.git/blob - useradmin/LdifWriter.java
Prepare next development cycle
[lgpl/argeo-commons.git] / useradmin / LdifWriter.java
1 package org.argeo.osgi.useradmin;
2
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.io.OutputStreamWriter;
6 import java.io.Writer;
7
8 import javax.naming.NamingEnumeration;
9 import javax.naming.NamingException;
10 import javax.naming.directory.Attribute;
11 import javax.naming.directory.Attributes;
12 import javax.naming.ldap.LdapName;
13
14 import org.apache.commons.codec.binary.Base64;
15
16 /** Basic LDIF writer */
17 public class LdifWriter {
18 private final Writer writer;
19
20 public LdifWriter(OutputStream out) {
21 this.writer = new OutputStreamWriter(out);
22 }
23
24 void writeEntry(LdapName name, Attributes attributes) throws IOException {
25 try {
26 // TODO check consistency of DN with attributes
27 writer.append("dn:").append(name.toString()).append('\n');
28 Attribute objectClassAttr = attributes.get("objectClass");
29 if (objectClassAttr != null)
30 writeAttribute(objectClassAttr);
31 for (NamingEnumeration<? extends Attribute> attrs = attributes
32 .getAll(); attrs.hasMore();) {
33 Attribute attribute = attrs.next();
34 if (attribute.getID().equals("dn")
35 || attribute.getID().equals("objectClass"))
36 continue;// skip DN attribute
37 writeAttribute(attribute);
38 }
39 writer.append('\n');
40 writer.flush();
41 } catch (NamingException e) {
42 throw new ArgeoUserAdminException("Cannot write LDIF", e);
43 }
44 }
45
46 private void writeAttribute(Attribute attribute) throws NamingException,
47 IOException {
48 for (NamingEnumeration<?> attrValues = attribute.getAll(); attrValues
49 .hasMore();) {
50 Object value = attrValues.next();
51 if (value instanceof byte[]) {
52 String encoded = Base64.encodeBase64String((byte[]) value);
53 writer.append(attribute.getID()).append("::").append(encoded)
54 .append('\n');
55 } else {
56 writer.append(attribute.getID()).append(':')
57 .append(value.toString()).append('\n');
58 }
59 }
60 }
61 }