Example usage for javax.naming NamingEnumeration nextElement

List of usage examples for javax.naming NamingEnumeration nextElement

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration nextElement.

Prototype

E nextElement();

Source Link

Document

Returns the next element of this enumeration if this enumeration object has at least one more element to provide.

Usage

From source file:org.apache.catalina.startup.TldConfig.java

private void tldScanResourcePathsWebInf(DirContext resources, String rootPath, Set tldPaths)
        throws IOException {

    if (log.isTraceEnabled()) {
        log.trace("  Scanning TLDs in " + rootPath + " subdirectory");
    }/*from   w  w w.  j  a  v  a2  s  . c o  m*/

    try {
        NamingEnumeration items = resources.list(rootPath);
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = rootPath + "/" + item.getName();
            if (!resourcePath.endsWith(".tld") && (resourcePath.startsWith("/WEB-INF/classes")
                    || resourcePath.startsWith("/WEB-INF/lib"))) {
                continue;
            }
            if (resourcePath.endsWith(".tld")) {
                if (log.isTraceEnabled()) {
                    log.trace("   Adding path '" + resourcePath + "'");
                }
                tldPaths.add(resourcePath);
            } else {
                tldScanResourcePathsWebInf(resources, resourcePath, tldPaths);
            }
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }
}

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

