Example usage for javax.naming.directory BasicAttributes BasicAttributes

List of usage examples for javax.naming.directory BasicAttributes BasicAttributes

Introduction

In this page you can find the example usage for javax.naming.directory BasicAttributes BasicAttributes.

Prototype

public BasicAttributes() 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Compares two attribute sets// www .j  ava 2 s .  c o m
 * 
 * @param authoritativeSet
 *            reference set
 * @param compareSet
 *            comparative set
 * @return list of modifications to commit
 * @throws NamingException
 */
public Map<String, Attributes> compareAttributeSets(Attributes authoritativeSet, Attributes compareSet)
        throws NamingException {

    Map<String, Attributes> modifications = new HashMap<String, Attributes>();
    Attributes delAttributes = new BasicAttributes();
    Attributes addAttributes = new BasicAttributes();
    Attributes replaceAttributes = new BasicAttributes();
    // List<LDAPModification> modifications = new
    // ArrayList<LDAPModification>();
    List<String> supportedAttrs = Arrays.asList(getSupportedAttributes());

    Iterator<String> it = supportedAttrs.iterator();

    // loop over supported attributes
    while (it.hasNext()) {
        String attribute = it.next();

        // skip unmodifiable attrs
        if (attribute.equals("modifyTimestamp"))
            continue;

        Attribute authoritaveAttribute = authoritativeSet.get(attribute);
        Attribute compareAttribute = compareSet.get(attribute);

        if (authoritaveAttribute == null || compareAttribute == null) {
            // remove an old attribute
            if (authoritaveAttribute == null && compareAttribute != null) {
                delAttributes.put(compareAttribute);
            }

            // add a new attribute
            if (authoritaveAttribute != null && compareAttribute == null) {
                addAttributes.put(authoritaveAttribute);
            }
        } else {
            // replace an attribute
            String authValue = (String) authoritaveAttribute.get();
            String compareValue = (String) compareAttribute.get();
            if (!authValue.equals(compareValue)) {
                replaceAttributes.put(authoritaveAttribute);
            }
        }
    }
    modifications.put(DEL_ATTRIBUTE, delAttributes);
    modifications.put(REPLACE_ATTRIBUTE, replaceAttributes);
    modifications.put(ADD_ATTRIBUTE, addAttributes);

    return modifications;
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Retrieves a list of attributes from an element.
 * @param ldap/*from  w  w  w  . j  a  va2  s  .c om*/
 *            A prepared LDAP context. Cannot be <code>null</code>.
 * @param rdn
 *            The relative DN (to the DN in the LDAP context
 *            <code>ldap</code>). Cannot be <code>null</code>.
 * @param attributes
 *            The requested attribute's names. Also indirectly referenced
 *            attributes on the form
 *            <code>someReferenceAttribute:someIndirectAttribute</code>,
 *            where the DN in the reference attribute
 *            <code>someReferenceAttribute</code> is followed to look up
 *            <code>someIndirectAttribute</code> from another element.
 * @return The requested attributes (<code>String</code> names and
 *         <code>String[]</code> values), if they did exist in the
 *         external backend. Otherwise returns those attributes that could
 *         actually be read, this may be an empty <code>HashMap</code>.
 *         Returns an empty <code>HashMap</code> if
 *         <code>attributes</code> is <code>null</code> or an empty
 *         array. Note that attribute values are mapped to
 *         <code>String</code> using ISO-8859-1.
 * @throws BackendException
 *             If unable to read the attributes from the backend.
 * @throws NullPointerException
 *             If <code>ldap</code> or <code>rdn</code> is
 *             <code>null</code>.
 * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String,
 *      java.lang.String[])
 */
