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