Example usage for javax.naming.directory Attribute getID

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

Introduction

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

Prototype

String getID();

Source Link

Document

Retrieves the id of this attribute.

Usage

From source file:org.projectforge.business.ldap.LdapDao.java

/**
 * @param ctx/*from www . j a v a2s. co  m*/
 * @param ouBase If organizational units are given by the given obj then this parameter will be ignored, otherwise
 *          this is the ou where the new object will be inserted.
 * @param obj
 * @param args
 * @throws NamingException
 */
public void create(final DirContext ctx, final String ouBase, final T obj, final Object... args)
        throws NamingException {
    final String dn = buildDn(ouBase, obj);
    log.info("Create " + getObjectClass() + ": " + dn + ": " + getLogInfo(obj));
    final Attributes attrs = new BasicAttributes();
    final List<ModificationItem> modificationItems = getModificationItems(new ArrayList<ModificationItem>(),
            obj);
    modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", getObjectClass()));
    final String[] additionalObjectClasses = getAdditionalObjectClasses(obj);
    if (additionalObjectClasses != null) {
        for (final String objectClass : additionalObjectClasses) {
            modificationItems.add(createModificationItem(DirContext.ADD_ATTRIBUTE, "objectClass", objectClass));
        }
    }
    for (final ModificationItem modItem : modificationItems) {
        final Attribute attr = modItem.getAttribute();
        LdapUtils.putAttribute(attrs, attr.getID(), (String) attr.get());
    }
    LdapUtils.putAttribute(attrs, "cn", LdapUtils.escapeCommonName(obj.getCommonName()));
    onBeforeBind(dn, attrs, args);
    ctx.bind(dn, null, attrs);
}

From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java

