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