Example usage for javax.naming.directory SearchResult getAttributes

List of usage examples for javax.naming.directory SearchResult getAttributes

Introduction

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

Prototype

public Attributes getAttributes() 

Source Link

Document

Retrieves the attributes in this search result.

Usage

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

/**
 * Check if User already exists on system.
 *
 * @param user/*  ww  w .ja  v  a  2  s.c  om*/
 *            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:ru.runa.wfe.security.logic.LdapLogic.java

private void fillTargetActorsRecursively(DirContext dirContext, Set<Actor> recursiveActors,
        SearchResult searchResult, Map<String, SearchResult> groupResultsByDistinguishedName,
        Map<String, Actor> actorsByDistinguishedName) throws NamingException {
    NamingEnumeration<String> namingEnum = (NamingEnumeration<String>) searchResult.getAttributes()
            .get(ATTR_GROUP_MEMBER).getAll();
    while (namingEnum.hasMore()) {
        String executorDistinguishedName = namingEnum.next();
        SearchResult groupSearchResult = groupResultsByDistinguishedName.get(executorDistinguishedName);
        if (groupSearchResult != null) {
            fillTargetActorsRecursively(dirContext, recursiveActors, groupSearchResult,
                    groupResultsByDistinguishedName, actorsByDistinguishedName);
        } else {// w w  w .  ja  va2 s. c  om
            Actor actor = actorsByDistinguishedName.get(executorDistinguishedName);
            if (actor != null) {
                recursiveActors.add(actor);
            } else {
                Matcher m = getPatternForMissedPeople().matcher(executorDistinguishedName);
                String executorPath = m.replaceAll("");
                Attribute samAttribute = dirContext.getAttributes(executorPath).get(ATTR_ACCOUNT_NAME);
                if (samAttribute != null) {
                    String executorName = samAttribute.get().toString();
                    log.debug("Executor name " + executorDistinguishedName + " fetched by invocation: "
                            + executorName);
                    try {
                        Executor executor = executorDao.getExecutor(executorName);
                        if (executor instanceof Actor) {
                            recursiveActors.add((Actor) executor);
                        }
                    } catch (ExecutorDoesNotExistException e) {
                        log.warn(e.getMessage() + " for '" + executorDistinguishedName + "'");
                    }
                } else {
                    log.warn("Not found '" + executorDistinguishedName
                            + "' neither in group or actor maps or by invocation");
                }
            }
        }
    }
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchFromUsers(DirContext context, Map filters) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;

    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    searchResultEnum = context.search(userBase, filter, searchControls);
    //roop of retrieval result

    List users = new ArrayList();
    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        String dn = searchResult.getName() + "," + userBase;
        LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
        users.add(user);/* w  w  w  .j  a v  a2  s.  c  o  m*/
    }
    return users;
}

From source file:org.apache.hadoop.security.LdapGroupsMapping.java

List<String> doGetGroups(String user) throws NamingException {
    List<String> groups = new ArrayList<String>();

    DirContext ctx = getDirContext();

    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = ctx.search(baseDN, userSearchFilter, new Object[] { user },
            SEARCH_CONTROLS);/*from   ww w. j  a va 2s . co  m*/
    if (results.hasMoreElements()) {
        SearchResult result = results.nextElement();
        String userDn = result.getNameInNamespace();

        NamingEnumeration<SearchResult> groupResults = null;

        if (isPosix) {
            String gidNumber = null;
            String uidNumber = null;
            Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
            Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
            if (gidAttribute != null) {
                gidNumber = gidAttribute.get().toString();
            }
            if (uidAttribute != null) {
                uidNumber = uidAttribute.get().toString();
            }
            if (uidNumber != null && gidNumber != null) {
                groupResults = ctx.search(
                        baseDN, "(&" + groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "("
                                + groupMemberAttr + "={1})))",
                        new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS);
            }
        } else {
            groupResults = ctx.search(baseDN, "(&" + groupSearchFilter + "(" + groupMemberAttr + "={0}))",
                    new Object[] { userDn }, SEARCH_CONTROLS);
        }
        if (groupResults != null) {
            while (groupResults.hasMoreElements()) {
                SearchResult groupResult = groupResults.nextElement();
                Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
                groups.add(groupName.get().toString());
            }
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") return " + groups);
    }
    return groups;
}

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

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override/*from   w w  w . j a v a 2s. c o  m*/
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}

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