/**
 * @param args/*w  w  w  .  ja  va  2  s.  com*/
 *            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.codehaus.plexus.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean("ldap.bind.authenticator.enabled")
            || (!config.getBoolean("ldap.bind.authenticator.allowEmptyPasswords", false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getPrincipal(), null);
    }/*from  w w w .j av a  2 s  .  c o  m*/

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

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

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getPrincipal() + "))";

    log.info("Searching for users with filter: \'{}\'" + " from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = getLdapConnection();
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getPrincipal());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getPrincipal());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.info("Found user?: {}", results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getPrincipal());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getPrincipal(), userDn);
            } else {
                return new AuthenticationResult(false, source.getPrincipal(), null);
            }
        }

        log.info("Attempting Authenication: + {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        return new AuthenticationResult(true, source.getPrincipal(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getPrincipal(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:ldap.ActiveLoginImpl.java

/**
 * This does a light copy of an attributes list (such as a UserAccount, if we need to modify it but
 * want to keep the original userAccount)
 * @param oldAtts/*from w  w  w .jav a  2 s .  c  o m*/
 * @return a light copy of the original attributes list.
 */
public Attributes copyAttributes(Attributes oldAtts) {
    BasicAttributes atts = new BasicAttributes();
    NamingEnumeration attList = oldAtts.getAll();
    while (attList.hasMoreElements()) // shouldn't throw an exception, so use normal enumeration methods
    {
        Attribute att = (Attribute) attList.nextElement();
        atts.put(att);
    }
    return atts;
}

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Convert a <i>Contact</i> into a LDAP inetOrgPerson set of attributes.
 * This method is used in from Client to Server
 * /*  w  ww.jav a2s  .c  o m*/
 * @param contact
 *            contact to transform into Attributes
 * @return Attributes representation of the contact
 */
public Attributes createEntry(Contact contact) {

    if (logger.isTraceEnabled())
        logger.trace("Working on contact:" + contact.getUid());

    Attributes attributeSet = new BasicAttributes();
    Attribute objClass = new BasicAttribute("objectClass");
    if (logger.isDebugEnabled())
        logger.debug("Ok let's add objectclass");

    objClass.add("inetOrgPerson");
    objClass.add("person");

    attributeSet.put(objClass);
    try {

        if (contact.getUid() == null) {
            contact.setUid(createUniqueId(contact));
            logger.info("UID is now: " + contact.getUid());
        }

        // Split contact object into sub-objects
        Name name = contact.getName();
        PersonalDetail personal = contact.getPersonalDetail();
        BusinessDetail business = contact.getBusinessDetail();

        List phones = personal.getPhones();
        List businessPhones = business.getPhones();

        List mails = personal.getEmails();
        List note = contact.getNotes();

        // personal address
        Address addr = personal.getAddress();

        // if displayname doesn't exist and the firstname and the lastname
        // are not both defined, this will result in a NullPointerException
        // I don't want to support any other ways of doing this right now.
        // a solution could be to use an UID for the rdn
        if (name != null) {

            if (propertyCheck(name.getLastName())) {
                attributeSet.put(new BasicAttribute("sn", name.getLastName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("sn", ""));
            }

            if (propertyCheck(name.getFirstName())) {
                attributeSet
                        .put(new BasicAttribute("givenName", name.getFirstName().getPropertyValueAsString()));
            } else {
                attributeSet.put(new BasicAttribute("givenName", ""));
            }

            attributeSet.put(new BasicAttribute("cn", name.getFirstName().getPropertyValueAsString() + " "
                    + name.getLastName().getPropertyValueAsString()));
        }

        // Company name
        if (business != null && propertyCheck(business.getCompany())) {
            attributeSet.put(new BasicAttribute("o", business.getCompany().getPropertyValueAsString()));
        }

        // Adding phones
        if (phones != null && !phones.isEmpty()) {

            Iterator iter2 = phones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Home phones
                if (phone.getPhoneType().equals("HomeTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("homePhone", phone.getPropertyValueAsString()));
                }

                // MobilePhones
                if (phone.getPhoneType().equals("MobileTelephoneNumber"))
                    attributeSet.put(new BasicAttribute("mobile", phone.getPropertyValueAsString()));

            }
        }

        // Adding business phones
        if (businessPhones != null && !businessPhones.isEmpty()) {

            Iterator iter2 = businessPhones.iterator();
            while (iter2.hasNext()) {
                Phone phone = (Phone) iter2.next();

                // if empty, no need to check type
                if (!propertyCheck(phone))
                    continue;

                // Business phones
                if (phone.getPhoneType().equals("BusinessTelephoneNumber")) {
                    attributeSet.put(new BasicAttribute("telephoneNumber", phone.getPropertyValueAsString()));
                }
                // Fax
                if (phone.getPhoneType().equals("BusinessFaxNumber")) {
                    attributeSet.put(
                            new BasicAttribute("facsimiletelephonenumber", phone.getPropertyValueAsString()));
                }
            }
        }

        if (mails != null && !mails.isEmpty()) {

            Iterator iter1 = mails.iterator();

            // For each email address, add it
            while (iter1.hasNext()) {
                Email mail = (Email) iter1.next();
                if (propertyCheck(mail))
                    attributeSet.put(new BasicAttribute("mail", mail.getPropertyValueAsString()));
            }
        }

        // Address
        if (addr != null) {
            if (propertyCheck(personal.getAddress().getPostalCode()))
                attributeSet.put(new BasicAttribute("postalCode",
                        personal.getAddress().getPostalCode().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getStreet()))
                attributeSet.put(new BasicAttribute("postalAddress",
                        personal.getAddress().getStreet().getPropertyValueAsString()));

            if (propertyCheck(personal.getAddress().getCity()))
                attributeSet.put(
                        new BasicAttribute("l", personal.getAddress().getCity().getPropertyValueAsString()));
        }

        // Notes
        if (note != null && !note.isEmpty()) {
            Iterator note1 = note.iterator();
            while (note1.hasNext()) {
                Note nota = (Note) note1.next();
                if (propertyCheck(nota))
                    attributeSet.put(new BasicAttribute("description", nota.getPropertyValueAsString()));
            }
        }

        logger.info("Resulting LDAPAttributeSet is:");

        NamingEnumeration<String> ids = attributeSet.getIDs();

        while (ids.hasMoreElements()) {
            String attrID = ids.nextElement();
            logger.info(attrID + ": " + ((String) attributeSet.get(attrID).get()));

        }

        // Create the LDAPEntry with dn and attributes
        // THE DN is the DisplayName
        return attributeSet;

    } catch (Exception e) {
        logger.warn("Unable to create LDAPEntry from Contact: " + e.toString(), e);
        return null;
    }
}

From source file:org.apache.archiva.redback.authentication.ldap.LdapBindAuthenticator.java

public AuthenticationResult authenticate(AuthenticationDataSource s) throws AuthenticationException {
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) s;

    if (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ENABLED)
            || (!config.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
                    && StringUtils.isEmpty(source.getPassword()))) {
        return new AuthenticationResult(false, source.getUsername(), null);
    }//from   w w  w  . j a v  a 2  s  . c  o  m

    SearchControls ctls = new SearchControls();

    ctls.setCountLimit(1);

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

    String filter = "(&(objectClass=" + mapper.getUserObjectClass() + ")"
            + (mapper.getUserFilter() != null ? mapper.getUserFilter() : "") + "(" + mapper.getUserIdAttribute()
            + "=" + source.getUsername() + "))";

    log.debug("Searching for users with filter: '{}' from base dn: {}", filter, mapper.getUserBaseDn());

    LdapConnection ldapConnection = null;
    LdapConnection authLdapConnection = null;
    NamingEnumeration<SearchResult> results = null;
    try {
        ldapConnection = getLdapConnection();
        // check the cache for user's userDn in the ldap server
        String userDn = ldapCacheService.getLdapUserDn(source.getUsername());

        if (userDn == null) {
            log.debug("userDn for user {} not found in cache. Retrieving from ldap server..",
                    source.getUsername());

            DirContext context = ldapConnection.getDirContext();

            results = context.search(mapper.getUserBaseDn(), filter, ctls);

            log.debug("Found user '{}': {}", source.getUsername(), results.hasMoreElements());

            if (results.hasMoreElements()) {
                SearchResult result = results.nextElement();

                userDn = result.getNameInNamespace();

                log.debug("Adding userDn {} for user {} to the cache..", userDn, source.getUsername());

                // REDBACK-289/MRM-1488 cache the ldap user's userDn to lessen calls to ldap server
                ldapCacheService.addLdapUserDn(source.getUsername(), userDn);
            } else {
                return new AuthenticationResult(false, source.getUsername(), null);
            }
        }

        log.debug("Attempting Authenication: {}", userDn);

        authLdapConnection = connectionFactory.getConnection(userDn, source.getPassword());

        log.info("user '{}' authenticated", source.getUsername());

        return new AuthenticationResult(true, source.getUsername(), null);
    } catch (LdapException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } catch (NamingException e) {
        return new AuthenticationResult(false, source.getUsername(), e);
    } finally {
        closeNamingEnumeration(results);
        closeLdapConnection(ldapConnection);
        if (authLdapConnection != null) {
            closeLdapConnection(authLdapConnection);
        }
    }
}

