Example usage for javax.naming.directory Attribute get

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

Introduction

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

Prototype

Object get() throws NamingException;

Source Link

Document

Retrieves one of this attribute's values.

Usage

From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

public Map<String, String> findLdapUserDetails(String userName) {
    Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord());
    HashMap<String, String> userDetails = new HashMap<String, String>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }//w w  w .  ja  v a2  s  .  co  m
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);

    // Load any search filter
    String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();

        // Add the search filter if specified.  This only allows for a single search filter.. i.e. foo=bar.
        String filter;
        if ((searchFilter != null) && (searchFilter.length() != 0)) {
            filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))";
        } else {
            filter = "(" + loginProperty + "=" + userName + ")";
        }

        log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName);

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);
        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change
                log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]);
                // Nothing found for this DN, move to the next one if we have one.
                continue;
            }

            // We use the first match
            SearchResult si = answer.next();
            //generate the DN
            String userDN = null;
            try {
                userDN = si.getNameInNamespace();
            } catch (UnsupportedOperationException use) {
                userDN = si.getName();
                if (userDN.startsWith("\"")) {
                    userDN = userDN.substring(1, userDN.length());
                }
                if (userDN.endsWith("\"")) {
                    userDN = userDN.substring(0, userDN.length() - 1);
                }
                userDN = userDN + "," + baseDNs[x];
            }
            userDetails.put("dn", userDN);

            // Construct the UserDN
            NamingEnumeration<String> keys = si.getAttributes().getIDs();
            while (keys.hasMore()) {
                String key = keys.next();
                Attribute value = si.getAttributes().get(key);
                if ((value != null) && (value.get() != null)) {
                    userDetails.put(key, value.get().toString());
                }
            }
            return userDetails;
        }
        return userDetails;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

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  w  w  w.  j  a  v a 2s. c  o 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: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 {/*from w w  w  .  j  a  v  a2s  . c  o m*/
            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.projectforge.business.ldap.LdapDao.java

/**
 * @param ctx// w w  w . j a v  a2s.c o  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:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

/**
 * @throws NamingException/*from  www  . j  a  va  2s.c  o  m*/
 * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#validatePassword(java.lang.String,java.lang.String)
 */
protected Set<Map<String, String>> buildGroup(Properties systemConfig, String filter) {
    Set<Map<String, String>> ret = new HashSet<Map<String, String>>();
    // Load our LDAP specific properties
    Properties env = getProperties(systemConfig);

    // Load the BaseDN
    String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN);

    // Load the LoginProperty
    String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty);
    if (loginProperty == null) {
        // Use the default
        loginProperty = "cn";
    }
    // Load any information we may need to bind
    String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN);
    String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }
    try {
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        SearchControls searchControls = getSearchControls();
        /*String filter = "(&(objectclass=groupOfUniqueNames)(uniqueMember=uid=" + userName
        + ",ou=People, dc=rhndev, dc=redhat, dc=com))";*/

        // Loop through each configured base DN.  It may be useful
        // in the future to allow for a filter to be configured for
        // each BaseDN, but for now the filter will apply to all.
        String[] baseDNs = baseDN.split(BASEDN_DELIMITER);

        for (int x = 0; x < baseDNs.length; x++) {
            NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls);
            boolean ldapApiEnumerationBugEncountered = false;
            while ((!ldapApiEnumerationBugEncountered) && answer.hasMoreElements()) {//BZ:582471- ldap api bug change
                // We use the first match
                SearchResult si = null;
                try {
                    si = answer.next();
                } catch (NullPointerException npe) {
                    ldapApiEnumerationBugEncountered = true;
                    break;
                }
                Map<String, String> entry = new HashMap<String, String>();
                String name = (String) si.getAttributes().get("cn").get();
                name = name.trim();
                Attribute desc = si.getAttributes().get("description");
                String description = desc != null ? (String) desc.get() : "";
                description = description.trim();
                entry.put("id", name);
                entry.put("name", name);
                entry.put("description", description);
                ret.add(entry);
            }
        }
    } catch (NamingException e) {
        if (e instanceof InvalidSearchFilterException) {
            InvalidSearchFilterException fException = (InvalidSearchFilterException) e;
            String message = "The ldap group filter defined is invalid ";
            log.error(message, fException);
            throw new LdapFilterException(message + " " + fException.getMessage());
        }
        //TODO: check for ldap connection/unavailable/etc. exceptions.
        else {
            log.error("LDAP communication error: " + e.getMessage(), e);
            throw new LdapCommunicationException(e);
        }
    }

    return ret;
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String getAttributes(DirContext oDirContext, String sMapperAttribute, Name name) throws OAException {
    String sReturn = null;//from www .  j a va  2 s .  c o m
    try {
        if (sMapperAttribute == null) {
            _logger.error("No attribute name to map to supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        Attributes attributes = null;
        try {
            attributes = oDirContext.getAttributes(name, new String[] { sMapperAttribute });
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Could not resolve attribute '");
            sbFailed.append(sMapperAttribute);
            sbFailed.append("' while retrieving attributes for id: ");
            sbFailed.append(name);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        Attribute attrMapping = attributes.get(sMapperAttribute);
        if (attrMapping == null) {
            _logger.debug("Attribute not found: " + sMapperAttribute);
        } else {
            Object oValue = attrMapping.get();
            if (!(oValue instanceof String)) {
                StringBuffer sbError = new StringBuffer("Returned value for attribute '");
                sbError.append(sMapperAttribute);
                sbError.append("' has a value which is not of type 'String'");
                _logger.error(sbError.toString());
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
            sReturn = (String) oValue;
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + name);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + name, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
    return sReturn;
}

From source file:ru.efo.security.ADUserDetailsService.java

private ADUserDetails loadUserByUsername(DirContext context, String username, String password)
        throws UsernameNotFoundException {
    try {//from   www  .j  a  va2s.  com
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // search for username
        NamingEnumeration<SearchResult> renum = context.search(userSearchBase,
                "(&(objectClass=user)(sAMAccountName={0}))", new Object[] { username }, controls);
        if (!renum.hasMoreElements()) {
            throw new UsernameNotFoundException("User '" + username + "' is not exist");
        }
        SearchResult result = renum.next();
        final Attributes attributes = result.getAttributes();

        // User's display name
        String displayName = null;
        Attribute attr = attributes.get(displayNameAttribute);
        if (attr != null) {
            displayName = attr.get().toString();
        }
        if (!StringUtils.hasText(displayName))
            displayName = username;
        logger.log(Level.FINE, "Display name: " + displayName);

        // User's email
        String email = null;
        attr = attributes.get(emailAttribute);
        if (attr != null) {
            email = attr.get().toString();
        }
        logger.log(Level.FINE, "E-mail: " + email);

        // User's phone number
        String phone = null;
        attr = attributes.get(phoneAttribute);
        if (attr != null) {
            phone = attr.get().toString();
        }
        logger.log(Level.FINE, "Phone: " + phone);

        // Is user blocked
        boolean blocked = false;
        attr = attributes.get("userAccountControl");
        if (attr != null) {
            blocked = (Long.parseLong(attr.get().toString()) & 2) != 0;
        }
        logger.log(Level.FINE, "Blocked: " + blocked);

        // describe roles and groups
        final Set<String> roles = new TreeSet<>();
        final Set<String> groups = new TreeSet<>();
        Attribute memberOf = attributes.get("memberOf");
        describeRoles(context, memberOf, groups, roles);

        // Describe user primary role
        Attribute attrPrimaryGroupId = attributes.get("primaryGroupId");
        Attribute attrObjectSid = attributes.get("objectSid");
        if (attrPrimaryGroupId != null && attrObjectSid != null) {
            int primaryGroupId = Integer.parseInt(attrPrimaryGroupId.get().toString());
            byte[] objectSid = (byte[]) attrObjectSid.get();
            // add primary group RID
            for (int i = 0; i < 4; i++) {
                objectSid[objectSid.length - 4 + i] = (byte) (primaryGroupId & 0xFF);
                primaryGroupId >>= 8;
            }
            StringBuilder tmp = new StringBuilder();
            for (int i = 2; i <= 7; i++) {
                tmp.append(Integer.toHexString(objectSid[i] & 0xFF));
            }
            // convert objectSid to String
            StringBuilder sidBuilder = new StringBuilder("S-").append(objectSid[0]).append("-")
                    .append(Long.parseLong(tmp.toString(), 16));
            // the sub authorities count
            int count = objectSid[1];
            // add authorities
            for (int i = 0; i < count; i++) {
                tmp.setLength(0);

                int offset = i * 4;
                tmp.append(String.format("%02X%02X%02X%02X", (objectSid[11 + offset] & 0xFF),
                        (objectSid[10 + offset] & 0xFF), (objectSid[9 + offset] & 0xFF),
                        (objectSid[8 + offset] & 0xFF)));
                sidBuilder.append('-').append(Long.parseLong(tmp.toString(), 16));
            }
            SearchControls searchControls = new SearchControls();
            searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            renum = context.search(userSearchBase, "(&(objectClass=group)(objectSid={0}))",
                    new Object[] { sidBuilder.toString() }, searchControls);
            if (renum.hasMoreElements()) {
                result = renum.next();
                attr = result.getAttributes().get("distinguishedName");
                describeRoles(context, attr, groups, roles);
            }
        }
        return new ADUserDetails(username, password, displayName, email, phone, blocked, groups, roles);
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not find user '" + username + "'", ex);
        throw new UsernameNotFoundException(ex.getMessage());
    }
}

From source file:fr.cls.atoll.motu.web.services.MotuOGCFrontController.java

/**
 * Method that returns an adapted version of the servlet config returned by the super method. Thus, the
 * {@link ServletContext#getRealPath(String)} is overriden to allow a nice resolution of a file among
 * external directories.//from  w w w  .j a v  a  2s  . c o  m
 * 
 * @return the servlet context instance of this servlet.
 */
private ServletConfig wrapServletConfig(final ServletConfig sc) {
    return new ServletConfigAdapter(sc) {
        private ServletContextAdapter ctx = null;

        @Override
        public ServletContext getServletContext() {
            if (ctx == null) {
                ctx = new ServletContextAdapter(super.getServletContext()) {

                    /**
                     * First try to resolve the given location as a resource (using classpath extensions
                     * if necessary). If this try fails, then let the process go on.
                     */
                    @Override
                    public String getRealPath(String name) {
                        try {
                            // try the classpath
                            URL url = ConfigLoader.getInstance().get(name);

                            if (url != null) {
                                return url.toString();
                            }

                            // try the current context naming
                            // TODO: try to see if we can keep independence with the container
                            ApplicationContext appCtx = null;
                            if (ctx.getRootContext() instanceof ApplicationContextFacade) {

                                Field privateStringField = ApplicationContextFacade.class
                                        .getDeclaredField("context");
                                privateStringField.setAccessible(true);
                                Object context = privateStringField.get(ctx.getRootContext());

                                if ((context != null) && context instanceof ApplicationContext) {
                                    DirContext dc = ((ApplicationContext) context).getResources();

                                    Attributes atts = dc.getAttributes(name);
                                    for (NamingEnumeration e = atts.getAll(); e.hasMore();) {
                                        final Attribute a = (Attribute) e.next();

                                        if ("canonicalPath".equals(a.getID())) {
                                            String s = a.get().toString();
                                            File f = new File(s);
                                            if (f.exists()) {
                                                return f.getAbsolutePath();
                                            }
                                        }
                                    }
                                }
                            }

                            throw new IllegalStateException("name " + name
                                    + " not resolved on classpath. Try default (servlet) resolution.");

                        } catch (Exception e) {
                            return super.getRealPath(name);
                        }
                    }
                };
            }
            return ctx;
        }
    };
}

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   www  . j  a v 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;
}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String searchAttributes(DirContext oDirContext, String sIDAttribute, String sMapperAttribute, String id)
        throws OAException {
    String sReturn = null;/*  w  ww.jav a2  s  .c om*/
    NamingEnumeration oNamingEnumeration = null;
    try {
        if (sIDAttribute == null) {
            _logger.error("No attribute name to map from supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        StringBuffer sbQuery = new StringBuffer("(");
        sbQuery.append(sIDAttribute);
        sbQuery.append("=");
        sbQuery.append(JNDIUtil.escapeLDAPSearchFilter(id));
        sbQuery.append(")");
        String sSearchQuery = sbQuery.toString();

        String sSearchFor = sMapperAttribute;
        if (sSearchFor == null)
            sSearchFor = "*";

        SearchControls oScope = new SearchControls();
        oScope.setSearchScope(SearchControls.SUBTREE_SCOPE);
        oScope.setReturningAttributes(new String[] { sSearchFor });

        try {
            oNamingEnumeration = oDirContext.search(_sDNBase, sSearchQuery, oScope);
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Wrong filter: ");
            sbFailed.append(sSearchQuery);
            sbFailed.append(" while searching for attributes for id: ");
            sbFailed.append(id);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        if (!oNamingEnumeration.hasMore()) {
            _logger.debug("No result when searching for: " + sSearchQuery);
        } else {
            SearchResult oSearchResult = (SearchResult) oNamingEnumeration.next();

            if (sMapperAttribute == null) {
                sReturn = oSearchResult.getName();
                sReturn += "," + _sDNBase;
            } else {
                Attributes oSearchedAttributes = oSearchResult.getAttributes();
                Attribute attrMapping = oSearchedAttributes.get(sMapperAttribute);
                if (attrMapping == null) {
                    _logger.debug("Mapping attribute not found: " + sMapperAttribute);
                } else {
                    Object oValue = attrMapping.get();
                    if (!(oValue instanceof String)) {
                        StringBuffer sbError = new StringBuffer("Returned value for mapping attribute '");
                        sbError.append(_sMapperAttribute);
                        sbError.append("' has a value which is not of type 'String'");
                        _logger.error(sbError.toString());
                        throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
                    }
                    sReturn = (String) oValue;
                }
            }
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + id, e);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + id, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    } finally {
        if (oNamingEnumeration != null) {
            try {
                oNamingEnumeration.close();
            } catch (Exception e) {
                _logger.error("Could not close Naming Enumeration after searching for id: " + id, e);
            }
        }
    }
    return sReturn;
}