Example usage for javax.naming.directory Attribute add

List of usage examples for javax.naming.directory Attribute add

Introduction

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

Prototype

boolean add(Object attrVal);

Source Link

Document

Adds a new value to the attribute.

Usage

From source file:ldap.ActiveLoginImpl.java

/**
 * This adds a new user.  It requires at the minimum a name, it should also
 * usually have a surname and a password at a minimum.
 *
 * @param account/*from   ww w.jav a  2s  . c  om*/
 * @throws Exception
 */
public void addAccount(UserAccount account, DirContext context, String userBaseDN) throws Exception {
    // set some default values for the user entry if they haven't been manually added.

    //if (account.get(Config.USER_NAMING_ATT) == null)
    if (account.get(LdapConstants.ldapAttrCn) == null)
        throw new NamingException("addAccount(), UserAccount has no naming Attribute");

    if (account.get(LdapConstants.ldapObjectClass) == null) {
        //Attribute oc = new BasicAttribute("objectClass");
        Attribute oc = new BasicAttribute(LdapConstants.ldapObjectClass);

        if (LdapConstants.ldapObjectClassEmployeeEnable) {
            //oc.add("employee");
            oc.add(LdapConstants.ldapObjectClassEmployee);
        }

        //old redbasin stuff   
        /*   
               if (LdapConstants.ldapAttrTopEnable) {
                       oc.add(LdapConstants.ldapAttrTop); 
               }
               if (LdapConstants.ldapAttrPersonEnable) {
                       oc.add(LdapConstants.ldapAttrPerson); 
               }
               if (LdapConstants.ldapAttrOrgPersonEnable) {
                       oc.add(LdapConstants.ldapAttrOrgPerson); 
               }
               if (LdapConstants.ldapAttrInetOrgPersonEnable) {
                       oc.add(LdapConstants.ldapAttrInetOrgPerson); 
               }
        */
        account.put(oc);
    }

    /*  made changes  */
    /*
            if (account.get("cn") == null)
    account.put("cn", account.getUserID());
            
            if (account.get("sn") == null)
    account.put("sn", "xxx");  // put in default value for required attribute
    */
    if (account.get(LdapConstants.ldapAttrCn) == null)
        account.put(LdapConstants.ldapAttrCn, account.getUserID());

    if (account.get(LdapConstants.ldapAttrSn) == null)
        account.put(LdapConstants.ldapAttrSn, "xxx"); // put in default value for required attribute
    //logger.info("ADDING: \n" + account.getUserDN() + "\n" + account.toString());
    logger.info("ADDING: \n" + userBaseDN + "\n" + account.toString());

    /**
    * deal with the password adding later 
    */
    /*
       Attributes attributes = copyAttributes(account);
       UserAccount myaccount = hashPasswordAttribute(attributes);
    */
    // use this only when we add the user
    //context.createSubcontext(account.getUserDN(), account);
    context.createSubcontext(userBaseDN, account);
}

From source file:openscim.restful.server.resources.user.ldap.LdapUserResource.java

