Example usage for javax.naming Context PROVIDER_URL

List of usage examples for javax.naming Context PROVIDER_URL

Introduction

In this page you can find the example usage for javax.naming Context PROVIDER_URL.

Prototype

String PROVIDER_URL

To view the source code for javax.naming Context PROVIDER_URL.

Click Source Link

Document

Constant that holds the name of the environment property for specifying configuration information for the service provider to use.

Usage

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  a2  s.c om*/

    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:eu.uqasar.util.ldap.LdapManager.java

private LdapContext getConnection(LdapSettings settings, final String userName, final String password)
        throws CommunicationException, NamingException {
    Validate.notEmpty(settings.getAuthUserDN());

    // bind by using the specified username/password
    Properties props = new Properties();
    props.put(Context.SECURITY_PRINCIPAL, userName == null ? settings.getAuthUserDN() : userName);
    if (settings.getAuthUserPassword() != null || password != null) {
        props.put(Context.SECURITY_CREDENTIALS, password == null ? settings.getAuthUserPassword() : password);
    }/*from   w  w w .  j av  a2 s . c  om*/

    // ensures that objectSID attribute values
    // will be returned as a byte[] instead of a String
    props.put("java.naming.ldap.attributes.binary", "objectSID");

    // the following is helpful in debugging errors
    // props.put("com.sun.jndi.ldap.trace.ber", System.err);
    String ldapURL = String.format("ldap://%s:%s", settings.getHost(), settings.getPort());
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, ldapURL);
    props.put(Context.REFERRAL, "follow");
    try {
        return new InitialLdapContext(props, null);
    } catch (CommunicationException e) {
        logger.warn(String.format("Failed to connect to %s:%s", settings.getHost(), settings.getPort()), e);
        throw e;
    } catch (NamingException e) {
        logger.warn(String.format("Failed to authenticate %s:%s", settings.getHost(), settings.getPort()), e);
        throw e;
    }
}

From source file:org.apache.directory.server.jndi.ServerContextFactory.java

private void loadLdifs(DirectoryService service) throws NamingException {
    ServerStartupConfiguration cfg = (ServerStartupConfiguration) service.getConfiguration()
            .getStartupConfiguration();//from ww w  . j ava2 s  .c o  m

    // log and bail if property not set
    if (cfg.getLdifDirectory() == null) {
        log.info("LDIF load directory not specified.  No LDIF files will be loaded.");
        return;
    }

    // log and bail if LDIF directory does not exists
    if (!cfg.getLdifDirectory().exists()) {
        log.warn("LDIF load directory '" + getCanonical(cfg.getLdifDirectory())
                + "' does not exist.  No LDIF files will be loaded.");
        return;
    }

    // get an initial context to the rootDSE for creating the LDIF entries
    Hashtable env = (Hashtable) service.getConfiguration().getEnvironment().clone();
    env.put(Context.PROVIDER_URL, "");
    DirContext root = (DirContext) this.getInitialContext(env);

    // make sure the configuration area for loaded ldif files is present
    ensureLdifFileBase(root);

    // if ldif directory is a file try to load it
    if (!cfg.getLdifDirectory().isDirectory()) {
        if (log.isInfoEnabled()) {
            log.info("LDIF load directory '" + getCanonical(cfg.getLdifDirectory())
                    + "' is a file.  Will attempt to load as LDIF.");
        }

        Attributes fileEntry = getLdifFileEntry(root, cfg.getLdifDirectory());

        if (fileEntry != null) {
            String time = (String) fileEntry.get("createTimestamp").get();

            if (log.isInfoEnabled()) {
                log.info("Load of LDIF file '" + getCanonical(cfg.getLdifDirectory())
                        + "' skipped.  It has already been loaded on " + time + ".");
            }

            return;
        }

        LdifFileLoader loader = new LdifFileLoader(root, cfg.getLdifDirectory(), cfg.getLdifFilters());
        loader.execute();

        addFileEntry(root, cfg.getLdifDirectory());
        return;
    }

    // get all the ldif files within the directory (should be sorted alphabetically)
    File[] ldifFiles = cfg.getLdifDirectory().listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            boolean isLdif = pathname.getName().toLowerCase().endsWith(".ldif");
            return pathname.isFile() && pathname.canRead() && isLdif;
        }
    });

    // log and bail if we could not find any LDIF files
    if (ldifFiles == null || ldifFiles.length == 0) {
        log.warn("LDIF load directory '" + getCanonical(cfg.getLdifDirectory())
                + "' does not contain any LDIF files.  No LDIF files will be loaded.");
        return;
    }

    // load all the ldif files and load each one that is loaded
    for (int ii = 0; ii < ldifFiles.length; ii++) {
        Attributes fileEntry = getLdifFileEntry(root, ldifFiles[ii]);
        if (fileEntry != null) {
            String time = (String) fileEntry.get("createTimestamp").get();
            log.info("Load of LDIF file '" + getCanonical(ldifFiles[ii])
                    + "' skipped.  It has already been loaded on " + time + ".");
            continue;
        }
        LdifFileLoader loader = new LdifFileLoader(root, ldifFiles[ii], cfg.getLdifFilters());
        int count = loader.execute();
        log.info("Loaded " + count + " entries from LDIF file '" + getCanonical(ldifFiles[ii]) + "'");
        if (fileEntry == null) {
            addFileEntry(root, ldifFiles[ii]);
        }
    }
}

