Example usage for javax.naming.directory BasicAttribute BasicAttribute

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

Introduction

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

Prototype

public BasicAttribute(String id) 

Source Link

Document

Constructs a new instance of an unordered attribute with no value.

Usage

From source file:org.easy.ldap.NamingFactory.java

public static Attribute getUsersObjectClasses() {
    Attribute objClasses = new BasicAttribute(LdapClasseNames.OBJECT_CLASS.toString());
    objClasses.add(LdapClasseNames.TOP.toString());
    objClasses.add(LdapClasseNames.ORG_UNIT.toString());

    return objClasses;

}

From source file:org.swordess.ldap.util.ModUtils.java

public static <T> ModificationItem create(int operationMod, String id, Collection<?> values,
        Evaluator<T> evaluator) {//from www. j  av  a2s. c  om
    if (CollectionUtils.isEmpty(values)) {
        return null;
    }

    boolean hasOneNotNullAtLeast = false;
    Attribute attr = new BasicAttribute(id);

    if (null == evaluator) {
        for (Object value : values) {
            if (null != value) {
                hasOneNotNullAtLeast = true;
                attr.add(value);
            }
        }

    } else {
        for (Object value : values) {
            if (null == value) {
                continue;
            }
            T evaled = evaluator.eval(value);
            if (null != evaled) {
                hasOneNotNullAtLeast = true;
                attr.add(evaled);
            }
        }
    }
    return hasOneNotNullAtLeast ? new ModificationItem(operationMod, attr) : null;
}

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 {/*from  w  ww  . ja  v a  2 s .c o m*/
        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;
    }
}

From source file:edu.vt.middleware.ldap.dsml.Dsmlv1.java

/**
 * This will take a DSML <code>Element</code> containing an entry of type
 * <dsml:entry name="name"/> and convert it to a LDAP search result.
 *
 * @param  entryElement  <code>Element</code> of DSML content
 *
 * @return  <code>SearchResult</code>
 *//* w  w  w  .  j a  va  2s. c o m*/
protected SearchResult createSearchResult(final Element entryElement) {
    String name = "";
    final Attributes entryAttributes = new BasicAttributes(true);
    SearchResult attrResults = null;

    if (entryElement != null) {

        name = entryElement.attributeValue("dn");
        if (name == null) {
            name = "";
        }

        if (entryElement.hasContent()) {

            final Iterator<?> ocIterator = entryElement.elementIterator("objectclass");
            while (ocIterator.hasNext()) {
                final Element ocElement = (Element) ocIterator.next();
                if (ocElement != null && ocElement.hasContent()) {
                    final String ocName = "objectClass";
                    final Attribute entryAttribute = new BasicAttribute(ocName);
                    final Iterator<?> valueIterator = ocElement.elementIterator("oc-value");
                    while (valueIterator.hasNext()) {
                        final Element valueElement = (Element) valueIterator.next();
                        if (valueElement != null) {
                            final String value = valueElement.getText();
                            if (value != null) {
                                entryAttribute.add(value);
                            }
                        }
                    }
                    entryAttributes.put(entryAttribute);
                }
            }

            attrResults = super.createSearchResult(entryElement);
        }
    }

    if (attrResults != null) {
        final Attributes attrs = attrResults.getAttributes();
        if (attrs != null) {
            final NamingEnumeration<? extends Attribute> ae = attrs.getAll();
            if (ae != null) {
                try {
                    while (ae.hasMore()) {
                        entryAttributes.put(ae.next());
                    }
                } catch (NamingException e) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Could not read attribute in SearchResult from parent");
                    }
                }
            }
        }
    }
    return new SearchResult(name, null, entryAttributes);
}

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

private void bindUserObject(DirContext context, String cn, String dn) throws Exception {
    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("inetOrgPerson");
    objectClass.add("person");
    objectClass.add("organizationalperson");
    attributes.put(objectClass);//w w  w .j  a  v  a2  s  .c  om
    attributes.put("cn", cn);
    attributes.put("sn", "foo");
    attributes.put("mail", cn + "@apache.org");
    attributes.put("userPassword", passwordEncoder.encodePassword("foo"));
    attributes.put("givenName", "foo");
    context.createSubcontext(dn, attributes);
}

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

private void initConfiguration() throws NamingException {
    // Create the partition for the tests
    MutablePartitionConfiguration testPartition = new MutablePartitionConfiguration();
    testPartition.setId("NuxeoTestLdapServer");
    testPartition.setSuffix(BASE_DN);/*  w  w  w  .j  a v  a  2 s  .  com*/

    BasicAttributes attributes = new BasicAttributes();
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("domain");
    objectClass.add("extensibleObject");
    attributes.put(objectClass);
    testPartition.setContextEntry(attributes);

    Set<Object> indexedAttrs = new HashSet<Object>();
    indexedAttrs.add("objectClass");
    indexedAttrs.add("uid");
    indexedAttrs.add("cn");
    indexedAttrs.add("ou");
    indexedAttrs.add("uniqueMember");

    // POSIX RFC-2307 schema.
    indexedAttrs.add("gidNumber");
    indexedAttrs.add("uidNumber");

    testPartition.setIndexedAttributes(indexedAttrs);

    Set<MutablePartitionConfiguration> partitions = new HashSet<MutablePartitionConfiguration>();
    partitions.add(testPartition);

    cfg.setPartitionConfigurations(partitions);
}

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

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//  w w  w  .  j  a v  a2  s. c  o  m
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);/*from  ww w  .  ja  v a  2s .  c  o m*/
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

@SuppressWarnings("unused")
private ApacheDS startKerberos() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    kdcServer.setDirectoryService(directoryService);
    // FIXME hard-coded ports
    kdcServer.setTransports(new TcpTransport(6088), new UdpTransport(6088));
    kdcServer.setEnabled(true);/*from   ww  w .  ja  va2 s. c  om*/
    kdcServer.setPrimaryRealm(realm);
    kdcServer.setSearchBaseDn(baseDn);
    kdcServer.setKdcPrincipal("krbtgt/" + realm + "@" + baseDn);
    kdcServer.start();

    // -------------------------------------------------------------------
    // Enable the krb5kdc schema
    // -------------------------------------------------------------------

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    env.put(DirectoryService.JNDI_KEY, directoryService);
    env.put(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
    env.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    InitialLdapContext schemaRoot = new InitialLdapContext(env, null);

    // check if krb5kdc is disabled
    Attributes krb5kdcAttrs = schemaRoot.getAttributes("cn=Krb5kdc");
    boolean isKrb5KdcDisabled = false;
    if (krb5kdcAttrs.get("m-disabled") != null) {
        isKrb5KdcDisabled = ((String) krb5kdcAttrs.get("m-disabled").get()).equalsIgnoreCase("TRUE");
    }

    // if krb5kdc is disabled then enable it
    if (isKrb5KdcDisabled) {
        Attribute disabled = new BasicAttribute("m-disabled");
        ModificationItem[] mods = new ModificationItem[] {
                new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled) };
        schemaRoot.modifyAttributes("cn=Krb5kdc", mods);
    }
    return this;
}

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// www . j  a v  a 2s  .c o m
 * @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);
}