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
;
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
;
18 import org
.argeo
.osgi
.useradmin
.UserDirectoryException
;
20 /** Basic LDIF writer */
21 public class LdifWriter
{
22 private final Writer writer
;
24 /** Writer must be closed by caller */
25 public LdifWriter(Writer writer
) {
29 /** Stream must be closed by caller */
30 public LdifWriter(OutputStream out
) {
31 this(new OutputStreamWriter(out
));
34 public void writeEntry(LdapName name
, Attributes attributes
) throws IOException
{
37 Rdn nameRdn
= name
.getRdn(name
.size() - 1);
38 Attribute nameAttr
= attributes
.get(nameRdn
.getType());
39 if (!nameAttr
.get().equals(nameRdn
.getValue()))
40 throw new UserDirectoryException(
41 "Attribute " + nameAttr
.getID() + "=" + nameAttr
.get() + " not consistent with DN " + name
);
43 writer
.append(dn
.name() + ":").append(name
.toString()).append('\n');
44 Attribute objectClassAttr
= attributes
.get("objectClass");
45 if (objectClassAttr
!= null)
46 writeAttribute(objectClassAttr
);
47 for (NamingEnumeration
<?
extends Attribute
> attrs
= attributes
.getAll(); attrs
.hasMore();) {
48 Attribute attribute
= attrs
.next();
49 if (attribute
.getID().equals(dn
.name()) || attribute
.getID().equals("objectClass"))
50 continue;// skip DN attribute
51 writeAttribute(attribute
);
55 } catch (NamingException e
) {
56 throw new UserDirectoryException("Cannot write LDIF", e
);
60 protected void writeAttribute(Attribute attribute
) throws NamingException
, IOException
{
61 for (NamingEnumeration
<?
> attrValues
= attribute
.getAll(); attrValues
.hasMore();) {
62 Object value
= attrValues
.next();
63 if (value
instanceof byte[]) {
64 String encoded
= Base64
.encodeBase64String((byte[]) value
);
65 writer
.append(attribute
.getID()).append("::").append(encoded
).append('\n');
67 writer
.append(attribute
.getID()).append(':').append(value
.toString()).append('\n');