From source file:com.funambol.LDAP.dao.impl.ContactDAO.java

/**
 * Here's the place where all the magic happens: This method transforms a
 * LDAP entry to a <i>Contact</i> object.
 * /*w w w  . j a v  a2 s  .  c o  m*/
 * @param entry
 *            The LDAP entry
 * @return contact from the LDAP server
 */
public Contact createContact(Attributes attrs) {

    if (attrs == null) {
        logger.warn("Entry from LDAP is null so won't be able to create a contact");
        return null;
    }
    try {
        if (logger.isDebugEnabled())
            logger.debug("Getting attribute cn");

        String cn = (attrs.get("cn") != null) ? (String) attrs.get("cn").get() : "null";
        // logger.info("Getting attribute " + ldapId);
        // String entryId = ( attrs.get(ldapId) != null ) ? (String)
        // attrs.get(ldapId).get() : "null";

        if (logger.isDebugEnabled()) {
            logger.debug("Creating Contact for " + cn
            // + ". Id is ( "+ entryId + " )"
            );
        }
        Contact contact = new Contact();

        /* Set name */
        Name name = new Name();
        if (attrs.get("cn") != null) {
            name.getDisplayName().setPropertyValue(cn);
        }
        if (attrs.get("givenName") != null) {
            name.getFirstName().setPropertyValue((String) attrs.get("givenName").get());
        }
        if (attrs.get("sn") != null) {
            name.getLastName().setPropertyValue((String) attrs.get("sn").get());
        }
        if (attrs.get("middleName") != null) {
            name.getMiddleName().setPropertyValue((String) attrs.get("middleName").get());
        }
        if (attrs.get("title") != null) {
            name.getSalutation().setPropertyValue((String) attrs.get("title").get());
        }
        if (attrs.get("nickName") != null) {
            name.getNickname().setPropertyValue((String) attrs.get("nickName").get());
        }
        contact.setName(name);

        /* Set personal details */
        PersonalDetail personal = new PersonalDetail();
        BusinessDetail business = new BusinessDetail();

        /* Set email */
        if (attrs.get("mail") != null) {
            Email email = new Email();
            email.setEmailType("Email1Address");
            email.setPropertyValue((String) attrs.get("mail").get());
            personal.addEmail(email);
        }
        if (attrs.get("mailAlternateAddress") != null) {
            Email email = new Email();
            email.setEmailType("Email2Address");
            email.setPropertyValue((String) attrs.get("mailAlternateAddress").get());
            personal.addEmail(email);
        }

        // (Other, Home, Business) x (Telephone,Mobile) x Number

        /* Set phone phones */
        ArrayList<Phone> allPhones = new ArrayList<Phone>();

        // telephone: home, work,
        if (attrs.get("homePhone") != null) {
            Phone homePhone = new Phone();
            homePhone.setPropertyValue((String) attrs.get("homePhone").get());
            homePhone.setPhoneType("HomeTelephoneNumber");
            allPhones.add(homePhone);
        }

        if (attrs.get("mobile") != null) {
            Phone mobile = new Phone();
            mobile.setPropertyValue((String) attrs.get("mobile").get());
            mobile.setPhoneType("MobileTelephoneNumber");
            allPhones.add(mobile);
        }

        String val = LdapUtils.getPrintableAttribute(attrs.get("telephoneNumber"));
        if (StringUtils.isNotEmpty(val)) {
            Phone phone = new Phone();
            phone.setPhoneType("BusinessTelephoneNumber");
            phone.setPropertyValue(val);
            business.addPhone(phone);
        }
        val = LdapUtils.getPrintableAttribute(attrs.get("facsimileTelephoneNumber"));
        if (StringUtils.isNotEmpty(val)) {
            Phone phone = new Phone();
            phone.setPhoneType("BusinessFaxNumber");
            phone.setPropertyValue(val);
            business.addPhone(phone);
        }

        personal.setPhones(allPhones);

        /*
        * Set address
        *//*
           * if(entry.getAttribute("postalCode")!= null) {
           * personal.getAddress().getPostalCode().setPropertyValue(
           * entry.getAttribute("postalCode").getStringValue()); }
           * 
           * if(entry.getAttribute("l")!= null) {
           * personal.getAddress().getCity().setPropertyValue(
           * entry.getAttribute("l").getStringValue()); }
           * 
           * if(entry.getAttribute("postalAddress")!= null) {
           * personal.getAddress().getStreet().setPropertyValue(
           * entry.getAttribute("postalAddress").getStringValue()); }
           */

        /* title */
        if (attrs.get("title") != null) {
            NamingEnumeration<?> values = attrs.get("title").getAll();
            ArrayList<Title> titles = new ArrayList<Title>();
            while (values.hasMoreElements()) {
                titles.add(new Title((String) values.nextElement()));

            }
            business.setTitles(titles);
        }

        if (attrs.get("street") != null) {

            NamingEnumeration<?> streets = attrs.get("street").getAll();
            while (streets.hasMoreElements()) {
                business.getAddress().getStreet().setPropertyValue((String) streets.nextElement());
            }

        }
        if (attrs.get("c") != null) {
            business.getAddress().getCountry().setPropertyValue((String) attrs.get("c").get());
        }

        if (attrs.get("l") != null) {
            business.getAddress().getCity().setPropertyValue((String) attrs.get("l").get());
        }

        if (attrs.get("postalCode") != null) {
            business.getAddress().getPostalCode().setPropertyValue((String) attrs.get("postalCode").get());
        }

        if (attrs.get("postalAddress") != null) {
            business.getAddress().getStreet().setPropertyValue((String) attrs.get("postalAddress").get());
        }

        if (attrs.get("o") != null) {
            business.getCompany().setPropertyValue((String) attrs.get("o").get());
        }
        if (attrs.get("calFbUrl") != null) {
            contact.setFreeBusy((String) attrs.get("calFbUrl").get());
        }
        contact.setPersonalDetail(personal);
        contact.setBusinessDetail(business);

        // contact.setUid(entryId);

        return contact;
    } catch (Exception e) {
        logger.warn("Error in getting entry values: ", e);
        return null;
    }
}

