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(boolean ignoreCase) 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:org.kitodo.production.services.data.LdapServerService.java

/**
 * Check if User already exists on system.
 *
 * @param user/*w w  w .ja  va  2 s  .  c  o  m*/
 *            The User.
 * @return result as boolean
 */
public boolean isUserAlreadyExists(User user) {
    Hashtable<String, String> ldapEnvironment = initializeWithLdapConnectionSettings(
            user.getLdapGroup().getLdapServer());
    DirContext ctx;
    boolean result = false;
    try {
        ctx = new InitialDirContext(ldapEnvironment);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search(buildUserDN(user), matchAttrs);
        result = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            logger.debug(">>>{}", sr.getName());
            Attributes attrs = sr.getAttributes();
            String givenName = getStringForAttribute(attrs, "givenName");
            String surName = getStringForAttribute(attrs, "sn");
            String mail = getStringForAttribute(attrs, "mail");
            String cn = getStringForAttribute(attrs, "cn");
            String homeDirectory = getStringForAttribute(attrs, "homeDirectory");

            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(homeDirectory);
        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e.getMessage(), e);
    }
    return result;
}

From source file:de.sub.goobi.helper.ldap.LdapUser.java

@Override
public Attributes getAttributes(String name, String[] ids) throws NamingException {
    if (!name.equals("")) {
        throw new NameNotFoundException();
    }//  w  w w  .  j a  v  a2  s .co m

    Attributes answer = new BasicAttributes(true);
    Attribute target;
    for (String id : ids) {
        target = this.myAttrs.get(id);
        if (target != null) {
            answer.put(target);
        }
    }
    return answer;
}

From source file:org.kitodo.production.ldap.LdapUser.java

@Override
public Attributes getAttributes(String name, String[] ids) throws NamingException {
    if (!name.equals("")) {
        throw new NameNotFoundException();
    }//from   w w  w  . j a v a  2s  .  c  om

    Attributes answer = new BasicAttributes(true);
    Attribute target;
    for (String id : ids) {
        target = this.attributes.get(id);
        if (Objects.nonNull(target)) {
            answer.put(target);
        }
    }
    return answer;
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Create sub contexts under the tenant's main context.
 *
 * @param dnOfParentContext    domain name of the parent context.
 * @param nameOfCurrentContext name of the current context.
 * @param initialDirContext    The directory connection.
 * @throws UserStoreException if an error occurs while creating context.
 *///from   w  w w .  ja v a 2s. co  m
protected void createOrganizationalSubContext(String dnOfParentContext, String nameOfCurrentContext,
        DirContext initialDirContext) throws UserStoreException {

    DirContext subContext = null;
    DirContext organizationalContext = null;

    try {
        //get the connection for tenant's main context
        subContext = (DirContext) initialDirContext.lookup(dnOfParentContext);

        Attributes contextAttributes = new BasicAttributes(true);
        //create sub unit object class attribute
        Attribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objectClass.add(tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORG_SUB_CONTEXT_OBJ_CLASS));
        contextAttributes.put(objectClass);

        //create org sub unit name attribute
        String orgSubUnitAttributeName = tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORG_SUB_CONTEXT_ATTRIBUTE);
        Attribute organizationSubUnit = new BasicAttribute(orgSubUnitAttributeName);
        organizationSubUnit.add(nameOfCurrentContext);
        contextAttributes.put(organizationSubUnit);

        //construct the rdn of org sub context
        String rdnOfOrganizationalContext = orgSubUnitAttributeName + "=" + nameOfCurrentContext;
        if (logger.isDebugEnabled()) {
            logger.debug("Adding sub context: " + rdnOfOrganizationalContext + " under " + dnOfParentContext
                    + " ...");
        }
        //create sub context
        organizationalContext = subContext.createSubcontext(rdnOfOrganizationalContext, contextAttributes);
        if (logger.isDebugEnabled()) {
            logger.debug("Sub context: " + rdnOfOrganizationalContext + " was added under " + dnOfParentContext
                    + " successfully.");
        }

    } catch (NamingException e) {
        String errorMsg = "Error occurred while adding the organizational unit " + "sub context.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalContext);
        closeContext(subContext);
    }
}

