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