From source file:catalina.startup.ContextConfig.java

/**
 * Accumulate and return a Set of resource paths to be analyzed for
 * tag library descriptors.  Each element of the returned set will be
 * the context-relative path to either a tag library descriptor file,
 * or to a JAR file that may contain tag library descriptors in its
 * <code>META-INF</code> subdirectory.
 *
 * @exception IOException if an input/output error occurs while
 *  accumulating the list of resource paths
 *//*from  ww  w .  ja va2 s  .c  o m*/
private Set tldScanResourcePaths() throws IOException {

    if (debug >= 1) {
        log(" Accumulating TLD resource paths");
    }
    Set resourcePaths = new HashSet();

    // Accumulate resource paths explicitly listed in the web application
    // deployment descriptor
    if (debug >= 2) {
        log("  Scanning <taglib> elements in web.xml");
    }
    String taglibs[] = context.findTaglibs();
    for (int i = 0; i < taglibs.length; i++) {
        String resourcePath = context.findTaglib(taglibs[i]);
        // FIXME - Servlet 2.3 DTD implies that the location MUST be
        // a context-relative path starting with '/'?
        if (!resourcePath.startsWith("/")) {
            resourcePath = "/WEB-INF/web.xml/../" + resourcePath;
        }
        if (debug >= 3) {
            log("   Adding path '" + resourcePath + "' for URI '" + taglibs[i] + "'");
        }
        resourcePaths.add(resourcePath);
    }

    // Scan TLDs in the /WEB-INF subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning TLDs in /WEB-INF subdirectory");
    }
    DirContext resources = context.getResources();
    try {
        NamingEnumeration items = resources.list("/WEB-INF");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/" + item.getName();
            // FIXME - JSP 1.2 is not explicit about whether we should
            // scan subdirectories of /WEB-INF for TLDs also
            if (!resourcePath.endsWith(".tld")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }

    // Scan JARs in the /WEB-INF/lib subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning JARs in /WEB-INF/lib subdirectory");
    }
    try {
        NamingEnumeration items = resources.list("/WEB-INF/lib");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/lib/" + item.getName();
            if (!resourcePath.endsWith(".jar")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF/lib directory exists
    }

    // Return the completed set
    return (resourcePaths);

}