private HashMap<String, String[]> getAttributes(final InitialLdapContext ldap, final String rdn,
        final String[] attributes) throws BackendException {

    // Sanity checks.
    if (ldap == null)
        throw new NullPointerException("LDAP context cannot be NULL");
    if (rdn == null)
        throw new NullPointerException("RDN cannot be NULL");
    if ((attributes == null) || (attributes.length == 0))
        return new HashMap<String, String[]>();

    // Used to remember attributes to be read through references later on.
    Hashtable<String, Vector> attributeReferences = new Hashtable<String, Vector>();

    // Strip down request, resolving references and removing duplicates.
    Vector<String> strippedAttributeRequest = new Vector<String>();
    for (int i = 0; i < attributes.length; i++) {
        int indexOfSplitCharacter = attributes[i]
                .indexOf(DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR);
        if (indexOfSplitCharacter == -1) {

            // A regular attribute request.
            if (!strippedAttributeRequest.contains(attributes[i]))
                strippedAttributeRequest.add(attributes[i]);

        } else {

            // A referenced attribute request.
            final String referencingAttribute = attributes[i].substring(0, indexOfSplitCharacter);
            if (!strippedAttributeRequest.contains(referencingAttribute))
                strippedAttributeRequest.add(referencingAttribute);

            // Add to list of attributes to be read through each reference.
            if (!attributeReferences.containsKey(referencingAttribute)) {

                // Add new reference.
                Vector<String> referencedAttribute = new Vector<String>();
                referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));
                attributeReferences.put(referencingAttribute, referencedAttribute);

            } else {

                // Update existing reference.
                Vector<String> referencedAttribute = attributeReferences.get(referencingAttribute);
                if (!referencedAttribute.contains(attributes[i].substring(indexOfSplitCharacter + 1)))
                    referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1));

            }

        }

    }

    // The context provider URL and DN, for later logging.
    String url = "unknown backend";
    String dn = "unknown dn";

    // Get the attributes from an already initialized LDAP connection.
    Attributes rawAttributes = null;
    try {

        // Remember the URL and bind DN, for later logging.
        final Hashtable environment = ldap.getEnvironment();
        url = (String) environment.get(Context.PROVIDER_URL);
        dn = (String) environment.get(Context.SECURITY_PRINCIPAL);

        // Get the attributes.
        rawAttributes = ldap.getAttributes(rdn, strippedAttributeRequest.toArray(new String[] {}));

    } catch (NameNotFoundException e) {

        // Successful authentication but missing user element; no attributes
        // returned and the event is logged.
        log.logWarn("No LDAP element found (DN was '" + dn + "')", mySessionTicket);
        rawAttributes = new BasicAttributes();

    } catch (NamingException e) {
        String a = new String();
        for (int i = 0; i < attributes.length; i++)
            a = a + attributes[i] + ", ";
        throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '"
                + rdn + "' on '" + url + "'", e);
    }

    // Translate retrieved attributes from Attributes to HashMap.
    HashMap<String, String[]> convertedAttributes = new HashMap<String, String[]>();
    for (int i = 0; i < attributes.length; i++) {

        // Did we get any attribute back at all?
        final String requestedAttribute = attributes[i];
        Attribute rawAttribute = rawAttributes.get(requestedAttribute);
        if (rawAttribute == null) {

            // Attribute was not returned.
            log.logDebug("Requested attribute '" + requestedAttribute + "' not found on '" + url + "'",
                    mySessionTicket);

        } else {

            // Map the attribute values to String[].
            ArrayList<String> convertedAttributeValues = new ArrayList<String>(rawAttribute.size());
            for (int j = 0; j < rawAttribute.size(); j++) {
                try {

                    // We either have a String or a byte[].
                    String convertedAttributeValue = null;
                    try {

                        // Encode String.
                        convertedAttributeValue = new String(((String) rawAttribute.get(j)).getBytes(),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);
                    } catch (ClassCastException e) {

                        // Encode byte[] to String.
                        convertedAttributeValue = new String(Base64.encodeBase64((byte[]) rawAttribute.get(j)),
                                DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET);

                    }
                    convertedAttributeValues.add(convertedAttributeValue);

                } catch (NamingException e) {
                    throw new BackendException("Unable to read attribute value of '" + rawAttribute.getID()
                            + "' from '" + url + "'", e);
                } catch (UnsupportedEncodingException e) {
                    throw new BackendException(
                            "Unable to use " + DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET + " encoding",
                            e);
                }
            }
            convertedAttributes.put(requestedAttribute, convertedAttributeValues.toArray(new String[] {}));

        }

    }

    // Follow references to look up any indirectly referenced attributes.
    Enumeration<String> keys = attributeReferences.keys();
    while (keys.hasMoreElements()) {

        // Do we have a reference? 
        final String referencingAttribute = keys.nextElement();
        final String[] referencingValues = convertedAttributes.get(referencingAttribute);
        if (referencingValues == null) {

            // No reference was found in this attribute.
            log.logDebug("Found no DN references in attribute '" + referencingAttribute + "'", mySessionTicket);

        } else {

            // One (or more) references was found in this attribute.
            if (referencingValues.length > 1)
                log.logDebug("Found " + referencingValues.length + " DN references in attribute '"
                        + referencingAttribute + "'; ignoring all but first", mySessionTicket);
            log.logDebug("Following reference '" + referencingValues[0] + "' found in '" + referencingAttribute
                    + "' to look up attribute(s) '" + attributeReferences.get(referencingAttribute).toString(),
                    mySessionTicket);
            String providerURL = null; // To be used later.
            try {

                // Follow the reference.
                providerURL = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
                providerURL = providerURL.substring(0, providerURL.lastIndexOf("/") + 1) + referencingValues[0];
                ldap.addToEnvironment(Context.PROVIDER_URL, providerURL);

            } catch (NamingException e) {
                throw new BackendException("Unable to update provider URL in LDAP environment", e);
            }

            // Add any referenced attributes returned.
            HashMap additionalAttributes = getAttributes(ldap, providerURL,
                    (String[]) attributeReferences.get(referencingAttribute).toArray(new String[] {}));
            Iterator i = additionalAttributes.keySet().iterator();
            while (i.hasNext()) {
                String attributeName = (String) i.next();
                convertedAttributes.put(referencingAttribute
                        + DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR + attributeName,
                        (String[]) additionalAttributes.get(attributeName));
            }

        }

    }

    return convertedAttributes;

}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean addOrganisation(LDAPUser lus, Organization org) {
    boolean registration = false;
    DirContext ctx = null;/*  w w  w.  j  a  va  2s.c o m*/
    try {
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("organization");
        oc.add("top");
        attrsBag.put(oc);

        Attribute o = new BasicAttribute("o", org.getKey());
        attrsBag.put(o);

        Attribute description = new BasicAttribute("description", org.getDescription());
        attrsBag.put(description);

        if (org.getReference() != null && !org.getReference().isEmpty()) {
            Attribute registeredAddr = new BasicAttribute("registeredAddress", org.getReference());
            attrsBag.put(registeredAddr);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext(
                "o=" + org.getKey() + ",c=" + org.getCountryCode() + "," + rb.getString("organisationsRoot"),
                attrsBag);

        registration = true;
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return registration;

}

From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java

private BasicAttributes getBasicAttributes(List<ExtensibleObject> requestAttribute, String idField) {
    BasicAttributes attrs = new BasicAttributes();

    // add the object class
    Attribute oc = new BasicAttribute("objectclass");
    oc.add("top");

    // add the ou for this record
    Attribute ouSet = new BasicAttribute("ou");
    String ou = getOU(requestAttribute);
    log.debug("GetAttributes() - ou=" + ou);
    if (ou != null && ou.length() > 0) {
        ouSet.add(ou);/* w w w  . j a  v  a 2s .c o  m*/
    }

    // add the structural classes
    attrs.put(oc);
    attrs.put(ouSet);

    // add the identifier

    // add the attributes
    for (ExtensibleObject obj : requestAttribute) {
        List<ExtensibleAttribute> attrList = obj.getAttributes();
        for (ExtensibleAttribute att : attrList) {

            log.debug("Attr Name=" + att.getName() + " " + att.getValue());

            if (att.getName() != idField) {
                attrs.put(att.getName(), att.getValue());
            }
        }
    }

    return attrs;
}

From source file:CreateJavaSchema.java

/**
 * Inserts object class definitions from RFC 2713 into the schema.
 *
 * This method maps the LDAP schema definitions in RFC 2713 onto the
 * proprietary attributes required by the Active Directory schema.
 *
 * The resulting object class definitions differ from those of RFC 2713
 * in the following ways://from   w  ww .  j a v a  2s. c  o m
 *
 *     - Abstract and auxiliary classes are now defined as structural.
 *     - The javaObject class now inherits from javaContainer.
 *     - The javaNamingReference, javaSerializedObject and
 *       javaMarshalledObject now inherit from javaObject.
 *
 * The effect of these differences is that Java objects cannot be
 * mixed-in with other directory entries, they may only be stored as
 * stand-alone entries.
 *
 * The reason for these differences is due to the way auxiliary classes
 * are supported the Active Directory. Only the names of structural
 * classes (not auxiliary) may appear in the object class attribute of
 * an entry. Therefore, the abstract and auxiliary classes in the Java
 * schema definition are re-defined as structural.
 */
protected void insertADObjectClasses(DirContext rootCtx, DirContext schemaCtx) throws NamingException {

    System.out.println("  [inserting new object class definitions ...]");

    String dn = schemaCtx.getNameInNamespace();
    String attrID;

    attrID = new String("javaContainer");
    Attributes attrs1 = new BasicAttributes();

    attrs1.put(new BasicAttribute("objectClass", "classSchema"));
    attrs1.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs1.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.1"));
    attrs1.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs1.put(new BasicAttribute("mustContain", "cn"));
    attrs1.put(new BasicAttribute("objectClassCategory", "1"));
    attrs1.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs1.put(new BasicAttribute("subclassOf", "top"));
    attrs1.put(new BasicAttribute("possSuperiors", "top")); //any superior
    attrs1.put(new BasicAttribute("description", "Container for a Java object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs1);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // because javaObject relys on javaContainer

    attrID = new String("javaObject");
    Attributes attrs2 = new BasicAttributes();

    attrs2.put(new BasicAttribute("objectClass", "classSchema"));
    attrs2.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs2.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.4"));
    attrs2.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs2.put(new BasicAttribute("mustContain", "javaClassName"));

    Attribute joMay = new BasicAttribute("mayContain");
    joMay.add("javaClassNames");
    joMay.add("javaCodeBase");
    joMay.add("javaDoc");
    joMay.add("description");
    attrs2.put(joMay);

    attrs2.put(new BasicAttribute("objectClassCategory", "1"));
    attrs2.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs2.put(new BasicAttribute("subclassOf", "javaContainer"));
    attrs2.put(new BasicAttribute("description", "Java object representation"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs2);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // because next 3 rely on javaObject

    attrID = new String("javaSerializedObject");
    Attributes attrs3 = new BasicAttributes();

    attrs3.put(new BasicAttribute("objectClass", "classSchema"));
    attrs3.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs3.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.5"));
    attrs3.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs3.put(new BasicAttribute("mustContain", "javaSerializedData"));
    attrs3.put(new BasicAttribute("objectClassCategory", "1"));
    attrs3.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs3.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs3.put(new BasicAttribute("description", "Java serialized object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs3);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaNamingReference");
    Attributes attrs4 = new BasicAttributes();

    attrs4.put(new BasicAttribute("objectClass", "classSchema"));
    attrs4.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs4.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.7"));
    attrs4.put(new BasicAttribute("lDAPDisplayName", attrID));

    Attribute jnrMay = new BasicAttribute("mayContain");
    jnrMay.add("javaReferenceAddress");
    jnrMay.add("javaFactory");
    attrs4.put(jnrMay);

    attrs4.put(new BasicAttribute("objectClassCategory", "1"));
    attrs4.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs4.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs4.put(new BasicAttribute("description", "JNDI reference"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs4);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaMarshalledObject");
    Attributes attrs5 = new BasicAttributes();

    attrs5.put(new BasicAttribute("objectClass", "classSchema"));
    attrs5.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs5.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.8"));
    attrs5.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs5.put(new BasicAttribute("mustContain", "javaSerializedData"));
    attrs5.put(new BasicAttribute("objectClassCategory", "1"));
    attrs5.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs5.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs5.put(new BasicAttribute("description", "Java marshalled object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs5);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // finally
}

From source file:CreateJavaSchema.java

/**
 * Inserts object class definitions from RFC 2713 into the schema.
 * /*  w w  w .j a  v a 2 s .  c  o m*/
 * This method maps the LDAP schema definitions in RFC 2713 onto the
 * proprietary attributes required by the Active Directory schema.
 * 
 * The resulting object class definitions differ from those of RFC 2713 in the
 * following ways:
 *  - Abstract and auxiliary classes are now defined as structural. - The
 * javaObject class now inherits from javaContainer. - The
 * javaNamingReference, javaSerializedObject and javaMarshalledObject now
 * inherit from javaObject.
 * 
 * The effect of these differences is that Java objects cannot be mixed-in
 * with other directory entries, they may only be stored as stand-alone
 * entries.
 * 
 * The reason for these differences is due to the way auxiliary classes are
 * supported the Active Directory. Only the names of structural classes (not
 * auxiliary) may appear in the object class attribute of an entry. Therefore,
 * the abstract and auxiliary classes in the Java schema definition are
 * re-defined as structural.
 */
protected void insertADObjectClasses(DirContext rootCtx, DirContext schemaCtx) throws NamingException {

    System.out.println("  [inserting new object class definitions ...]");

    String dn = schemaCtx.getNameInNamespace();
    String attrID;

    attrID = new String("javaContainer");
    Attributes attrs1 = new BasicAttributes();

    attrs1.put(new BasicAttribute("objectClass", "classSchema"));
    attrs1.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs1.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.1"));
    attrs1.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs1.put(new BasicAttribute("mustContain", "cn"));
    attrs1.put(new BasicAttribute("objectClassCategory", "1"));
    attrs1.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs1.put(new BasicAttribute("subclassOf", "top"));
    attrs1.put(new BasicAttribute("possSuperiors", "top")); // any superior
    attrs1.put(new BasicAttribute("description", "Container for a Java object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs1);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // because javaObject relys on javaContainer

    attrID = new String("javaObject");
    Attributes attrs2 = new BasicAttributes();

    attrs2.put(new BasicAttribute("objectClass", "classSchema"));
    attrs2.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs2.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.4"));
    attrs2.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs2.put(new BasicAttribute("mustContain", "javaClassName"));

    Attribute joMay = new BasicAttribute("mayContain");
    joMay.add("javaClassNames");
    joMay.add("javaCodeBase");
    joMay.add("javaDoc");
    joMay.add("description");
    attrs2.put(joMay);

    attrs2.put(new BasicAttribute("objectClassCategory", "1"));
    attrs2.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs2.put(new BasicAttribute("subclassOf", "javaContainer"));
    attrs2.put(new BasicAttribute("description", "Java object representation"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs2);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // because next 3 rely on javaObject

    attrID = new String("javaSerializedObject");
    Attributes attrs3 = new BasicAttributes();

    attrs3.put(new BasicAttribute("objectClass", "classSchema"));
    attrs3.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs3.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.5"));
    attrs3.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs3.put(new BasicAttribute("mustContain", "javaSerializedData"));
    attrs3.put(new BasicAttribute("objectClassCategory", "1"));
    attrs3.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs3.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs3.put(new BasicAttribute("description", "Java serialized object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs3);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaNamingReference");
    Attributes attrs4 = new BasicAttributes();

    attrs4.put(new BasicAttribute("objectClass", "classSchema"));
    attrs4.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs4.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.7"));
    attrs4.put(new BasicAttribute("lDAPDisplayName", attrID));

    Attribute jnrMay = new BasicAttribute("mayContain");
    jnrMay.add("javaReferenceAddress");
    jnrMay.add("javaFactory");
    attrs4.put(jnrMay);

    attrs4.put(new BasicAttribute("objectClassCategory", "1"));
    attrs4.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs4.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs4.put(new BasicAttribute("description", "JNDI reference"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs4);
    System.out.println("    [" + attrID + "]");

    attrID = new String("javaMarshalledObject");
    Attributes attrs5 = new BasicAttributes();

    attrs5.put(new BasicAttribute("objectClass", "classSchema"));
    attrs5.put(new BasicAttribute("defaultHidingValue", "FALSE"));
    attrs5.put(new BasicAttribute("governsID", "1.3.6.1.4.1.42.2.27.4.2.8"));
    attrs5.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs5.put(new BasicAttribute("mustContain", "javaSerializedData"));
    attrs5.put(new BasicAttribute("objectClassCategory", "1"));
    attrs5.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs5.put(new BasicAttribute("subclassOf", "javaObject"));
    attrs5.put(new BasicAttribute("description", "Java marshalled object"));

    schemaCtx.createSubcontext("CN=" + attrID, attrs5);
    System.out.println("    [" + attrID + "]");

    flushADSchemaMods(rootCtx); // finally
}

From source file:ldap.ActiveLoginImpl.java

public void testMain() throws Exception {
    //Here are some usage examples to demonstrate how the password hashing API works.

    //1,2: This shows how we automatically hash a password attribute in a new user.

    String defaultEncryptionScheme = LdapConstants.SHA; // set the default encryption scheme - usually we only have one scheme per directory

    Attributes test = new BasicAttributes();
    test.put("cn", "test user");
    test.put("userPassword", "secret");
    test.put("objectClass", "person");

    //ActiveLoginImpl login = new ActiveLoginImpl();

    //logger.info("1: invoking hashPasswordAttribute: "); 
    Attributes mytest = hashPasswordAttribute(test);
    String pwd = stringEncode((byte[]) mytest.get("userPassword").get());
    // logger.info("1: show automatically hashed password attribute: " + pwd);

    //logger.info("2: verify SHA hashed password against plaintext = " + passwordVerify("{SHA}5en6G6MezRroT3XKqkdPOmY/BfQ=", "secret"));
    //logger.info("2: verify SHA hashed password against plaintext = " + passwordVerify(pwd, "secret"));

    //3,4 This shows using a salted hash; we automatically generate the salt
    defaultEncryptionScheme = LdapConstants.SSHA; // set the default encryption scheme to a salted hash
    test.put("userPassword", "secret"); // reset password
    // logger.info("3) 1: invoking hashPasswordAttribute: "); 
    test = hashPasswordAttribute(test); // hash password generating random salt

    String saltedPwd = stringEncode((byte[]) test.get("userPassword").get());

    // these are commented out.
    //logger.info("3: show salted hashed password attribute:        " + saltedPwd);

    //logger.info("4: verify SSHA salted hash password against plaintext = " + passwordVerify(saltedPwd, "secret"));

    //5,6 This shows using an old-style 'crypt' hash directly

    //logger.info("5: show creation of crypt password 'secret' with salt 'KD' = " + stringEncode(hashPwd("secret", LdapConstants.crypt ,plainDecode("KD"))));

    // logger.info("6: And verify crypt hashed password = " +   passwordVerify("{crypt}KDdVi0RbEzCac", "secret"));
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    String entryNameAfter = entryName;
    if (paramValueMap != null) {
        String newEntryName = (String) paramValueMap.get("newEntryName");
        if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) {
            if (log.isDebugEnabled())
                log.debug("newEntryName=[" + newEntryName + "]");
            DirContext dirContext = null;
            try {
                dirContext = getDirContext(paramValueMap);
                dirContext.rename(entryName, newEntryName);
                entryNameAfter = newEntryName;
            } catch (NamingException e) {
                String msg;//ww w  .jav a 2 s  . c om
                // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                // Sun:
                //   [LDAP: error code 32 - No Such Object...
                if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                    msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]";
                } else {
                    msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]";
                }
                storeLdapException(e, prc);
                throw new SenderException(msg, e);
            } finally {
                closeDirContext(dirContext);
            }
        }
    }

    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Update attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Update value: ***");
                    } else {
                        log.debug("Update value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    String msg;
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 32 - No Such Object...
                    if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter
                                + "]";
                    } else {
                        msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter
                                + "]";
                    }
                    //result = DEFAULT_RESULT_UPDATE_NOK;
                    storeLdapException(e, prc);
                    throw new SenderException(msg, e);
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            //dirContext.rename(newEntryName, oldEntryName);
            //result = DEFAULT_RESULT;
            dirContext.rename(entryName, entryName);
            return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>";
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
            return DEFAULT_RESULT_CREATE_NOK;
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationCreate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;/* w  w  w  .j  av a 2s. c o  m*/
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Create attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Create value: ***");
                    } else {
                        log.debug("Create value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.ADD_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   20 LDAP_TYPE_OR_VALUE_EXISTS Indicates that the attribute value specified in a modify or add operation already exists as a value for that attribute.
                    // Sun:
                    //   [LDAP: error code 20 - Attribute Or Value Exists]
                    if (e.getMessage().startsWith("[LDAP: error code 20 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_CREATE_OK;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            if (unicodePwd) {
                Enumeration enumeration = attrs.getIDs();
                while (enumeration.hasMoreElements()) {
                    String id = (String) enumeration.nextElement();
                    if ("unicodePwd".equalsIgnoreCase(id)) {
                        Attribute attr = attrs.get(id);
                        for (int i = 0; i < attr.size(); i++) {
                            attr.set(i, encodeUnicodePwd(attr.get(i)));
                        }
                    }
                }
            }
            dirContext = getDirContext(paramValueMap);
            dirContext.bind(entryName, null, attrs);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // if (log.isDebugEnabled()) log.debug("Exception in operation [" + getOperation()+ "] entryName ["+entryName+"]", e);
            if (log.isDebugEnabled())
                log.debug("Exception in operation [" + getOperation() + "] entryName [" + entryName + "]: "
                        + e.getMessage());
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                return DEFAULT_RESULT_CREATE_OK;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }

}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the modificationItems in the javax.naming.directory.Attributes
 * format.//w w  w  . j  a v  a2s. c o  m
 *
 * @param modificationItems
 *                the modification items list
 * @param forgetEmpty
 *                if specified, empty attributes will not be converted
 * @return the formatted attributes
 */
private Attributes getAttributes(final List<ModificationItem> modificationItems, final boolean forgetEmpty) {
    Attributes attrs = new BasicAttributes();
    for (ModificationItem mi : modificationItems) {
        if (!(forgetEmpty && mi.getAttribute().size() == 0)) {
            attrs.put(mi.getAttribute());
        }
    }
    return attrs;
}