private Subject createSubject(Attributes attributes) {
    String name = "";
    String subjectID = "";
    String description = "";

    if (attributes == null) {
        log.debug("ldap create subject with null attrs");
        return (null);
    }//from   w  w  w. j av  a 2s.com
    try {
        Attribute attribute = attributes.get(subjectIDAttributeName);
        if (attribute == null) {
            log.error("No value for LDAP attribute \"" + subjectIDAttributeName
                    + "\". It is Grouper attribute \"SubjectID\".");
            return null;
        }
        subjectID = ((String) attribute.get()).toLowerCase();
        attribute = attributes.get(nameAttributeName);
        if (attribute == null) {
            log.debug("No immedaite value for attribute \"" + nameAttributeName + "\". Will look later.");
        } else {
            name = (String) attribute.get();
        }
        attribute = attributes.get(descriptionAttributeName);
        if (attribute == null) {
            log.debug(
                    "No immedaite value for attribute \"" + descriptionAttributeName + "\". Will look later.");
        } else {
            description = (String) attribute.get();
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }
    LdapSubject subject = new LdapSubject(subjectID, name, description, this.getSubjectType().getName(),
            this.getId());

    // add the attributes

    Map myAttributes = new HashMap();
    try {
        for (NamingEnumeration e = attributes.getAll(); e.hasMore();) {
            Attribute attr = (Attribute) e.next();
            String attrName = attr.getID();
            // skip the basic ones
            if (attrName.equals(nameAttributeName))
                continue;
            if (attrName.equals(subjectIDAttributeName))
                continue;
            if (attrName.equals(descriptionAttributeName))
                continue;
            Set values = new HashSet();
            for (NamingEnumeration en = attr.getAll(); en.hasMore();) {
                Object value = en.next();
                values.add(value.toString());
            }
            myAttributes.put(attrName, values);
        }
        subject.setAttributes(myAttributes);
    } catch (NamingException e) {
        log.error("Naming error: " + e);
    }

    return subject;
}

From source file:org.springframework.security.ldap.userdetails.LdapUserDetailsManager.java

public void updateUser(UserDetails user) {
    DistinguishedName dn = usernameMapper.buildDn(user.getUsername());

    logger.debug("Updating user '" + user.getUsername() + "' with DN '" + dn + "'");

    List<GrantedAuthority> authorities = getUserAuthorities(dn, user.getUsername());

    DirContextAdapter ctx = loadUserAsContext(dn, user.getUsername());
    ctx.setUpdateMode(true);//www.j  a  va 2  s.co m
    copyToContext(user, ctx);

    // Remove the objectclass attribute from the list of mods (if present).
    List<ModificationItem> mods = new LinkedList<>(Arrays.asList(ctx.getModificationItems()));
    ListIterator<ModificationItem> modIt = mods.listIterator();

    while (modIt.hasNext()) {
        ModificationItem mod = (ModificationItem) modIt.next();
        Attribute a = mod.getAttribute();
        if ("objectclass".equalsIgnoreCase(a.getID())) {
            modIt.remove();
        }
    }

    template.modifyAttributes(dn, mods.toArray(new ModificationItem[mods.size()]));

    // template.rebind(dn, ctx, null);
    // Remove the old authorities and replace them with the new one
    removeAuthorities(dn, authorities);
    addAuthorities(dn, user.getAuthorities());
}

From source file:org.orbeon.oxf.processor.LDAPProcessor.java

private void serialize(List results, Config config, ContentHandler ch) {
    try {/*from w w  w . java  2s  .c  om*/
        ch.startDocument();
        ch.startElement("", "results", "results", SAXUtils.EMPTY_ATTRIBUTES);
        for (Iterator i = results.iterator(); i.hasNext();) {
            SearchResult sr = (SearchResult) i.next();

            ch.startElement("", "result", "result", SAXUtils.EMPTY_ATTRIBUTES);
            addElement(ch, "name", sr.getName());
            try {
                addElement(ch, "fullname", sr.getNameInNamespace());
            } catch (UnsupportedOperationException e) {
                // This seems to be the only  way to know if sr contains a name!
            }
            Attributes attr = sr.getAttributes();
            NamingEnumeration attrEn = attr.getAll();
            while (attrEn.hasMoreElements()) {
                Attribute a = (Attribute) attrEn.next();
                if (config.getAttributes().isEmpty() || config.getAttributes().contains(a.getID())) {
                    ch.startElement("", "attribute", "attribute", SAXUtils.EMPTY_ATTRIBUTES);
                    addElement(ch, "name", a.getID());
                    NamingEnumeration aEn = a.getAll();
                    while (aEn.hasMoreElements()) {
                        Object o = aEn.next();
                        addElement(ch, "value", o.toString());
                    }
                    ch.endElement("", "attribute", "attribute");
                }
            }
            ch.endElement("", "result", "result");
        }
        ch.endElement("", "results", "results");
        ch.endDocument();
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java

public String determineLdapSingleAttributeValue(String dn, String attributeName, Collection<?> values)
        throws NamingException {
    if (values == null || values.isEmpty()) {
        return null;
    }/*from  w w  w . j  a v  a2  s. c  o  m*/

    Collection<String> stringValues = null;
    // Determine item type, try to convert to strings
    Object firstElement = values.iterator().next();
    if (firstElement instanceof String) {
        stringValues = (Collection) values;
    } else if (firstElement instanceof Element) {
        stringValues = new ArrayList<String>(values.size());
        for (Object value : values) {
            Element element = (Element) value;
            stringValues.add(element.getTextContent());
        }
    } else {
        throw new IllegalArgumentException("Unexpected value type " + firstElement.getClass());
    }

    if (stringValues.size() == 1) {
        return stringValues.iterator().next();
    }

    if (StringUtils.isBlank(dn)) {
        throw new IllegalArgumentException(
                "No dn argument specified, cannot determine which of " + values.size() + " values to use");
    }

    LdapName parsedDn = new LdapName(dn);
    for (int i = 0; i < parsedDn.size(); i++) {
        Rdn rdn = parsedDn.getRdn(i);
        Attributes rdnAttributes = rdn.toAttributes();
        NamingEnumeration<String> rdnIDs = rdnAttributes.getIDs();
        while (rdnIDs.hasMore()) {
            String rdnID = rdnIDs.next();
            Attribute attribute = rdnAttributes.get(rdnID);
            if (attributeName.equals(attribute.getID())) {
                for (int j = 0; j < attribute.size(); j++) {
                    Object value = attribute.get(j);
                    if (stringValues.contains(value)) {
                        return (String) value;
                    }
                }
            }
        }
    }

    // Fallback. No values in DN. Just return the first alphabetically-wise value.
    return Collections.min(stringValues);
}

From source file:org.apache.directory.server.tools.commands.exportcmd.ExportCommandExecutor.java

private void execute() throws Exception {
    // Connecting to server and retreiving entries
    NamingEnumeration entries = connectToServerAndGetEntries();

    // Creating destination file
    File destionationFile = new File(ldifFileName);

    // Deleting the destination file if it already exists
    if (destionationFile.exists()) {
        destionationFile.delete();/*from   ww  w  . ja va2s . c o  m*/
    }

    // Creating the writer to generate the LDIF file
    FileWriter fw = new FileWriter(ldifFileName, true);

    BufferedWriter writer = new BufferedWriter(fw);
    OtcLdifComposerImpl composer = new OtcLdifComposerImpl();
    MultiValueMap map = new MultiValueMap();
    //      MultiMap map = new MultiMap() {
    //         // FIXME Stop forking commons-collections.
    //         private final MultiValueMap map = new MultiValueMap();
    //
    //         public Object remove(Object arg0, Object arg1) {
    //            return map.remove(arg0, arg1);
    //         }
    //
    //         public int size() {
    //            return map.size();
    //         }
    //
    //         public Object get(Object arg0) {
    //            return map.get(arg0);
    //         }
    //
    //         public boolean containsValue(Object arg0) {
    //            return map.containsValue(arg0);
    //         }
    //
    //         public Object put(Object arg0, Object arg1) {
    //            return map.put(arg0, arg1);
    //         }
    //
    //         public Object remove(Object arg0) {
    //            return map.remove(arg0);
    //         }
    //
    //         public Collection values() {
    //            return map.values();
    //         }
    //
    //         public boolean isEmpty() {
    //            return map.isEmpty();
    //         }
    //
    //         public boolean containsKey(Object key) {
    //            return map.containsKey(key);
    //         }
    //
    //         public void putAll(Map arg0) {
    //            map.putAll(arg0);
    //         }
    //
    //         public void clear() {
    //            map.clear();
    //         }
    //
    //         public Set keySet() {
    //            return map.keySet();
    //         }
    //
    //         public Set entrySet() {
    //            return map.entrySet();
    //         }
    //      };

    int entriesCounter = 1;
    long t0 = System.currentTimeMillis();

    while (entries.hasMoreElements()) {
        SearchResult sr = (SearchResult) entries.nextElement();
        Attributes attributes = sr.getAttributes();
        NamingEnumeration attributesEnumeration = attributes.getAll();

        map.clear();

        while (attributesEnumeration.hasMoreElements()) {
            Attribute attr = (Attribute) attributesEnumeration.nextElement();
            NamingEnumeration e2 = null;

            e2 = attr.getAll();

            while (e2.hasMoreElements()) {
                Object value = e2.nextElement();
                map.put(attr.getID(), value);
            }
        }

        // Writing entry in the file
        writer.write("dn: " + sr.getNameInNamespace() + "\n");
        writer.write(composer.compose(map) + "\n");

        notifyEntryWrittenListener(sr.getNameInNamespace());
        entriesCounter++;

        if (entriesCounter % 10 == 0) {
            notifyOutputListener(new Character('.'));
        }

        if (entriesCounter % 500 == 0) {
            notifyOutputListener("" + entriesCounter);
        }
    }

    writer.flush();
    writer.close();
    fw.close();

    long t1 = System.currentTimeMillis();

    notifyOutputListener("Done!");
    notifyOutputListener(entriesCounter + " entries exported in " + ((t1 - t0) / 1000) + " seconds");
}

From source file:org.acegisecurity.userdetails.ldap.LdapUserDetailsMapper.java

public Object mapAttributes(String dn, Attributes attributes) throws NamingException {
    LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();

    essence.setDn(dn);//from www .j a  v a  2  s. co  m
    essence.setAttributes(attributes);

    Attribute passwordAttribute = attributes.get(passwordAttributeName);

    if (passwordAttribute != null) {
        essence.setPassword(mapPassword(passwordAttribute));
    }

    // Map the roles
    for (int i = 0; (roleAttributes != null) && (i < roleAttributes.length); i++) {
        Attribute roleAttribute = attributes.get(roleAttributes[i]);

        if (roleAttribute == null) {
            logger.debug("Couldn't read role attribute '" + roleAttributes[i] + "' for user " + dn);
            continue;
        }

        NamingEnumeration attributeRoles = roleAttribute.getAll();

        while (attributeRoles.hasMore()) {
            GrantedAuthority authority = createAuthority(attributeRoles.next());

            if (authority != null) {
                essence.addAuthority(authority);
            } else {
                logger.debug(
                        "Failed to create an authority value from attribute with Id: " + roleAttribute.getID());
            }
        }
    }

    return essence;
}

From source file:org.glite.slcs.pki.bouncycastle.X509PrincipalUtil.java

/**
 * Reads the given {@link Attribute} and recurses into RDN attributes, fills
 * the given vectors.// w ww.j  a  v  a  2s .c om
 * 
 * @param attr
 *            The {@link Attribute} to read.
 * @param oids
 *            The vector of OID.
 * @param values
 *            The vector of value.
 * @param added
 *            The added status vector.
 * @throws NamingException
 *             if a naming error occurs.
 */
private void readAttr(Attribute attr, Vector<DERObjectIdentifier> oids, Vector<Object> values,
        Vector<Boolean> added) throws NamingException {
    // Recursively looking into each attribute
    LOG.debug("Attribute: " + attr);
    for (int i = 0; i < attr.size(); i++) {
        if (attr.get(i) instanceof Attribute) {
            Attribute rdnAttr = (Attribute) attr.get(i);
            LOG.debug("Attribute RDN: " + rdnAttr);
            readAttr(rdnAttr, oids, values, added);
        } else { // Get back the OID from name
            DERObjectIdentifier oid = (DERObjectIdentifier) X509Name.DefaultLookUp
                    .get(Strings.toLowerCase(attr.getID()));
            oids.add(oid);
            Object attrValue = attr.get(i);
            LOG.debug("Attribute value: " + attrValue);
            values.add(attrValue);
            added.add(start_);
            start_ = true;

        }
    }

}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

private Map<String, Object> fromAttributesToMap(Attributes attributes) throws NamingException {
    try {//  w w w  . j a va 2s .c  o  m
        Map<String, Object> map = new HashMap<String, Object>();
        for (NamingEnumeration<? extends Attribute> attrs = attributes.getAll(); attrs.hasMore();) {
            Attribute attr = attrs.next();
            map.put(attr.getID(), AttrUtils.valuesAsObject(attr));
        }
        return map;
    } catch (NamingException e) {
        LogUtils.debug(LOG, "failed to go through attributes when fromAttributesToMap");
        throw e;
    }
}

From source file:com.wfp.utils.LDAPUtils.java

@SuppressWarnings("unchecked")
public static Map<String, String> parseDataAsMap(NamingEnumeration searchResults) {
    Map<String, String> resultAttrMap = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }/*from  w  ww .  j a va2  s.  co  m*/
    // Loop through the search results
    while (searchResults.hasMoreElements()) {

        SearchResult sr = null;
        try {
            sr = (SearchResult) searchResults.next();
        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            if (resultAttrMap == null) {
                resultAttrMap = new HashMap<String, String>();
            }
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                        String attrValue = (String) e.next();

                        resultAttrMap.put(attr.getID(), attrValue);
                    }
                }
            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }

    return resultAttrMap;
}