From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java

private Boolean processNamingEnumeration(NamingEnumeration ne, String password, Boolean authenticated,
        Map map) {//from   ww w  .  j av  a 2s .c o  m
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " processNamingEnumeration() ";
    log.debug(m + ">");
    try {
        boolean errorOnSomeComparison = false;
        while (ne.hasMoreElements()) {
            log.debug(m + "another element");
            SearchResult s = null;
            try {
                Object o = ne.nextElement();
                log.debug(m + "got a " + o.getClass().getName());
                s = (SearchResult) o;
            } catch (Throwable th) {
                log.error(m + "naming enum contains obj not SearchResult");
                continue;
            }
            Attributes attributes = s.getAttributes();
            getAttributes(attributes, map);
            if (individualUserComparison()) {
                Boolean temp = null;
                try {
                    temp = comparePassword(attributes, password, PASSWORD);
                    log.debug(m + "-this- comp yields " + temp);
                    if (authenticated != null && !authenticated) {
                        log.debug(m + "keeping prev failed authn");
                    } else {
                        log.debug(m + "replacing prvsuccess or null authn");
                        if (errorOnSomeComparison) {
                            log.debug(m + "errorOnSomeComparison==" + errorOnSomeComparison);
                        } else {
                            authenticated = temp;
                        }
                    }
                } catch (Throwable th) {
                    log.debug(m + "in iUC conditional, caught throwable th==" + th);
                    errorOnSomeComparison = true;
                    authenticated = null;
                }
            }
        }
        if (individualUserComparison()) {
            if (errorOnSomeComparison) {
                log.debug(m + "exception, so assuring authenticated==" + authenticated);
                authenticated = null;
                map.clear();
            } else if (authenticated == null) {
                authenticated = Boolean.FALSE;
                log.debug(m + "no passwd attr found, so authenticated==" + authenticated);
            }
        }
    } catch (Throwable th) { // play it safe:
        map.clear();
        if (authenticated != null && authenticated) {
            // drop an earlier authentication, before exception was thrown
            authenticated = null;
        } // but leave alone a earlier -failed- authentication
        if (LOG_STACK_TRACES) {
            log.error(m + "ldap filter failure", th);
        } else {
            log.error(m + "ldap filter failure" + th.getMessage());
        }
    } finally {
        log.debug(m + "< authenticated==" + authenticated + " map==" + map);
    }
    return authenticated;
}