From source file:com.ccc.ccm.client.activemq.StoreablePooledConnectionFactory.java

public void populateProperties(Properties props) {
    props.setProperty("dispatchAsync", Boolean.toString(isDispatchAsync()));

    if (getBrokerURL() != null) {
        props.setProperty(Context.PROVIDER_URL, getBrokerURL());
        props.setProperty("brokerURL", getBrokerURL());
    }/*from   w  ww  .  j av a2s.  c  om*/

    if (getClientID() != null) {
        props.setProperty("clientID", getClientID());
    }

    IntrospectionSupport.getProperties(getPrefetchPolicy(), props, "prefetchPolicy.");
    IntrospectionSupport.getProperties(getRedeliveryPolicy(), props, "redeliveryPolicy.");

    props.setProperty("copyMessageOnSend", Boolean.toString(isCopyMessageOnSend()));
    props.setProperty("disableTimeStampsByDefault", Boolean.toString(isDisableTimeStampsByDefault()));
    props.setProperty("objectMessageSerializationDefered",
            Boolean.toString(isObjectMessageSerializationDefered()));
    props.setProperty("optimizedMessageDispatch", Boolean.toString(isOptimizedMessageDispatch()));

    if (getPassword() != null) {
        props.setProperty("password", getPassword());
    }

    props.setProperty("useSyncSend", Boolean.toString(isUseSyncSend()));
    props.setProperty("useAsyncSend", Boolean.toString(isUseAsyncSend()));
    props.setProperty("useCompression", Boolean.toString(isUseCompression()));
    props.setProperty("useRetroactiveConsumer", Boolean.toString(isUseRetroactiveConsumer()));
    props.setProperty("watchTopicAdvisories", Boolean.toString(isWatchTopicAdvisories()));

    if (getUserName() != null) {
        props.setProperty("userName", getUserName());
    }

    props.setProperty("closeTimeout", Integer.toString(getCloseTimeout()));
    props.setProperty("alwaysSessionAsync", Boolean.toString(isAlwaysSessionAsync()));
    props.setProperty("optimizeAcknowledge", Boolean.toString(isOptimizeAcknowledge()));
    props.setProperty("statsEnabled", Boolean.toString(isStatsEnabled()));

}

From source file:com.openkm.principal.LdapPrincipalAdapter.java

/**
 * Create static LDAP configuration environment.
 *///from ww w .  java  2  s .c  o  m
private static Hashtable<String, String> getEnvironment() {
    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.PROVIDER_URL, Config.PRINCIPAL_LDAP_SERVER);

    // Enable connection pooling
    // @see http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/pool.html
    env.put("com.sun.jndi.ldap.connect.pool", "true");

    /**
     * Referral values: ignore, follow or throw.
     * 
     * @see http://docs.oracle.com/javase/jndi/tutorial/ldap/referral/jndi.html
     * @see http://java.sun.com/products/jndi/jndi-ldap-gl.html
     */
    if (!"".equals(Config.PRINCIPAL_LDAP_REFERRAL)) {
        env.put(Context.REFERRAL, Config.PRINCIPAL_LDAP_REFERRAL);
    }

    // Optional is some cases (Max OS/X)
    if (!Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL.equals("")) {
        env.put(Context.SECURITY_PRINCIPAL, Config.PRINCIPAL_LDAP_SECURITY_PRINCIPAL);
    }

    if (!Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS.equals("")) {
        env.put(Context.SECURITY_CREDENTIALS, Config.PRINCIPAL_LDAP_SECURITY_CREDENTIALS);
    }

    return env;
}

From source file:org.settings4j.connector.JNDIConnectorTest.java

