1 package org
.argeo
.naming
;
3 import java
.io
.IOException
;
4 import java
.io
.OutputStream
;
5 import java
.io
.OutputStreamWriter
;
7 import java
.nio
.charset
.Charset
;
8 import java
.nio
.charset
.StandardCharsets
;
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 static Charset DEFAULT_CHARSET
= StandardCharsets
.UTF_8
;
24 private final Writer writer
;
26 /** Writer must be closed by caller */
27 public LdifWriter(Writer writer
) {
31 /** Stream must be closed by caller */
32 public LdifWriter(OutputStream out
) {
33 this(new OutputStreamWriter(out
, DEFAULT_CHARSET
));
36 public void writeEntry(LdapName name
, Attributes attributes
) throws IOException
{
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
);
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
);
57 } catch (NamingException e
) {
58 throw new UserDirectoryException("Cannot write LDIF", e
);
62 public void write(Map
<LdapName
, Attributes
> entries
) throws IOException
{
63 for (LdapName dn
: entries
.keySet())
64 writeEntry(dn
, entries
.get(dn
));
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');
74 writer
.append(attribute
.getID()).append(": ").append(value
.toString()).append('\n');