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