1 package org
.argeo
.naming
;
3 import java
.io
.IOException
;
4 import java
.io
.OutputStream
;
5 import java
.io
.OutputStreamWriter
;
7 import java
.util
.Base64
;
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
;
17 import org
.argeo
.osgi
.useradmin
.UserDirectoryException
;
19 /** Basic LDIF writer */
20 public class LdifWriter
{
21 private final Writer writer
;
23 /** Writer must be closed by caller */
24 public LdifWriter(Writer writer
) {
28 /** Stream must be closed by caller */
29 public LdifWriter(OutputStream out
) {
30 this(new OutputStreamWriter(out
));
33 public void writeEntry(LdapName name
, Attributes attributes
) throws IOException
{
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
);
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
);
54 } catch (NamingException e
) {
55 throw new UserDirectoryException("Cannot write LDIF", e
);
59 public void write(Map
<LdapName
, Attributes
> entries
) throws IOException
{
60 for (LdapName dn
: entries
.keySet())
61 writeEntry(dn
, entries
.get(dn
));
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');
71 writer
.append(attribute
.getID()).append(':').append(value
.toString()).append('\n');