1 package org
.argeo
.util
.naming
;
3 import static org
.argeo
.osgi
.useradmin
.LdifName
.dn
;
5 import java
.io
.IOException
;
6 import java
.io
.OutputStream
;
7 import java
.io
.OutputStreamWriter
;
9 import java
.util
.Base64
;
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
;
19 import org
.argeo
.osgi
.useradmin
.UserDirectoryException
;
21 /** Basic LDIF writer */
22 public class LdifWriter
{
23 private final Writer writer
;
25 /** Writer must be closed by caller */
26 public LdifWriter(Writer writer
) {
30 /** Stream must be closed by caller */
31 public LdifWriter(OutputStream out
) {
32 this(new OutputStreamWriter(out
));
35 public void writeEntry(LdapName name
, Attributes attributes
) throws IOException
{
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
);
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
);
56 } catch (NamingException e
) {
57 throw new UserDirectoryException("Cannot write LDIF", e
);
61 public void write(Map
<LdapName
, Attributes
> entries
) throws IOException
{
62 for (LdapName dn
: entries
.keySet())
63 writeEntry(dn
, entries
.get(dn
));
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');
73 writer
.append(attribute
.getID()).append(':').append(value
.toString()).append('\n');