From source file:CreateJavaSchema.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*/

    // javaContainer
    Attributes attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.1");
    attrs.put("NAME", "javaContainer");
    attrs.put("DESC", "Container for a Java object");
    attrs.put("SUP", "top");
    attrs.put("STRUCTURAL", "true");
    Attribute jcMust = new BasicAttribute("MUST", "cn");

    if (netscape41bug) {
        jcMust.add("objectClass");
    }
    attrs.put(jcMust);

    ocRoot.createSubcontext("javaContainer", attrs);
    System.out.println("Created javaContainer object class");

    // javaObject
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.4");
    attrs.put("NAME", "javaObject");
    attrs.put("DESC", "Java object representation");
    attrs.put("SUP", "top");
    attrs.put("ABSTRACT", "true");
    Attribute joMust = new BasicAttribute("MUST", "javaClassName");

    if (netscape41bug) {
        joMust.add("objectClass");
    }
    attrs.put(joMust);

    Attribute optional = new BasicAttribute("MAY", "javaCodebase");
    optional.add("javaClassNames");
    optional.add("javaDoc");
    optional.add("description");
    attrs.put(optional);
    ocRoot.createSubcontext("javaObject", attrs);
    System.out.println("Created javaObject object class");

    // javaSerializedObject
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.5");
    attrs.put("NAME", "javaSerializedObject");
    attrs.put("DESC", "Java serialized object");
    attrs.put("SUP", "javaObject");
    attrs.put("AUXILIARY", "true");
    Attribute jsoMust = new BasicAttribute("MUST", "javaSerializedData");

    if (netscape41bug) {
        jsoMust.add("objectClass");
    }

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

    // javaMarshalledObject
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.8");
    attrs.put("NAME", "javaMarshalledObject");
    attrs.put("DESC", "Java marshalled object");
    attrs.put("SUP", "javaObject");
    attrs.put("AUXILIARY", "true");

    if (netscapebug) {
        // Netscape ignores 'SUP' so we must add explicitly
        attrs.put(optional);
    }
    attrs.put(jsoMust); // re-use the MUST from javaSerializedObject
    ocRoot.createSubcontext("javaMarshalledObject", attrs);
    System.out.println("Created javaMarshalledObject object class");

    // javaNamingReference
    attrs = new BasicAttributes(true);
    attrs.put("NUMERICOID", "1.3.6.1.4.1.42.2.27.4.2.7");
    attrs.put("NAME", "javaNamingReference");
    attrs.put("DESC", "JNDI reference");
    attrs.put("SUP", "javaObject");
    attrs.put("AUXILIARY", "true");

    if (netscapebug) {
        // Netscape ignores 'SUP' so we must add explicitly
        attrs.put("MUST", "javaClassName");
    } else {
        optional = new BasicAttribute("MAY");
    }

    optional.add("javaReferenceAddress");
    optional.add("javaFactory");
    attrs.put(optional);
    ocRoot.createSubcontext("javaNamingReference", attrs);
    System.out.println("Created javaNamingReference object class");
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * check if User already exists on system.
 *
 * @param inLogin/*from  w w w  .  j av  a  2s . c o  m*/
 *            String
 * @return path as string
 */