@Override
public Response createUser(UriInfo uriInfo, User user) {
    // check the ldap template has been setup correctly
    if (ldapTemplate != null) {
        // create the mapper if it doesn't already exists
        if (mapper == null)
            mapper = new UserAttributesMapper(properties);

        // build the user dn
        String dn = user.getId();
        if (properties
                .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                        UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
            // utilise ldap formated dn
            dn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + user.getId() + ","
                    + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN,
                            UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN);
        }/*ww  w.j  a  v a  2s. c om*/

        try {
            try {
                // create the mapper if it doesn't already exists
                if (mapper == null)
                    mapper = new UserAttributesMapper(properties);

                // retrieve the user
                User lookedUser = (User) ldapTemplate.lookup(dn, mapper);

                // check if the user was found
                if (lookedUser != null) {
                    // user already exists            
                    return ResourceUtilities.buildErrorResponse(HttpStatus.CONFLICT,
                            HttpStatus.CONFLICT.getMessage() + ": Resource " + user.getId()
                                    + " already exists");
                }
            } catch (Exception nException) {
                // user not found, do nothing
            }

            Attributes userAttributes = new BasicAttributes();

            // get the objectclasses
            String objectclasses = properties.getProperty(UserAttributesMapper.ACCOUNT_OBJECTCLASS_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_ACCOUNT_OBJECTCLASS_ATTRIBUTE);

            // set the objectclass of the user
            /*
            Attribute objectclassAttribute = new BasicAttribute("objectclass");
            Scanner scanner = new Scanner(objectclasses);            
            scanner.useDelimiter(",");
            while(scanner.hasNext())
            {
               objectclassAttribute.add(scanner.next());
            }
            */

            BasicAttribute objectclassAttribute = new BasicAttribute("objectclass");
            objectclassAttribute.add("inetOrgPerson");
            objectclassAttribute.add("organizationalPerson");
            objectclassAttribute.add("person");
            objectclassAttribute.add("top");
            userAttributes.put(objectclassAttribute);

            // get the uid attribute name
            String uidAtttributeName = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE);

            // set the uid
            userAttributes.put(uidAtttributeName, user.getId());

            // get the display name attribute name
            String displayAtttributeName = properties.getProperty(UserAttributesMapper.DISPLAYNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_DISPLAYNAME_ATTRIBUTE);

            // set the display name
            if (user.getDisplayName() != null)
                userAttributes.put(displayAtttributeName, user.getDisplayName());

            // get the surname attribute name
            String surnameAtttributeName = properties.getProperty(UserAttributesMapper.FAMILYNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_FAMILYNAME_ATTRIBUTE);

            // get the given name attribute name
            String givenAtttributeName = properties.getProperty(UserAttributesMapper.GIVENNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_GIVENNAME_ATTRIBUTE);

            // set the names
            if (user.getName() != null) {
                if (user.getName().getFamilyName() != null)
                    userAttributes.put(surnameAtttributeName, user.getName().getFamilyName());
                if (user.getName().getGivenName() != null)
                    userAttributes.put(givenAtttributeName, user.getName().getGivenName());
            }

            // get the email attribute name
            String mailAtttributeName = properties.getProperty(UserAttributesMapper.MAIL_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_MAIL_ATTRIBUTE);

            // set the emails
            if (user.getEmails() != null) {
                Attribute attribute = new BasicAttribute(mailAtttributeName);
                List<PluralAttribute> emails = user.getEmails().getEmail();
                for (PluralAttribute email : emails) {
                    attribute.add(email.getValue());
                }
                userAttributes.put(attribute);
            }

            // get the telephone attribute name
            String telephoneAtttributeName = properties.getProperty(UserAttributesMapper.TELEPHONE_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_TELEPHONE_ATTRIBUTE);

            // set the telephones
            if (user.getPhoneNumbers() != null) {
                Attribute attribute = new BasicAttribute(telephoneAtttributeName);
                List<PluralAttribute> telephones = user.getPhoneNumbers().getPhoneNumber();
                for (PluralAttribute telephone : telephones) {
                    attribute.add(telephone.getValue());
                }
                userAttributes.put(attribute);
            }

            // get the password attribute name
            String passwordAtttributeName = properties.getProperty(UserAttributesMapper.PASSWORD_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_PASSWORD_ATTRIBUTE);

            // set the password
            if (user.getPassword() != null)
                userAttributes.put(passwordAtttributeName, user.getPassword());

            // create the user
            ldapTemplate.bind(dn, null, userAttributes);

            // determine the url of the new resource
            URI location = new URI("/User/" + dn);
            if (properties
                    .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                            UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                    .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                location = new URI("/User/" + user.getId());
            }

            // set the internal id to the dn
            user.setId(dn);
            if (properties
                    .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                            UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                    .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                user.setId(user.getId());
            }

            // user stored successfully, return the user            
            return Response.created(location).entity(user).build();
        } catch (URISyntaxException usException) {
            // problem generating entity location
            logger.error("problem generating entity location");
            usException.printStackTrace(System.out);

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage()
                            + ": Service Provider problem generating entity location");
        } catch (Exception nException) {
            // problem creating user
            logger.error("problem creating user");
            nException.printStackTrace(System.out);

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem creating user");
        }
    } else {
        // ldap not configured
        logger.error("ldap not configured");

        // return a server error
        return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.NOT_IMPLEMENTED.getMessage()
                        + ": Service Provider user ldap repository not configured");
    }
}

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

/**
 * Convert a <i>Contact</i> into a LDAP inetOrgPerson set of attributes.
 * This method is used in from Client to Server
 * /*from w  w  w .ja v  a 2  s  . c o m*/
 * @param contact
 *            contact to transform into Attributes
 * @return Attributes representation of the contact
 */
