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:org.apache.openaz.xacml.std.pip.engines.ldap.LDAPEngine.java

@Override
public void configure(String id, Properties properties) throws PIPException {
    /*//from  www.  j  ava 2 s. co m
     * Handle the standard properties
     */
    super.configure(id, properties);
    String propertyPrefix = id + ".";

    /*
     * Configure the LDAP environment: I think the only required property is the provider_url
     */
    if (!this.configureStringProperty(propertyPrefix, Context.PROVIDER_URL, properties, null)) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + Context.PROVIDER_URL);
    }
    this.configureStringProperty(propertyPrefix, Context.AUTHORITATIVE, properties, null);
    this.configureIntegerProperty(propertyPrefix, Context.BATCHSIZE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.DNS_URL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.INITIAL_CONTEXT_FACTORY, properties,
            DEFAULT_CONTEXT_FACTORY);
    this.configureStringProperty(propertyPrefix, Context.LANGUAGE, properties, null);
    this.configureStringProperty(propertyPrefix, Context.OBJECT_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.REFERRAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_AUTHENTICATION, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_CREDENTIALS, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PRINCIPAL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.SECURITY_PROTOCOL, properties, null);
    this.configureStringProperty(propertyPrefix, Context.STATE_FACTORIES, properties, null);
    this.configureStringProperty(propertyPrefix, Context.URL_PKG_PREFIXES, properties, null);

    String ldapScopeValue = properties.getProperty(propertyPrefix + PROP_LDAP_SCOPE, DEFAULT_SCOPE);
    if (LDAP_SCOPE_SUBTREE.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    } else if (LDAP_SCOPE_OBJECT.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.OBJECT_SCOPE;
    } else if (LDAP_SCOPE_ONELEVEL.equals(ldapScopeValue)) {
        this.ldapScope = SearchControls.ONELEVEL_SCOPE;
    } else {
        this.logger.warn("Invalid LDAP Scope value '" + ldapScopeValue + "'; using " + DEFAULT_SCOPE);
        this.ldapScope = SearchControls.SUBTREE_SCOPE;
    }

    /*
     * Get list of resolvers defined for this LDAP Engine
     */
    String resolversList = properties.getProperty(propertyPrefix + PROP_RESOLVERS);
    if (resolversList == null || resolversList.isEmpty()) {
        throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                + propertyPrefix + PROP_RESOLVERS);
    }

    /*
     * Iterate the resolvers
     */
    for (String resolver : Splitter.on(',').trimResults().omitEmptyStrings().split(resolversList)) {
        /*
         * Get the LDAPResolver for this LDAPEngine
         */
        String resolverClassName = properties
                .getProperty(propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        if (resolverClassName == null) {
            throw new PIPException("Invalid configuration for " + this.getClass().getName() + ": No "
                    + propertyPrefix + PROP_RESOLVER + "." + resolver + ".classname");
        }

        LDAPResolver ldapResolverNew = null;
        try {
            Class<?> classResolver = Class.forName(resolverClassName);
            if (!LDAPResolver.class.isAssignableFrom(classResolver)) {
                this.logger.error("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
                throw new PIPException("LDAPResolver class " + resolverClassName + " does not implement "
                        + LDAPResolver.class.getCanonicalName());
            }
            ldapResolverNew = LDAPResolver.class.cast(classResolver.newInstance());
        } catch (Exception ex) {
            this.logger.error("Exception instantiating LDAPResolver for class '" + resolverClassName + "': "
                    + ex.getMessage(), ex);
            throw new PIPException("Exception instantiating LDAPResolver for class '" + resolverClassName + "'",
                    ex);
        }
        assert ldapResolverNew != null;
        ldapResolverNew.configure(propertyPrefix + PROP_RESOLVER + "." + resolver, properties,
                this.getIssuer());

        this.ldapResolvers.add(ldapResolverNew);
    }

}

From source file:com.duroty.application.files.actions.DownloadFileAction.java

/**
 * DOCUMENT ME!/*  w w  w  .j a  va2s . c  o m*/
 *
 * @param request DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
protected Hashtable getContextProperties(HttpServletRequest request) {
    Hashtable props = (Hashtable) SessionManager.getObject(Constants.CONTEXT_PROPERTIES, request);

    if (props == null) {
        props = new Hashtable();

        props.put(Context.INITIAL_CONTEXT_FACTORY,
                Configuration.properties.getProperty(Configuration.JNDI_INITIAL_CONTEXT_FACTORY));
        props.put(Context.URL_PKG_PREFIXES,
                Configuration.properties.getProperty(Configuration.JNDI_URL_PKG_PREFIXES));
        props.put(Context.PROVIDER_URL, Configuration.properties.getProperty(Configuration.JNDI_PROVIDER_URL));

        Principal principal = request.getUserPrincipal();
        props.put(Context.SECURITY_PRINCIPAL, principal.getName());
        props.put(Context.SECURITY_CREDENTIALS, SessionManager.getObject(Constants.JAAS_PASSWORD, request));

        props.put(Context.SECURITY_PROTOCOL,
                Configuration.properties.getProperty(Configuration.SECURITY_PROTOCOL));

        SessionManager.setObject(Constants.CONTEXT_PROPERTIES, props, request);
    }

    return props;
}

From source file:com.hs.mail.security.login.JndiLoginModule.java

@SuppressWarnings("unchecked")
protected DirContext open() throws NamingException {
    if (context == null) {
        try {/*w ww .  j  a v  a  2 s  . co  m*/
            // Set up the environment for creating the initial context
            Hashtable env = new Hashtable();
            env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
            if (StringUtils.isNotEmpty(username)) {
                env.put(Context.SECURITY_PRINCIPAL, username);
            }
            if (StringUtils.isNotEmpty(password)) {
                env.put(Context.SECURITY_CREDENTIALS, password);
            }
            env.put(Context.PROVIDER_URL, url);
            env.put(Context.SECURITY_AUTHENTICATION, authentication);
            context = new InitialDirContext(env);
        } catch (NamingException e) {
            throw e;
        }
    }
    return context;
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.LdapCommentAuthenticator.java

public boolean authenticate(HttpServletRequest request) {
    boolean validUser = false;
    LdapContext context = null;// ww  w . j  a v a 2  s .co  m

    String ldapDc = WebloggerConfig.getProperty("comment.authenticator.ldap.dc");
    String ldapOu = WebloggerConfig.getProperty("comment.authenticator.ldap.ou");
    String ldapPort = WebloggerConfig.getProperty("comment.authenticator.ldap.port");
    String ldapHost = WebloggerConfig.getProperty("comment.authenticator.ldap.host");
    String ldapSecurityLevel = WebloggerConfig.getProperty("comment.authenticator.ldap.securityLevel");

    boolean rollerPropertiesValid = validateRollerProperties(ldapDc, ldapOu, ldapPort, ldapHost);

    String ldapUser = request.getParameter("ldapUser");
    String ldapPass = request.getParameter("ldapPass");

    boolean userDataValid = validateUsernamePass(ldapUser, ldapPass);

    if (rollerPropertiesValid && userDataValid) {
        try {
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            if (ldapSecurityLevel != null && (ldapSecurityLevel.equalsIgnoreCase("none")
                    || ldapSecurityLevel.equalsIgnoreCase("simple")
                    || ldapSecurityLevel.equalsIgnoreCase("strong"))) {
                env.put(Context.SECURITY_AUTHENTICATION, ldapSecurityLevel);
            }
            env.put(Context.SECURITY_PRINCIPAL, getQualifedDc(ldapDc, ldapOu, ldapUser));
            env.put(Context.SECURITY_CREDENTIALS, ldapPass);
            env.put(Context.PROVIDER_URL, "ldap://" + ldapHost + ":" + ldapPort);
            context = new InitialLdapContext(env, null);
            validUser = true;
            LOG.info("LDAP Authentication Successful. user: " + ldapUser);
        } catch (Exception e) {
            // unexpected
            LOG.error(e);
        } finally {
            if (context != null) {
                try {
                    context.close();
                } catch (NamingException e) {
                    LOG.error(e);
                }
            }
        }
    }
    return validUser;
}

From source file:org.wso2.carbon.humantask.core.db.Database.java

@SuppressWarnings("unchecked")
private <T> T lookupInJndi(String objName) throws Exception {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    try {//from  ww w  .jav a 2 s.  c  om
        InitialContext ctx = null;
        try {
            if (serverConfiguration.getDataSourceJNDIRepoInitialContextFactory() != null
                    && serverConfiguration.getDataSourceJNDIRepoProviderURL() != null) {
                Properties jndiProps = new Properties();

                jndiProps.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                        serverConfiguration.getDataSourceJNDIRepoInitialContextFactory());
                jndiProps.setProperty(Context.PROVIDER_URL,
                        serverConfiguration.getDataSourceJNDIRepoProviderURL());

                ctx = new InitialContext(jndiProps);
            } else {
                ctx = new InitialContext();
            }
            return (T) ctx.lookup(objName);
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (Exception ex1) {
                    log.error("Error closing JNDI connection.", ex1);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}

From source file:org.pegadi.server.user.LDAPUserServerImpl.java

/**
 * Can probably be done more elegant too.
 *
 * @param userDN   real dn to the user.//from w  w w.  jav  a2s  .  co  m
 * @param password the user's password
 * @return
 */
public boolean checkAuthentication(String userDN, String password) {
    if (password.trim().equals(""))
        return false;
    DirContext ctx2 = null;
    try {
        // See if the user authenticates.
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url + "/" + ldapBaseDN);
        env.put(Context.SECURITY_AUTHENTICATION, auth);
        env.put(Context.SECURITY_PRINCIPAL, userDN);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put("com.sun.jndi.ldap.connect.timeout", "10000");
        // Specify timeout to be 10 seconds, only on non SSL since SSL connections
        // break with a timeout.
        ctx2 = new InitialDirContext(env);
        log.info("Successfully logged in... " + userDN);
    } catch (Exception e) {
        log.error("Exception during login", e);
        return false;
    }

    finally {
        try {
            ctx2.close();
        } catch (NamingException ignore) {
        }
    }

    return true;
}

From source file:org.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Lookup the DataSource on JNDI using the specified properties
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource looked up using specified properties
 *//*  w ww.j  a  v  a 2 s .  c  o  m*/
private DataSource lookupDataSource(OMElement pool, AbstractDBMediator mediator) {

    Hashtable props = new Hashtable();
    // load the minimum required properties
    props.put(Context.INITIAL_CONTEXT_FACTORY, (getValue(pool, ICCLASS_Q)));
    props.put(Context.SECURITY_PRINCIPAL, getValue(pool, USER_Q));
    props.put(Context.SECURITY_CREDENTIALS, getValue(pool, PASS_Q));
    props.put(Context.PROVIDER_URL, getValue(pool, URL_Q));
    String dsName = getValue(pool, DSNAME_Q);

    //save loaded properties for later
    mediator.addDataSourceProperty(ICCLASS_Q, getValue(pool, ICCLASS_Q));
    mediator.addDataSourceProperty(DSNAME_Q, getValue(pool, DSNAME_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    try {
        Context ctx = new InitialContext(props);
        if (ctx != null) {
            Object ds = ctx.lookup(dsName);
            if (ds != null && ds instanceof DataSource) {
                return (DataSource) ds;
            } else {
                handleException("DataSource : " + dsName + " not found when looking up"
                        + " using JNDI properties : " + props);
            }
        } else {
            handleException("Error getting InitialContext using JNDI properties : " + props);
        }
    } catch (NamingException e) {
        handleException("Error looking up DataSource : " + dsName + " using JNDI properties : " + props, e);
    }
    return null;
}

From source file:nl.nn.adapterframework.ldap.LdapFindMemberPipe.java

private boolean findMember(String host, int port, String dnSearchIn, boolean useSsl, String dnFind,
        boolean recursiveSearch) throws NamingException {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    String provUrl = retrieveUrl(host, port, dnSearchIn, useSsl);
    env.put(Context.PROVIDER_URL, provUrl);
    if (StringUtils.isNotEmpty(cf.getUsername())) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, cf.getUsername());
        env.put(Context.SECURITY_CREDENTIALS, cf.getPassword());
    } else {/*w  w w  .  j a va 2 s.co  m*/
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    DirContext ctx = null;
    try {
        try {
            ctx = new InitialDirContext(env);
        } catch (CommunicationException e) {
            log.info("Cannot create constructor for DirContext (" + e.getMessage()
                    + "], will try again with dummy SocketFactory");
            env.put("java.naming.ldap.factory.socket", DummySSLSocketFactory.class.getName());
            ctx = new InitialLdapContext(env, null);
        }
        Attribute attrs = ctx.getAttributes("").get("member");
        if (attrs != null) {
            boolean found = false;
            for (int i = 0; i < attrs.size() && !found; i++) {
                String dnFound = (String) attrs.get(i);
                if (dnFound.equalsIgnoreCase(dnFind)) {
                    found = true;
                } else {
                    if (recursiveSearch) {
                        found = findMember(host, port, dnFound, useSsl, dnFind, recursiveSearch);
                    }
                }
            }
            return found;
        }
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn("Exception closing DirContext", e);
            }
        }
    }
    return false;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Creates a DirContext with the applications configuration settings.
 * @return a DirContext//from  w w  w  .jav a2 s.  c  o m
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public DirContext createDirContext() throws NamingException {
    final Hashtable<String, String> env = new Hashtable<>();
    env.put(Context.SECURITY_PRINCIPAL, BIND_USERNAME);
    env.put(Context.SECURITY_CREDENTIALS, BIND_PASSWORD);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    if (IS_LDAP_SSLTLS) {
        env.put("java.naming.ldap.factory.socket", "alpine.crypto.RelaxedSSLSocketFactory");
    }
    return new InitialDirContext(env);
}

From source file:test.integ.be.fedict.performance.TestPKIPerformanceTest.java

@Test
public void testPki() throws Exception {

    LOG.debug("performance test using test PKI");

    // get test PKI information
    if (interactive) {
        testPkiPath = JOptionPane.showInputDialog("Please give the test PKI base URL");
    } else {/*from w w  w  . j  av a 2  s  . c o m*/
        testPkiPath = PKI_PATH;
    }
    testPKI = TestPKI.load(testPkiPath);

    // initialize test framework
    List<PerformanceData> performance = new LinkedList<PerformanceData>();
    List<MemoryData> memory = new LinkedList<MemoryData>();
    PerformanceData currentPerformance = new PerformanceData();
    performance.add(currentPerformance);
    long nextIntervalT = System.currentTimeMillis() + INTERVAL_SIZE;

    // initialize JBoss monitoring for memory usage
    String jnpLocation = "jnp://" + HOST + ":1099";
    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    environment.put(Context.PROVIDER_URL, jnpLocation);
    rmi = (MBeanServerConnection) new InitialContext(environment).lookup("jmx/invoker/RMIAdaptor");

    if (interactive) {
        new PerformanceWorkingFrame(this);
    }

    // used to generate our certificates
    DateTime notBefore = new DateTime().minusYears(10);
    DateTime notAfter = new DateTime().plusYears(10);
    KeyPair testKeyPair = TestUtils.generateKeyPair();
    List<CAConfiguration> leaves = testPKI.getLeaves();
    Random random = new Random();

    // operate
    this.startTime = new DateTime();
    while (this.run) {

        try {
            List<X509Certificate> certificateChain = getCertificateChain(testKeyPair, leaves, random, notBefore,
                    notAfter);

            // initialize XKMS2 client
            XKMS2Client client = new XKMS2Client(XKMS_LOCATION);
            client.validate("performance", certificateChain);
            currentPerformance.inc();
            this.count++;

        } catch (ValidationFailedException e) {

            if (e.getReasons().get(0).equals(XKMSConstants.KEY_BINDING_REASON_REVOCATION_STATUS_URI)) {
                LOG.debug("revoked");
                currentPerformance.incRevoked();
                this.revokedCount++;
            } else {
                LOG.error("Validation failed: " + e.getReasons().get(0));
                currentPerformance.incFailures();
            }

        } catch (Exception e) {
            LOG.error("error: " + e.getMessage(), e);
            currentPerformance.incFailures();
        } finally {

            if (System.currentTimeMillis() > nextIntervalT) {

                memory.add(new MemoryData(getFreeMemory(), getMaxMemory(), getTotalMemory()));

                currentPerformance = new PerformanceData();
                nextIntervalT = System.currentTimeMillis() + INTERVAL_SIZE;
                performance.add(currentPerformance);
                this.intervalCount++;

                if (!interactive) {
                    DateTime now = new DateTime();
                    if (now.isAfter(startTime.plusMinutes(minutes))) {
                        this.run = false;
                    }
                }

            }
        }
    }

    // add last performance
    performance.add(currentPerformance);

    if (interactive) {
        // show result
        PerformanceResultDialog dialog = new PerformanceResultDialog(
                new PerformanceResultsData(INTERVAL_SIZE, performance, this.expectedRevokedCount, memory));
        while (dialog.isVisible()) {
            Thread.sleep(1000);
        }
    } else {
        // write results to file for later
        PerformanceResultDialog.writeResults(
                new PerformanceResultsData(INTERVAL_SIZE, performance, expectedRevokedCount, memory));
    }
}