public boolean isUserAlreadyExists(String inLogin) {
    Hashtable<String, String> env = getLdapConnectionSettings();
    env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
    env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));
    DirContext ctx;
    boolean rueckgabe = false;
    try {
        ctx = new InitialDirContext(env);
        Attributes matchAttrs = new BasicAttributes(true);
        NamingEnumeration<SearchResult> answer = ctx.search("ou=users,dc=gdz,dc=sub,dc=uni-goettingen,dc=de",
                matchAttrs);
        rueckgabe = answer.hasMoreElements();

        while (answer.hasMore()) {
            SearchResult sr = answer.next();
            if (logger.isDebugEnabled()) {
                logger.debug(">>>" + sr.getName());
            }
            Attributes attrs = sr.getAttributes();
            String givenName = " ";
            String surName = " ";
            String mail = " ";
            String cn = " ";
            String hd = " ";
            try {
                givenName = attrs.get("givenName").toString();
            } catch (Exception err) {
                givenName = " ";
            }
            try {
                surName = attrs.get("sn").toString();
            } catch (Exception e2) {
                surName = " ";
            }
            try {
                mail = attrs.get("mail").toString();
            } catch (Exception e3) {
                mail = " ";
            }
            try {
                cn = attrs.get("cn").toString();
            } catch (Exception e4) {
                cn = " ";
            }
            try {
                hd = attrs.get("homeDirectory").toString();
            } catch (Exception e4) {
                hd = " ";
            }
            logger.debug(givenName);
            logger.debug(surName);
            logger.debug(mail);
            logger.debug(cn);
            logger.debug(hd);

        }

        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Returns a BasicAttributes object with basic required attributes
 *
 * @param userName//from  w  ww  .ja v  a 2 s .c om
 * @return
 */
protected BasicAttributes getAddUserBasicAttributes(String userName) {
    BasicAttributes basicAttributes = new BasicAttributes(true);
    String userEntryObjectClassProperty = realmConfig
            .getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS);
    BasicAttribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    String[] objectClassHierarchy = userEntryObjectClassProperty.split("/");
    for (String userObjectClass : objectClassHierarchy) {
        if (userObjectClass != null && !userObjectClass.trim().equals("")) {
            objectClass.add(userObjectClass.trim());
        }
    }
    // If KDC is enabled we have to set KDC specific object classes also
    if (kdcEnabled) {
        // Add Kerberos specific object classes
        objectClass.add("krb5principal");
        objectClass.add("krb5kdcentry");
        objectClass.add("subschema");
    }
    basicAttributes.put(objectClass);
    BasicAttribute userNameAttribute = new BasicAttribute(
            realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE));
    userNameAttribute.add(userName);
    basicAttributes.put(userNameAttribute);

    if (kdcEnabled) {
        CarbonContext cc = CarbonContext.getThreadLocalCarbonContext();
        if (cc != null) {
            String tenantDomainName = cc.getTenantDomain();
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomainName)) {
                userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + tenantDomainName;
            } else {
                userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR
                        + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            }
        }

        String principal = userName + "@" + this.getRealmName();

        BasicAttribute principalAttribute = new BasicAttribute(KRB5_PRINCIPAL_NAME_ATTRIBUTE);
        principalAttribute.add(principal);
        basicAttributes.put(principalAttribute);

        BasicAttribute versionNumberAttribute = new BasicAttribute(KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
        versionNumberAttribute.add("0");
        basicAttributes.put(versionNumberAttribute);
    }
    return basicAttributes;
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