public Map<String, Collection<String>> findUsersWithRoles(DirContext dirContext)
        throws LdapControllerException {
    Map<String, Collection<String>> usersWithRoles = new HashMap<String, Collection<String>>();

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {/*from w w w . j  av a2 s.  c om*/

        SearchControls searchControls = new SearchControls();

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

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

        namingEnumeration = dirContext.search(getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();

            String groupName = searchResult.getName();
            // cn=blabla we only want bla bla
            groupName = StringUtils.substringAfter(groupName, "=");

            Attribute uniqueMemberAttr = searchResult.getAttributes().get("uniquemember");

            if (uniqueMemberAttr != null) {
                NamingEnumeration<String> allMembersEnum = (NamingEnumeration<String>) uniqueMemberAttr
                        .getAll();
                while (allMembersEnum.hasMore()) {
                    String userName = allMembersEnum.next();
                    // uid=blabla we only want bla bla
                    userName = StringUtils.substringAfter(userName, "=");
                    userName = StringUtils.substringBefore(userName, ",");
                    Collection<String> roles = usersWithRoles.get(userName);
                    if (roles == null) {
                        roles = new HashSet<String>();
                    }

                    roles.add(groupName);

                    usersWithRoles.put(userName, roles);

                }
            }

            log.debug("found groupName: '{}' with users: {}", groupName);

        }

        return usersWithRoles;
    } catch (NamingException e) {
        throw new LdapControllerException(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.infoscoop.account.ldap.LDAPAccountManager.java

public IAccount getUser(String uid) throws NamingException {

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration searchResultEnum;
    Map filters = new HashMap();

    String uidAttrName = "uid";
    if (this.propAttrMap.containsKey("user_id")) {
        try {//from  w ww  .ja  v a  2  s  .c  o  m
            uidAttrName = (String) this.propAttrMap.get("user_id");
        } catch (Exception ex) {
            //ignore
        }
    }
    if (uid != null && !"".equals(uid))
        filters.put(uidAttrName, uid);

    DirContext context = null;
    try {
        context = this.initContext();
        searchResultEnum = context.search(userBase, buildFilterByUid(filters), searchControls);
        //roop of retrieval result

        while (searchResultEnum.hasMore()) {
            SearchResult searchResult = (SearchResult) searchResultEnum.next();

            String dn = searchResult.getName() + "," + userBase;
            LDAPAccount user = createLDAPUser(dn, searchResult.getAttributes());
            setGroup(context, user);

            return user;
        }

        return null;
    } finally {
        if (context != null)
            context.close();
    }
}

From source file:org.apache.openaz.xacml.std.pip.engines.ldap.ConfigurableLDAPResolver.java

private Attribute decodeResultValue(SearchResult searchResult, String view, PIPRequest viewRequest) {
    AttributeValue<?> attributeValue = null;
    Collection<AttributeValue<?>> attributeMultiValue = null;
    DataType<?> dataType = null;/*from w w w.  ja v  a  2 s.  c o m*/

    this.logger.warn("(" + id + ") " + "SearchResult attributes: " + searchResult.getAttributes());
    try {
        dataType = dataTypeFactory.getDataType(viewRequest.getDataTypeId());
        if (dataType == null) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("(" + id + ") " + "Unknown data type in " + viewRequest);
            }
            return null;
        }

        if ("dn".equalsIgnoreCase(view)) {
            attributeValue = dataType.createAttributeValue(searchResult.getNameInNamespace());
        } else {
            javax.naming.directory.Attribute dirAttr = searchResult.getAttributes().get(view);
            if (dirAttr != null) {
                if (this.logger.isTraceEnabled()) {
                    this.logger.trace(
                            "(" + id + ") " + "directory attribute '" + view + "' value is '" + dirAttr + "'");
                }
                // we could guide this more elaborately by object class ..
                if (dirAttr.size() == 1) {
                    attributeValue = dataType.createAttributeValue(dirAttr.get().toString());
                } else {
                    if (this.logger.isTraceEnabled()) {
                        this.logger
                                .trace("(" + id + ") " + "SearchResult yields a multi-valued '" + view + "'");
                    }
                    attributeMultiValue = new HashSet<AttributeValue<?>>();
                    // we should
                    for (int i = 0; i < dirAttr.size(); i++) {
                        attributeMultiValue.add(dataType.createAttributeValue(dirAttr.get().toString()));
                    }
                }
            } else {
                this.logger.warn("(" + id + ") " + "SearchResult did not provide a value for '" + view + "'");
                return null;
            }
        }
    } catch (DataTypeException dtx) {
        this.logger.error("(" + id + ") " + "Failed to decode search result", dtx);
        return null;
    } catch (NamingException nx) {
        this.logger.error("(" + id + ") " + "Failed to decode search result", nx);
        return null;
    }

    Attribute attr = null;
    if (attributeMultiValue == null) {
        attr = new StdAttribute(viewRequest.getCategory(), viewRequest.getAttributeId(), attributeValue,
                viewRequest.getIssuer(), false);
    } else {
        attr = new StdAttribute(viewRequest.getCategory(), viewRequest.getAttributeId(), attributeMultiValue,
                viewRequest.getIssuer(), false);
    }
    this.logger.warn("(" + id + ") " + " providing attribute " + attr);
    return attr;
}

From source file:it.webappcommon.lib.LDAPHelper.java

/**
 * @param args//ww  w . j ava  2 s . co m
 *            the command line arguments
 */
// public static void main(String[] args) {
private List<UserInfo> search(String filter) throws NamingException {
    DirContext ctx = null;
    SearchControls ctls = null;
    Properties env = new Properties();
    List<UserInfo> res = new ArrayList<UserInfo>();
    boolean trovatiRisultati = false;

    env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT);

    env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");

    if (org.apache.commons.lang3.StringUtils.isEmpty(loginDomain)) {
        env.put(Context.SECURITY_PRINCIPAL, loginUserName);
    } else {
        env.put(Context.SECURITY_PRINCIPAL, loginDomain + "\\" + loginUserName);
    }
    env.put(Context.SECURITY_CREDENTIALS, loginPassword);

    try {
        ctx = new InitialDirContext(env);

        ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // String filter = "";
        // // filter = "(&(objectClass=inetOrgPerson)(objectClass=person))";
        // filter = FILTER_USERS_ACTIVE;

        // Tutti i membri di un gruppo
        // (objectCategory=user)(memberOf=CN=QA Users,OU=Help
        // Desk,DC=dpetri,DC=net)

        // ESEMPI
        // http://www.petri.co.il/ldap_search_samples_for_windows_2003_and_exchange.htm

        // Account disabled
        // (UserAccountControl:1.2.840.113556.1.4.803:=2)

        NamingEnumeration<SearchResult> answer = ctx.search(areaWhereSearch, filter, ctls);

        UserInfo userInfo = null;
        while (answer.hasMoreElements()) {
            trovatiRisultati = true;

            SearchResult a = answer.nextElement();
            // logger.debug(a.getNameInNamespace());

            Attributes result = a.getAttributes();

            if (result == null) {
                // System.out.print("Attributi non presenti");
            } else {
                NamingEnumeration<? extends Attribute> attributi = result.getAll();

                userInfo = new UserInfo();
                while (attributi.hasMoreElements()) {
                    Attribute att = attributi.nextElement();
                    // logger.debug(att.getID());

                    String value = "";
                    // for (NamingEnumeration vals = att.getAll();
                    // vals.hasMoreElements(); logger.debug("\t" +
                    // vals.nextElement()))
                    // ;
                    NamingEnumeration<?> vals = att.getAll();
                    while (vals.hasMoreElements()) {
                        Object val = vals.nextElement();

                        // logger.debug("\t" + val);
                        value = (value.isEmpty()) ? value + val.toString() : value + ";" + val.toString();
                    }

                    if (att.getID().equalsIgnoreCase(FIELD_ACCOUNT_NAME)) {
                        // userInfo.setFIELD_ACCOUNT_NAME(value);
                        userInfo.setAccount(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_COGNOME)) {
                        // userInfo.setFIELD_COGNOME(value);
                        userInfo.setCognome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_EMAIL)) {
                        // userInfo.setFIELD_EMAIL(value);
                        userInfo.setEmail(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_GROUPS)) {
                        // userInfo.setFIELD_GROUPS(value);
                        userInfo.setGruppi(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME)) {
                        // userInfo.setFIELD_NOME(value);
                        userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_COMPLETO)) {
                        // userInfo.setFIELD_NOME_COMPLETO(value);
                        userInfo.setNomeCompleto(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_NOME_VISUALIZZATO)) {
                        // userInfo.setFIELD_NOME_VISUALIZZATO(value);
                        // userInfo.setNome(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_TEL)) {
                        // userInfo.setFIELD_TEL(value);
                        userInfo.setTel(value);
                    } else if (att.getID().equalsIgnoreCase(FIELD_UFFICIO)) {
                        // userInfo.setFIELD_UFFICIO(value);
                        userInfo.setUfficio(value);
                    }
                    // res.put(att.getID(), value);
                }

                // Attribute attr = result.get("cn");
                // if (attr != null) {
                // logger.debug("cn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("sn");
                // if (attr != null) {
                // logger.debug("sn:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // attr = result.get("mail");
                // if (attr != null) {
                // logger.debug("mail:");
                // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // }
                //
                // // attr = result.get("uid");
                // // if (attr != null) {
                // // logger.debug("uid:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }
                // //
                // // attr = result.get("userPassword");
                // // if (attr != null) {
                // // logger.debug("userPassword:");
                // // for (NamingEnumeration vals = attr.getAll();
                // vals.hasMoreElements(); logger.debug("\t" +
                // vals.nextElement()));
                // // }

                if (userInfo != null) {
                    res.add(userInfo);
                }
            }
        }
    } catch (NamingException ne) {
        // ne.printStackTrace();
        logger.error(ne);
        throw ne;
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (Exception e) {
        }
    }

    // Azzero l'hash map
    if (!trovatiRisultati) {
        res = null;
    }

    return res;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //from  w w w.  j av a2s.c om
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}