public static void setTomcatJNDIContextProperties() {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.PROVIDER_URL, "localhost:1099");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Test case for <a href="http://issues.apache.org/jira/browse/DIREVE-284" where users in
 * mixed case partitions were not able to authenticate properly.  This test case creates
 * a new partition under dc=aPache,dc=org, it then creates the example user in the JIRA
 * issue and attempts to authenticate as that user.
 *
 * @throws Exception if the user cannot authenticate or test fails
 *///  ww w . ja v a2s.co  m
@Test
public void testUserAuthOnMixedCaseSuffix() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()) + "/dc=aPache,dc=org");
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    InitialDirContext ctx = new InitialDirContext(env);
    Attributes attrs = ctx.getAttributes("");
    assertTrue(attrs.get("dc").get().equals("aPache"));

    Attributes user = new BasicAttributes("cn", "Kate Bush", true);
    Attribute oc = new BasicAttribute("objectClass");
    oc.add("top");
    oc.add("person");
    oc.add("organizationalPerson");
    oc.add("inetOrgPerson");
    user.put(oc);
    user.put("sn", "Bush");
    user.put("userPassword", "Aerial");
    ctx.createSubcontext("cn=Kate Bush", user);

    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_CREDENTIALS, "Aerial");
    env.put(Context.SECURITY_PRINCIPAL, "cn=Kate Bush,dc=aPache,dc=org");

    InitialDirContext userCtx = new InitialDirContext(env);
    assertNotNull(userCtx);

    ctx.destroySubcontext("cn=Kate Bush");
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn//from   ww w  .jav a2s . c  om
 * @param password
 * @throws LDAPException
 * @see org.mule.module.ldap.api.LDAPConnection#bind(java.lang.String,
 *      java.lang.String)
 */
@Override
public void bind(String dn, String password) throws LDAPException {
    try {
        if (!isClosed()) {
            String currentUrl = (String) getConn().getEnvironment().get(Context.PROVIDER_URL);
            String currentAuth = (String) getConn().getEnvironment().get(Context.SECURITY_AUTHENTICATION);
            String currentDn = getBindedUserDn();

            logger.info("Already binded to " + currentUrl + " with " + currentAuth + " authentication as "
                    + (currentDn != null ? currentDn : "anonymous") + ". Closing connection first.");

            close();

            logger.info("Re-binding to " + getProviderUrl() + " with " + getAuthentication()
                    + " authentication as " + (dn != null ? dn : "anonymous"));
        }

        logConfiguration(dn, password);
        setConn(new InitialLdapContext(buildEnvironment(dn, password), null));
        logger.info("Binded to " + getProviderUrl() + " with " + getAuthentication() + " authentication as "
                + (dn != null ? dn : "anonymous"));

    } catch (NamingException nex) {
        throw handleNamingException(nex, "Bind failed.");
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java

protected DirContext createContext() throws DirectoryException {
    try {/*from ww w  .  ja v a 2 s  . co m*/
        /*
         * Dynamic server list requires re-computation on each access
         */
        String serverName = getDescriptor().getServerName();
        if (StringUtils.isEmpty(serverName)) {
            throw new DirectoryException("server configuration is missing for directory " + getName());
        }
        LDAPServerDescriptor serverConfig = getServer();
        if (serverConfig.isDynamicServerList()) {
            String ldapUrls = serverConfig.getLdapUrls();
            contextProperties.put(Context.PROVIDER_URL, ldapUrls);
        }
        return new InitialDirContext(contextProperties);
    } catch (NamingException e) {
        throw new DirectoryException("Cannot connect to LDAP directory '" + getName() + "': " + e.getMessage(),
                e);
    }
}

From source file:hudson.security.LDAPSecurityRealm.java

/**
 * Infer the root DN.//from   w w  w .  j a  v  a  2s .c om
 *
 * @return null if not found.
 */
private String inferRootDN(String server) {
    try {
        Hashtable<String, String> props = new Hashtable<String, String>();
        if (managerDN != null) {
            props.put(Context.SECURITY_PRINCIPAL, managerDN);
            props.put(Context.SECURITY_CREDENTIALS, getManagerPassword());
        }
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, getServerUrl() + '/');

        DirContext ctx = new InitialDirContext(props);
        Attributes atts = ctx.getAttributes("");
        Attribute a = atts.get("defaultNamingContext");
        if (a != null) // this entry is available on Active Directory. See http://msdn2.microsoft.com/en-us/library/ms684291(VS.85).aspx
            return a.toString();

        a = atts.get("namingcontexts");
        if (a == null) {
            LOGGER.warning("namingcontexts attribute not found in root DSE of " + server);
            return null;
        }
        return a.get().toString();
    } catch (NamingException e) {
        LOGGER.log(Level.WARNING, "Failed to connect to LDAP to infer Root DN for " + server, e);
        return null;
    }
}