public Attributes createEntry(Contact contact) {

    if (logger.isTraceEnabled())
        logger.trace("Working on contact:" + contact.getUid());

    Attributes attributeSet = new BasicAttributes();
    Attribute objClass = new BasicAttribute("objectClass");
    if (logger.isDebugEnabled())
        logger.debug("Ok let's add objectclass");

    objClass.add("inetOrgPerson");
    objClass.add("person");

    attributeSet.put(objClass);
    try {

        if (contact.getUid() == null) {
            contact.setUid(createUniqueId(contact));
            logger.info("UID is now: " + contact.getUid());
        }

        // Split contact object into sub-objects
        Name name = contact.getName();
        PersonalDetail personal = contact.getPersonalDetail();
        BusinessDetail business = contact.getBusinessDetail();

        List phones = personal.getPhones();
        List businessPhones = business.getPhones();

        List mails = personal.getEmails();
        List note = contact.getNotes();

        // personal address
        Address addr = personal.getAddress();

        // if displayname doesn't exist and the firstname and the lastname
        // are not both defined, this will result in a NullPointerException
        // I don't want to support any other ways of doing this right now.
        // a solution could be to use an UID for the rdn
        if (name != null) {

            if (propertyCheck(name.getLastName())) {
                attributeSet.put(new BasicAttribute("sn", name.getLastName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("sn", ""));
            }

            if (propertyCheck(name.getFirstName())) {
                attributeSet
                        .put(new BasicAttribute("givenName", name.getFirstName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("givenName", ""));
            }

            attributeSet.put(new BasicAttribute("cn", name.getFirstName().getPropertyValueAsString() + " "
                    + name.getLastName().getPropertyValueAsString()));
        }

        // Company name
        if (business != null && propertyCheck(business.getCompany())) {
            attributeSet.put(new BasicAttribute("o", business.getCompany().getPropertyValueAsString()));
        }

        // Adding phones
        if (phones != null && !phones.isEmpty()) {

            Iterator iter2 = phones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Home phones
                if (phone.getPhoneType().equals("HomeTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("homePhone", phone.getPropertyValueAsString()));
                }

                // MobilePhones
                if (phone.getPhoneType().equals("MobileTelephoneNumber"))
                    attributeSet.put(new BasicAttribute("mobile", phone.getPropertyValueAsString()));

            }
        }

        // Adding business phones
        if (businessPhones != null && !businessPhones.isEmpty()) {

            Iterator iter2 = businessPhones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Business phones
                if (phone.getPhoneType().equals("BusinessTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("telephoneNumber", phone.getPropertyValueAsString()));
                }
                // Fax
                if (phone.getPhoneType().equals("BusinessFaxNumber")) {
                    attributeSet.put(
                            new BasicAttribute("facsimiletelephonenumber", phone.getPropertyValueAsString()));
                }
            }
        }

        if (mails != null && !mails.isEmpty()) {

            Iterator iter1 = mails.iterator();

            // For each email address, add it
            while (iter1.hasNext()) {
                Email mail = (Email) iter1.next();
                if (propertyCheck(mail))
                    attributeSet.put(new BasicAttribute("mail", mail.getPropertyValueAsString()));
            }
        }

        // Address
        if (addr != null) {
            if (propertyCheck(personal.getAddress().getPostalCode()))
                attributeSet.put(new BasicAttribute("postalCode",
                        personal.getAddress().getPostalCode().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getStreet()))
                attributeSet.put(new BasicAttribute("postalAddress",
                        personal.getAddress().getStreet().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getCity()))
                attributeSet.put(
                        new BasicAttribute("l", personal.getAddress().getCity().getPropertyValueAsString()));
        }

        // Notes
        if (note != null && !note.isEmpty()) {
            Iterator note1 = note.iterator();
            while (note1.hasNext()) {
                Note nota = (Note) note1.next();
                if (propertyCheck(nota))
                    attributeSet.put(new BasicAttribute("description", nota.getPropertyValueAsString()));
            }
        }

        logger.info("Resulting LDAPAttributeSet is:");

        NamingEnumeration<String> ids = attributeSet.getIDs();

        while (ids.hasMoreElements()) {
            String attrID = ids.nextElement();
            logger.info(attrID + ": " + ((String) attributeSet.get(attrID).get()));

        }

        // Create the LDAPEntry with dn and attributes
        // THE DN is the DisplayName
        return attributeSet;

    } catch (Exception e) {
        logger.warn("Unable to create LDAPEntry from Contact: " + e.toString(), e);
        return null;
    }
}

From source file:CreateCorbaSchema.java

/**
 * Inserts object class definitions from RFC 2714 into the schema.
 * //w ww .  j av  a2 s. com
 * This method maps the LDAP schema definitions in RFC 2714 onto the
 * proprietary attributes required by the Active Directory schema.
 * 
 * The resulting object class definitions differ from those of RFC 2714 in the
 * following ways:
 *  - Abstract and auxiliary classes are now defined as structural. - The
 * corbaObject class now inherits from corbaContainer. - The
 * corbaObjectReference class now inherits from corbaObject.
 * 
 * The effect of these differences is that CORBA object references 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 in 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 CORBA schema definition is
 * 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("corbaContainer");
    Attributes attrs1 = new BasicAttributes();

    attrs1.put(new BasicAttribute("cn", attrID));
    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.10"));
    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 CORBA object"));

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

    flushADSchemaMods(rootCtx); // corbaObject relys on corbaContainer

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

    attrs2.put(new BasicAttribute("cn", attrID));
    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.9"));
    attrs2.put(new BasicAttribute("lDAPDisplayName", attrID));

    Attribute coMay = new BasicAttribute("mayContain");
    coMay.add("corbaRepositoryId");
    coMay.add("description");
    attrs2.put(coMay);

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

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

    flushADSchemaMods(rootCtx); // corbaObjectReference relys on corbaObject

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

    attrs3.put(new BasicAttribute("cn", attrID));
    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.11"));
    attrs3.put(new BasicAttribute("lDAPDisplayName", attrID));
    attrs3.put(new BasicAttribute("mustContain", "corbaIor"));
    attrs3.put(new BasicAttribute("objectClassCategory", "1"));
    attrs3.put(new BasicAttribute("systemOnly", "FALSE"));
    attrs3.put(new BasicAttribute("subclassOf", "corbaObject"));
    attrs3.put(new BasicAttribute("description", "CORBA interoperable object reference"));

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

    flushADSchemaMods(rootCtx); // finally
}

From source file:CreateCorbaSchema.java

protected void updateObjectClasses(DirContext ocRoot, String[] ocIDs) throws NamingException {

    /* Get rid of old OCs - reverse order */
    for (int i = ocIDs.length - 1; i >= 0; i--) {
        ocRoot.destroySubcontext(ocIDs[i]);
    }/*  ww w .j  a v a  2 s. c o m*/

    // corbaObject
    Attributes attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.9");
    attrs.put("NAME", "corbaObject");
    attrs.put("DESC", "CORBA object representation");
    attrs.put("SUP", "top");
    attrs.put("ABSTRACT", "true");
    Attribute optional = new BasicAttribute("MAY", "corbaRepositoryId");
    optional.add("description");
    attrs.put(optional);
    ocRoot.createSubcontext("corbaObject", attrs);
    System.out.println("Created corbaObject object class");

    // corbaObjectReference
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.11");
    attrs.put("NAME", "corbaObjectReference");
    attrs.put("DESC", "CORBA interoperable object reference");
    attrs.put("SUP", "corbaObject");
    attrs.put("AUXILIARY", "true");
    Attribute corMust = new BasicAttribute("MUST", "corbaIor");

    if (netscape41bug) {
        corMust.add("objectclass");
    }

    if (netscapebug) {
        // Netscape ignores 'SUP' so we must add explicitly
        attrs.put(optional);
    }
    attrs.put(corMust);
    ocRoot.createSubcontext("corbaObjectReference", attrs);
    System.out.println("Created corbaObjectReference object class");

    // corbaContainer
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.10");
    attrs.put("NAME", "corbaContainer");
    attrs.put("DESC", "Container for a CORBA object");
    attrs.put("SUP", "top");
    attrs.put("STRUCTURAL", "true");
    Attribute ccMust = new BasicAttribute("MUST", "cn");

    if (netscape41bug) {
        ccMust.add("objectclass");
    }

    attrs.put(ccMust);
    ocRoot.createSubcontext("corbaContainer", attrs);
    System.out.println("Created corbaContainer object class");
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

private boolean checkAttributeEnum(
        //List<Enum<?>> pOrgAtt, List<Enum<?>> pOldOrgAtt, String ldapAttributeName,
        List<ConstEnumOrgSubSector> pOrgAtt, List<ConstEnumOrgSubSector> pOldOrgAtt, String ldapAttributeName,
        Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
    boolean hasChanged = false;
    if (!isUpdate) {
        // is create
        if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            for (Enum<?> iterEnum : pOrgAtt) {
                if (iterEnum != null) {
                    vAttr.add(iterEnum.name());
                }//ww  w. j av  a  2 s .c o m
            }
            if (vAttr.size() > 0) {
                vOrgAttributes.put(vAttr);
            }
        }
    } else {
        if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            if ((pOrgAtt.isEmpty()) && (pOldOrgAtt != null) && (!pOldOrgAtt.isEmpty())) {
                vOrgRemoveAttributes.put(vAttr);
                hasChanged = true;
            } else {
                for (Enum<?> iterEnum : pOrgAtt) {
                    if (iterEnum != null) {
                        vAttr.add(iterEnum.name());
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                    hasChanged = true;
                }
            }
        } else if ((pOrgAtt == null || pOrgAtt.isEmpty()) && (pOldOrgAtt != null && !pOldOrgAtt.isEmpty())) {
            vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
            hasChanged = true;
        }
    }
    return hasChanged;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

/**
 * Checks attribute-set if it has to be written to LDAP or removed from LDAP if attribute = 0, its like not set.
 * /*from   ww w.  ja  v a2 s  .co  m*/
 * @param pOrganisationAtt
 * @param pOldOrganisationAtt
 * @param ldapAttributeName
 * @param vOrgAttributes
 * @param vOrgRemoveAttributes
 * @param isUpdate
 */
private boolean checkAttribute(List<String> pOrganisationAtt, List<String> pOldOrganisationAtt,
        String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes,
        boolean isUpdate) {
    boolean hasChanged = false;
    if (!isUpdate) {
        // is create
        if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            for (String url : pOrganisationAtt) {
                if ((url != null) && (url.trim().length() > 0)) {
                    vAttr.add(url);
                }
            }
            if (vAttr.size() > 0) {
                vOrgAttributes.put(vAttr);
            }
        }
    } else {
        if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            if (pOrganisationAtt.size() == 1 && pOrganisationAtt.contains("") && pOldOrganisationAtt != null
                    && !pOldOrganisationAtt.isEmpty()) {
                vOrgRemoveAttributes.put(vAttr);
                hasChanged = true;
            } else {
                for (String url : pOrganisationAtt) {
                    if ((url != null) && (url.trim().length() > 0)) {
                        vAttr.add(url);
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                    hasChanged = true;
                }
            }
        } else if ((pOrganisationAtt == null || pOrganisationAtt.isEmpty())
                && (pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty())) {
            vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
            hasChanged = true;
        }
    }
    return hasChanged;
}

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/**
 * Converts spml modifications to jndi modifications.
 * //from   ww w . ja  va 2s.  c  om
 * @param modification the spml modification
 * @return the jndi modifications
 * @throws PspException if a psp error occurs
 */
protected List<ModificationItem> getReferenceMods(Modification modification) throws PspException {
    List<ModificationItem> mods = new ArrayList<ModificationItem>();

    Map<String, List<Reference>> references = PSPUtil.getReferences(modification.getCapabilityData());

    if (references.isEmpty()) {
        return mods;
    }

    for (String typeOfReference : references.keySet()) {

        List<String> ids = new ArrayList<String>();
        for (Reference reference : references.get(typeOfReference)) {
            if (reference.getToPsoID().getTargetID().equals(getId())) {
                String id = reference.getToPsoID().getID();
                // fake empty string since the spml toolkit ignores an empty string psoID
                // if (id.equals(PSOReferencesDefinition.EMPTY_STRING)) {
                // id = "";
                // }
                if (id == null) {
                    id = "";
                }
                ids.add(id);
            }
        }

        Attribute attribute = new BasicAttribute(typeOfReference);
        for (String id : ids) {
            attribute.add(id);
        }

        int op = -1;
        if (modification.getModificationMode().equals(ModificationMode.ADD)) {
            op = DirContext.ADD_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.DELETE)) {
            op = DirContext.REMOVE_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.REPLACE)) {
            op = DirContext.REPLACE_ATTRIBUTE;
        } else {
            throw new PspException("Unknown modification operation : " + modification.getModificationMode());
        }

        mods.add(new ModificationItem(op, attribute));
    }

    return mods;
}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean saveUserRole(String roleName, String username, DirContext context) throws MappingException {

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        groupName = roleName;//from  w w  w.  j ava2  s. c  om
    }

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {
        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute == null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.ADD_ATTRIBUTE, basicAttribute) });
            } else {
                attribute.add(this.userIdAttribute + "=" + username + "," + getBaseDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPSession.java

@Override
@SuppressWarnings("unchecked")
public DocumentModel createEntry(Map<String, Object> fieldMap) {
    checkPermission(SecurityConstants.WRITE);
    LDAPDirectoryDescriptor descriptor = getDirectory().getDescriptor();
    List<String> referenceFieldList = new LinkedList<String>();
    try {//w  w w.  j  a v a2  s. com
        String dn = String.format("%s=%s,%s", rdnAttribute, fieldMap.get(rdnField),
                descriptor.getCreationBaseDn());
        Attributes attrs = new BasicAttributes();
        Attribute attr;

        List<String> mandatoryAttributes = getMandatoryAttributes();
        for (String mandatoryAttribute : mandatoryAttributes) {
            attr = new BasicAttribute(mandatoryAttribute);
            attr.add(" ");
            attrs.put(attr);
        }

        String[] creationClasses = descriptor.getCreationClasses();
        if (creationClasses.length != 0) {
            attr = new BasicAttribute("objectclass");
            for (String creationClasse : creationClasses) {
                attr.add(creationClasse);
            }
            attrs.put(attr);
        }

        for (String fieldId : fieldMap.keySet()) {
            String backendFieldId = getDirectory().getFieldMapper().getBackendField(fieldId);
            if (backendFieldId.equals(getPasswordField())) {
                attr = new BasicAttribute(backendFieldId);
                String password = (String) fieldMap.get(fieldId);
                password = PasswordHelper.hashPassword(password, passwordHashAlgorithm);
                attr.add(password);
                attrs.put(attr);
            } else if (getDirectory().isReference(fieldId)) {
                List<Reference> references = directory.getReferences(fieldId);
                if (references.size() > 1) {
                    // not supported
                } else {
                    Reference reference = references.get(0);
                    if (reference instanceof LDAPReference) {
                        attr = new BasicAttribute(((LDAPReference) reference).getStaticAttributeId());
                        attr.add(descriptor.getEmptyRefMarker());
                        attrs.put(attr);
                    }
                }
                referenceFieldList.add(fieldId);
            } else if (LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY.equals(backendFieldId)) {
                // ignore special DN field
                log.warn(String.format("field %s is mapped to read only DN field: ignored", fieldId));
            } else {
                Object value = fieldMap.get(fieldId);
                if ((value != null) && !value.equals("") && !Collections.emptyList().equals(value)) {
                    attrs.put(getAttributeValue(fieldId, value));
                }
            }
        }

        if (log.isDebugEnabled()) {
            String idField = getIdField();
            log.debug(String.format("LDAPSession.createEntry(%s=%s): LDAP bind dn='%s' attrs='%s' [%s]",
                    idField, fieldMap.get(idField), dn, attrs, this));
        }
        dirContext.bind(dn, null, attrs);

        for (String referenceFieldName : referenceFieldList) {
            List<Reference> references = directory.getReferences(referenceFieldName);
            if (references.size() > 1) {
                // not supported
            } else {
                Reference reference = references.get(0);
                List<String> targetIds = (List<String>) fieldMap.get(referenceFieldName);
                reference.addLinks((String) fieldMap.get(getIdField()), targetIds);
            }
        }
        String dnFieldName = getDirectory().getFieldMapper()
                .getDirectoryField(LDAPDirectory.DN_SPECIAL_ATTRIBUTE_KEY);
        if (getDirectory().getSchemaFieldMap().containsKey(dnFieldName)) {
            // add the DN special attribute to the fieldmap of the new
            // entry
            fieldMap.put(dnFieldName, dn);
        }
        getDirectory().invalidateCaches();
        return fieldMapToDocumentModel(fieldMap);
    } catch (NamingException e) {
        handleException(e, "createEntry failed");
        return null;
    }
}