@Deprecated
protected String createAdminEntry(String dnOfUserContext, Tenant tenant, DirContext initialDirContext)
        throws UserStoreException {
    String userDN = null;/*  w  ww .  j av  a2s .com*/
    DirContext organizationalUsersContext = null;
    try {
        //get connection to tenant's user context
        organizationalUsersContext = (DirContext) initialDirContext.lookup(dnOfUserContext);
        Attributes userAttributes = new BasicAttributes(true);

        //create person object class attribute
        Attribute objClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objClass.add(realmConfig.getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS));
        if (UserCoreUtil.isKdcEnabled(realmConfig)) {
            // Add Kerberos specific object classes
            objClass.add("krb5principal");
            objClass.add("krb5kdcentry");
            objClass.add("subschema");

            String principal = tenant.getAdminName() + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR
                    + tenant.getDomain() + UserCoreConstants.TENANT_DOMAIN_COMBINER + getRealmName();
            Attribute kerberosPrincipalName = new BasicAttribute("krb5PrincipalName");
            kerberosPrincipalName.add(principal);

            Attribute keyVersionNumber = new BasicAttribute("krb5KeyVersionNumber");
            keyVersionNumber.add("0");

            userAttributes.put(kerberosPrincipalName);
            userAttributes.put(keyVersionNumber);
        }
        userAttributes.put(objClass);

        //create user password attribute
        Attribute password = new BasicAttribute(USER_PASSWORD_ATTRIBUTE_NAME);
        String passwordHashMethod = realmConfig.getUserStoreProperty(LDAPConstants.PASSWORD_HASH_METHOD);
        String passwordToStore = UserCoreUtil.getPasswordToStore(tenant.getAdminPassword(), passwordHashMethod,
                isKDCEnabled());
        password.add(passwordToStore);
        userAttributes.put(password);

        //create mail attribute
        Attribute adminEmail = new BasicAttribute(EMAIL_ATTRIBUTE_NAME);
        adminEmail.add(tenant.getEmail());
        userAttributes.put(adminEmail);

        //create compulsory attribute: sn-last name
        Attribute lastName = new BasicAttribute(SN_ATTRIBUTE_NAME);
        lastName.add(tenant.getAdminLastName());
        userAttributes.put(lastName);

        //read user name attribute in user-mgt.xml
        String userNameAttribute = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);

        //if user name attribute is not cn, add it to attribute list
        if (!(CN_ATTRIBUTE_NAME.equals(userNameAttribute))) {
            Attribute firstName = new BasicAttribute(CN_ATTRIBUTE_NAME);
            firstName.add(tenant.getAdminFirstName());
            userAttributes.put(firstName);
        }
        String userRDN = userNameAttribute + "=" + tenant.getAdminName();
        organizationalUsersContext.bind(userRDN, null, userAttributes);
        userDN = userRDN + "," + dnOfUserContext;
        //return (userRDN + dnOfUserContext);
    } catch (NamingException e) {
        String errorMsg = "Error occurred while creating Admin entry";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalUsersContext);
    }

    return userDN;
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationUpdate.java

