1 package org
.argeo
.osgi
.useradmin
;
3 import static org
.argeo
.osgi
.useradmin
.LdifName
.dn
;
5 import java
.io
.IOException
;
6 import java
.io
.OutputStream
;
7 import java
.io
.OutputStreamWriter
;
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
.apache
.commons
.codec
.binary
.Base64
;
19 /** Basic LDIF writer */
21 private final Writer writer
;
23 LdifWriter(OutputStream out
) {
24 this.writer
= new OutputStreamWriter(out
);
27 void writeEntry(LdapName name
, Attributes attributes
) throws IOException
{
30 Rdn nameRdn
= name
.getRdn(name
.size() - 1);
31 Attribute nameAttr
= attributes
.get(nameRdn
.getType());
32 if (!nameAttr
.get().equals(nameRdn
.getValue()))
33 throw new UserDirectoryException("Attribute "
34 + nameAttr
.getID() + "=" + nameAttr
.get()
35 + " not consistent with DN " + name
);
37 writer
.append(dn
.name() + ":").append(name
.toString()).append('\n');
38 Attribute objectClassAttr
= attributes
.get("objectClass");
39 if (objectClassAttr
!= null)
40 writeAttribute(objectClassAttr
);
41 for (NamingEnumeration
<?
extends Attribute
> attrs
= attributes
42 .getAll(); attrs
.hasMore();) {
43 Attribute attribute
= attrs
.next();
44 if (attribute
.getID().equals(dn
.name())
45 || attribute
.getID().equals("objectClass"))
46 continue;// skip DN attribute
47 writeAttribute(attribute
);
51 } catch (NamingException e
) {
52 throw new UserDirectoryException("Cannot write LDIF", e
);
56 private void writeAttribute(Attribute attribute
) throws NamingException
,
58 for (NamingEnumeration
<?
> attrValues
= attribute
.getAll(); attrValues
60 Object value
= attrValues
.next();
61 if (value
instanceof byte[]) {
62 String encoded
= Base64
.encodeBase64String((byte[]) value
);
63 writer
.append(attribute
.getID()).append("::").append(encoded
)
66 writer
.append(attribute
.getID()).append(':')
67 .append(value
.toString()).append('\n');