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