private void updateOrg() throws NameNotFoundException, AASUnauthorizedException, AttributeModificationException,
        ExecutionException {//from w  ww. j  a va  2s.  co  m
    boolean vChange = false;
    InitialLdapContext vCtx = null;
    try {

        if (this._oldOrganisation == null) {
            LOG.log(Level.WARNING, "No such organization ''{0}'' with oid: ''{1}''.",
                    new Object[] { this._organisation.getDisplayName(), this._organisation.getOIDs() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        GeoAdresse vGeoAdresse;
        String vLocalDispalyName = null;
        if (_submit != null) { // hier ist "GeoLocationDisplayName" breits ausgefhrt
            try {
                vGeoAdresse = _submit.get(10, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._organisation.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._organisation.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._organisation.getAddress()
                            .setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._organisation.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            }
        } else if (_submitGeoLocDisplayName != null) {
            try {
                vLocalDispalyName = _submitGeoLocDisplayName.get(5, TimeUnit.SECONDS);
                this._organisation.getAddress().setLocationDisplayName(vLocalDispalyName);
                //LOG.info("LocalDisplayName='" + vLocalDispalyName + "'" + vLocalDispalyName + "'");
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (ExecutionException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            }

        }

        LOG.info("newOIDs: '" + this._organisation.getOIDs() + "'");
        LOG.info("oldOIDs: '" + this._oldOrganisation.getOIDs() + "'");

        if (this._organisation.getOrgRDN() == null) {
            // -- Ansonsten eine nicht gesetzte RDN kann zum Knall fhren...
            this._organisation.setOrgRDN(this._oldOrganisation.getOrgRDN());
        } else if (!this._organisation.getOrgRDN().equals(this._oldOrganisation.getOrgRDN())) {
            // -- Hier ist etwas faul...
            LOG.log(Level.WARNING,
                    "The organization ''{0}'' has RDN: ''{1}'', but there exist an organization ''{0}'' with RDN: ''{2}''!",
                    new Object[] { this._organisation.getId(), this._organisation.getOrgRDN(),
                            this._oldOrganisation.getOrgRDN() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        if (this.isPrivilegesUpdate()) {
            Set<PrivilegeEnum> removePrivileges = this.privilegeDiff(this._organisation.getPrivilegesSet(),
                    this._oldOrganisation.getPrivilegesSet());
            Set<PrivilegeEnum> addPrivileges = this.privilegeDiff(this._oldOrganisation.getPrivilegesSet(),
                    this._organisation.getPrivilegesSet());
            if (!removePrivileges.isEmpty() || !addPrivileges.isEmpty()) {
                vChange = true;
                for (PrivilegeEnum p : removePrivileges) {
                    ThreadSinglePrivilegeDelete threadSinglePrivilegeDelete = new ThreadSinglePrivilegeDelete(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeDelete.call();
                }
                for (PrivilegeEnum p : addPrivileges) {
                    ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeCreate.call();
                }
            }
        }

        Attributes orgAttributes = new BasicAttributes(true);
        Attributes orgRemoveAttributes = new BasicAttributes(true);

        if (vChange = this.convertOrganizationToLdapOrgAttrsForUpdate(this._organisation, this._oldOrganisation,
                orgAttributes, orgRemoveAttributes, getPerformer())) {

            // -- If any changes, the status is set to 'revised'
            //    but not if status will be explicitly changed or by a update operation on Licenses directory
            if (!isChangeOfStatus() && !isUpdatingOfLicensedOrgs()) {
                if ((ConstEnumOrgStatus.approved.equals(this._organisation.getStatus()))) {
                    // -- ...then go retrospectively into "revised" status:
                    this._organisation.setStatus(ConstEnumOrgStatus.revised);

                    orgAttributes.put(Constants.ldap_ddbOrg_Status,
                            String.valueOf(this._organisation.getStatus().name()));
                }
            }
        }
        // ---------------------------------------------------------------------
        if (vChange) {

            // -- Save changes to the corresponding directory:
            StringBuilder vOrgEntryDN = (isUpdatingOfLicensedOrgs()
                    ? this.getLicensedOrgsDN(this._organisation.getOIDs())
                    : this.getOrgDN(this._organisation.getOIDs()));
            LOG.log(Level.INFO, "DEBUG-Info: destination OrgEntryDN = '" + vOrgEntryDN + "'");

            vCtx = LDAPConnector.getSingletonInstance().takeCtx();
            if (orgRemoveAttributes.size() > 0) {
                vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REMOVE_ATTRIBUTE, orgRemoveAttributes);
            }
            vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REPLACE_ATTRIBUTE, orgAttributes);
        } else {
            throw new AttributeModificationException(
                    "Not modified: oid = '" + this._organisation.getOIDs() + "'");
        }

    } catch (RejectedExecutionException ex) {
        LOG.log(Level.SEVERE, "RejectedExecutionException\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.WARNING, null, ex);
        throw ex;
    } catch (AttributeModificationException ex) {
        LOG.log(Level.WARNING, "AttributeModificationException\n{0}", ex.getMessage());
        // !!!!AttributeModificationException extends NamingExeption:
        //throw ex;
        throw new AttributeModificationException(ex.getMessage());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException\n{0}", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

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

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

    if (hasRole(context, roleName)) {
        return true;
    }//from ww w .  j a  v  a2  s.co m

    String groupName = findGroupName(roleName);

    if (groupName == null) {
        if (this.useDefaultRoleName) {
            groupName = roleName;
        } else {
            log.warn("skip group creation as no mapping for roleName:'{}'", roleName);
            return false;
        }
    }

    List<String> allGroups = getAllGroups(context);
    if (allGroups.contains(groupName)) {
        log.info("group {} already exists for role.", groupName, roleName);
        return false;
    }

    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("groupOfUniqueNames");
    attributes.put(objectClass);
    attributes.put("cn", groupName);

    // attribute mandatory when created a group so add admin as default member
    BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
    basicAttribute.add(this.userIdAttribute + "=admin," + getBaseDn());
    attributes.put(basicAttribute);

    try {
        String dn = "cn=" + groupName + "," + this.groupsDn;

        context.createSubcontext(dn, attributes);

        log.info("created group with dn:'{}", dn);

        return true;
    } catch (NameAlreadyBoundException e) {
        log.info("skip group '{}' creation as already exists", groupName);
        return true;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);

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