From source file:org.jboss.web.tomcat.tc4.SingleSignOnContextConfig.java

/**
 * Accumulate and return a Set of resource paths to be analyzed for
 * tag library descriptors.  Each element of the returned set will be
 * the context-relative path to either a tag library descriptor file,
 * or to a JAR file that may contain tag library descriptors in its
 * <code>META-INF</code> subdirectory.
 *
 * @exception IOException if an input/output error occurs while
 *  accumulating the list of resource paths
 */// www  .j av  a 2 s . co  m
private Set tldScanResourcePaths() throws IOException {

    if (debug >= 1) {
        log(" Accumulating TLD resource paths");
    }
    Set resourcePaths = new HashSet();

    // Accumulate resource paths explicitly listed in the web application
    // deployment descriptor
    if (debug >= 2) {
        log("  Scanning <taglib> elements in web.xml");
    }
    String taglibs[] = context.findTaglibs();
    for (int i = 0; i < taglibs.length; i++) {
        String resourcePath = context.findTaglib(taglibs[i]);
        // FIXME - Servlet 2.3 DTD implies that the location MUST be
        // a context-relative path starting with '/'?
        if (!resourcePath.startsWith("/")) {
            resourcePath = "/WEB-INF/" + resourcePath;
        }
        if (debug >= 3) {
            log("   Adding path '" + resourcePath + "' for URI '" + taglibs[i] + "'");
        }
        resourcePaths.add(resourcePath);
    }

    // Scan TLDs in the /WEB-INF subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning TLDs in /WEB-INF subdirectory");
    }
    DirContext resources = context.getResources();
    try {
        NamingEnumeration items = resources.list("/WEB-INF");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/" + item.getName();
            // FIXME - JSP 1.2 is not explicit about whether we should
            // scan subdirectories of /WEB-INF for TLDs also
            if (!resourcePath.endsWith(".tld")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF directory exists
    }

    // Scan JARs in the /WEB-INF/lib subdirectory of the web application
    if (debug >= 2) {
        log("  Scanning JARs in /WEB-INF/lib subdirectory");
    }
    try {
        NamingEnumeration items = resources.list("/WEB-INF/lib");
        while (items.hasMoreElements()) {
            NameClassPair item = (NameClassPair) items.nextElement();
            String resourcePath = "/WEB-INF/lib/" + item.getName();
            if (!resourcePath.endsWith(".jar")) {
                continue;
            }
            if (debug >= 3) {
                log("   Adding path '" + resourcePath + "'");
            }
            resourcePaths.add(resourcePath);
        }
    } catch (NamingException e) {
        ; // Silent catch: it's valid that no /WEB-INF/lib directory exists
    }

    // Return the completed set
    return (resourcePaths);

}