Example usage for javax.naming NamingEnumeration hasMoreElements

List of usage examples for javax.naming NamingEnumeration hasMoreElements

Introduction

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

Prototype

boolean hasMoreElements();

Source Link

Document

Tests if this enumeration contains more elements.

Usage

From source file:info.bunji.jdbc.logger.JdbcLoggerFactory.java

/**
 ********************************************
 * get loggerName from jdbc url.//from  w ww .ja v  a 2 s. c  o  m
 *
 * @param url connection url
 * @return loggerName(jdbc url or DataSourceName)
 ********************************************
 */
private static String getLoggerName(String url) {
    if (!dsNameMap.containsKey(url)) {
        dsNameMap.put(url, url);

        // datasource????
        InitialContext ctx = null;
        try {
            // JNDI??????
            ctx = new InitialContext();
            NamingEnumeration<NameClassPair> ne = ctx.list("java:comp/env/jdbc");
            while (ne.hasMoreElements()) {
                NameClassPair nc = ne.nextElement();
                DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/" + nc.getName());
                // ?DataSource????getUrl()
                Method method = ds.getClass().getMethod("getUrl");
                String dsUrl = (String) method.invoke(ds);
                if (dsUrl.startsWith(DriverEx.DRIVER_URL_PREFIX)) {
                    dsUrl = dsUrl.replace(DriverEx.DRIVER_URL_PREFIX, "jdbc:");
                    if (dsUrl.equals(url)) {
                        dsNameMap.put(url, nc.getName());
                        break;
                    }
                }
            }
        } catch (Throwable t) {
            printThrowable(t);
        } finally {
            try {
                if (ctx != null)
                    ctx.close();
            } catch (NamingException e) {
            }
        }
    }
    return dsNameMap.get(url);
}

From source file:no.smint.anthropos.ldap.LDAP.java

public static String getDn(String uid) throws NamingException {
    Hashtable<String, Object> env = config();
    DirContext ctx = new InitialDirContext(env);
    SearchControls ctls = new SearchControls();
    String filter = ("uid=" + uid);
    NamingEnumeration answer = ctx.search(name, filter, ctls);

    SearchResult searchResult;//from www .j a  va2s.c o m

    if (answer.hasMoreElements()) {
        searchResult = (SearchResult) answer.next();
    } else {
        System.out.println("Found no user by that name");
        return null;
    }
    if (answer.hasMoreElements()) {
        System.err.println("Matched mutliple users for the uid" + uid);
        return null;
    }
    ctx.close();
    return searchResult.getNameInNamespace();
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user.//from w  ww . j  a  va  2s  . co  m
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:com.liferay.portal.action.LoginAction.java

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();/*from w  w  w  . j  a v a 2s .c  o  m*/

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:com.expedia.seiso.security.SeisoUserDetailsContextMapper.java

@SuppressWarnings("unused")
private void printAttributeIds(DirContextOperations ctx) {
    Attributes attrs = ctx.getAttributes();
    NamingEnumeration<? extends String> allAttrs = attrs.getIDs();
    while (allAttrs.hasMoreElements()) {
        String attrId = allAttrs.nextElement();
        log.trace("attrId={}", attrId);
    }// w  w  w  .ja  v  a2s .  c  o m
}

From source file:hsa.awp.common.naming.DirectoryTest.java

/**
 * Checks if the content of the Attributes and Properties is equal. In
 * properties it assumes the mapping from ldap names to our names.
 *
 * @param attributes Ldap Attribtues//from   w w w. jav  a  2s  .c  om
 * @param properties Properties returned from Directory
 * @return True if they are equal, otherwise false
 * @throws Exception If someone went wron.
 */
private boolean isEqual(Attributes attributes, Properties properties) throws Exception {

    if (attributes.size() != properties.size()) {
        return false;
    }

    NamingEnumeration<String> attribIds = attributes.getIDs();
    while (attribIds.hasMoreElements()) {
        String curAttribId = attribIds.nextElement();
        String currentAttribValue = (String) attributes.get(curAttribId).get();
        String currentPropertyId = (String) directory.getClass().getField(mapping.getProperty(curAttribId))
                .get("");
        String currentPropertyValue = properties.getProperty(currentPropertyId);
        if (!currentAttribValue.equals(currentPropertyValue)) {
            return false;
        }
    }

    return true;
}

From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

private List<String> getCustomerNames(Attributes attrs) throws NamingException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.getCustomerName(Attributes attrs");
    }/*from w w  w. j a  v  a2  s.c  o  m*/
    List<String> customerNames = new ArrayList<String>();
    Attribute attribute = attrs.get(ldapConfig.getCustomerNameAttribute());
    if (attribute != null) {
        NamingEnumeration<?> all = attribute.getAll();
        while (all.hasMoreElements()) {
            customerNames.add((String) all.nextElement());
        }
    }

    return customerNames;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

static List getListOfEmailInfo(NamingEnumeration p_searchResults) throws NamingException {

    List result = new ArrayList();

    while (p_searchResults.hasMoreElements()) {
        Object searchResultObj = p_searchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tmpSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tmpSearchResult.getAttributes();
            result.add(getUserEmailInfo(entry));
        }//from  w  ww  .  j av a2s.c o  m
    }

    p_searchResults.close();
    return result.size() == 0 ? null : result;
}

From source file:com.marklogic.samplestack.integration.web.LDAPIT.java

private SearchResult findAccountByAccountName(String accountName) throws NamingException {

    String searchFilter = "(&(objectclass=person)(cn=" + accountName + "))";

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

    NamingEnumeration<SearchResult> results = ctx.search(ldapSearchBase, searchFilter, searchControls);

    SearchResult searchResult = null;
    if (results.hasMoreElements()) {
        searchResult = (SearchResult) results.nextElement();

        // make sure there is not another item available, there should be
        // only 1 match
        if (results.hasMoreElements()) {
            System.err.println("Matched multiple users for the accountName: " + accountName);
            return null;
        }//www  . j a  va 2s. c om
    }

    return searchResult;
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Get the Uset ID array from a NamingEnumeration
 *//* w  w  w  . ja v  a2  s .c o  m*/
static Vector getUIDsVectorFromSearchResults(NamingEnumeration p_SearchResults) throws NamingException {

    Vector uids = new Vector();

    while (p_SearchResults.hasMoreElements()) {
        /* Next directory entry */
        Object searchResultObj = p_SearchResults.nextElement();
        if (searchResultObj instanceof SearchResult) {
            SearchResult tempSearchResult = (SearchResult) searchResultObj;
            Attributes entry = tempSearchResult.getAttributes();
            String uid = getSingleAttributeValue(entry.get(LDAP_ATTR_USERID));
            uids.addElement(uid);
        }
    }

    p_SearchResults.close();

    return uids;
}