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:info.bunji.jdbc.logger.JdbcLoggerFactory.java

/**
 ********************************************
 * get loggerName from jdbc url./*w w w . jav  a 2  s .co 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:org.apache.catalina.util.ExtensionValidator.java

/**
 * Runtime validation of a Web Applicaiton.
 *
 * This method uses JNDI to look up the resources located under a 
 * <code>DirContext</code>. It locates Web Application MANIFEST.MF 
 * file in the /META-INF/ directory of the application and all 
 * MANIFEST.MF files in each JAR file located in the WEB-INF/lib 
 * directory and creates an <code>ArrayList</code> of 
 * <code>ManifestResorce<code> objects. These objects are then passed 
 * to the validateManifestResources method for validation.
 *
 * @param dirContext The JNDI root of the Web Application
 * @param context The context from which the Logger and path to the
 *                application//  w w  w .  j  av a2  s. co  m
 *
 * @return true if all required extensions satisfied
 */
public static synchronized boolean validateApplication(DirContext dirContext, StandardContext context)
        throws IOException {

    String appName = context.getPath();
    ArrayList appManifestResources = new ArrayList();
    ManifestResource appManifestResource = null;
    // If the application context is null it does not exist and 
    // therefore is not valid
    if (dirContext == null)
        return false;
    // Find the Manifest for the Web Applicaiton
    InputStream inputStream = null;
    try {
        NamingEnumeration wne = dirContext.listBindings("/META-INF/");
        Binding binding = (Binding) wne.nextElement();
        if (binding.getName().toUpperCase().equals("MANIFEST.MF")) {
            Resource resource = (Resource) dirContext.lookup("/META-INF/" + binding.getName());
            inputStream = resource.streamContent();
            Manifest manifest = new Manifest(inputStream);
            inputStream.close();
            inputStream = null;
            ManifestResource mre = new ManifestResource(
                    sm.getString("extensionValidator.web-application-manifest"), manifest,
                    ManifestResource.WAR);
            appManifestResources.add(mre);
        }
    } catch (NamingException nex) {
        // Application does not contain a MANIFEST.MF file
    } catch (NoSuchElementException nse) {
        // Application does not contain a MANIFEST.MF file
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Throwable t) {
                // Ignore
            }
        }
    }

    // Locate the Manifests for all bundled JARs
    NamingEnumeration ne = null;
    try {
        if (dirContext != null) {
            ne = dirContext.listBindings("WEB-INF/lib/");
        }
        while ((ne != null) && ne.hasMoreElements()) {
            Binding binding = (Binding) ne.nextElement();
            if (!binding.getName().toLowerCase().endsWith(".jar")) {
                continue;
            }
            Resource resource = (Resource) dirContext.lookup("/WEB-INF/lib/" + binding.getName());
            Manifest jmanifest = getManifest(resource.streamContent());
            if (jmanifest != null) {
                ManifestResource mre = new ManifestResource(binding.getName(), jmanifest,
                        ManifestResource.APPLICATION);
                appManifestResources.add(mre);
            }
        }
    } catch (NamingException nex) {
        // Jump out of the check for this application because it 
        // has no resources
    }

    return validateManifestResources(appName, appManifestResources);
}

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  2 s .  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);
    }//from  w w w.  j a  va2 s.c o  m
}

From source file:org.viafirma.util.ConfigUtil.java

/**
 * Recupera el conjunto de propiedades que utiliza la aplicacin.
 * @param context//from   ww w. j a va  2 s.  c  o m
 * @return
 */
public Properties readConfigPropertes() {
    Properties properties = new Properties();
    Context initCtx;
    try {
        initCtx = new InitialContext();
        Context contextInit = (Context) initCtx.lookup("java:comp/env");
        // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin 
        NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list("");
        while (propiedadesJDNI.hasMoreElements()) {
            NameClassPair propiedad = propiedadesJDNI.nextElement();
            Object temp = contextInit.lookup(propiedad.getName());
            if (temp instanceof String) {
                String valor = (String) temp;
                System.out.println("\t\t\t" + propiedad.getName() + "=" + valor);
                properties.put(propiedad.getName(), valor);
            }
        }
    } catch (Exception e) {
        log.fatal("No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible.",
                e);
        throw new ExceptionInInitializerError(
                "No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible."
                        + e.getMessage());
    }
    return properties;
}

From source file:org.viafirma.util.ConfigUtil.java

/**
 * Recupera el conjunto de propiedades que utiliza la aplicacin.
 * @param context/*from w ww  . j  a va2s.  co  m*/
 * @return
 */
public String readConfigProperty(String property) {
    Context initCtx;
    try {
        initCtx = new InitialContext();
        Context contextInit = (Context) initCtx.lookup("java:comp/env");
        // recuperamos ahora todos los parametros JNDI que estan en el raiz de la aplicacin 
        NamingEnumeration<NameClassPair> propiedadesJDNI = contextInit.list("");
        while (propiedadesJDNI.hasMoreElements()) {
            NameClassPair propiedad = propiedadesJDNI.nextElement();
            if (property.equalsIgnoreCase(propiedad.getName())) {
                // propiedad encontrada
                Object temp = contextInit.lookup(propiedad.getName());
                if (temp instanceof String) {
                    String valor = (String) temp;
                    return valor;
                }
            }
        }
    } catch (Exception e) {
        throw new ExceptionInInitializerError(
                "No se pueden recuperar los parametros de configuracin. JNDI parece no estar disponible."
                        + e.getMessage());
    }
    log.fatal("No se pueden recuperar el parametro de configuracin " + property
            + " de configuracin. JNDI parece no estar disponible.");
    return null;
}

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//ww  w  . ja v  a2  s. com
 * @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:org.wso2.carbon.connector.ldap.SearchEntry.java

private SearchResult makeSureOnlyOneMatch(NamingEnumeration<SearchResult> results) {
    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()) {
            // Here the code has matched multiple objects for the searched target
            return null;
        }//w w w  . j ava 2  s.  co m
    }
    return searchResult;
}

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  av  a  2s.  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.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;
        }/*from w w  w  .  jav a 2 s . co  m*/
    }

    return searchResult;
}