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.juddi.v3.auth.LdapSimpleAuthenticator.java

public String authenticate(String authorizedName, String cred)
        throws AuthenticationException, FatalErrorException {
    if (authorizedName == null || "".equals(authorizedName)) {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }/*from w  ww . j a va2 s .c  om*/

    int MaxBindingsPerService = -1;
    int MaxServicesPerBusiness = -1;
    int MaxTmodels = -1;
    int MaxBusinesses = -1;
    try {
        MaxBindingsPerService = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BINDINGS_PER_SERVICE,
                -1);
        MaxServicesPerBusiness = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_SERVICES_PER_BUSINESS,
                -1);
        MaxTmodels = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_TMODELS_PER_PUBLISHER, -1);
        MaxBusinesses = AppConfig.getConfiguration().getInt(Property.JUDDI_MAX_BUSINESSES_PER_PUBLISHER, -1);
    } catch (Exception ex) {
        MaxBindingsPerService = -1;
        MaxServicesPerBusiness = -1;
        MaxTmodels = -1;
        MaxBusinesses = -1;
        logger.error("config exception! " + authorizedName, ex);
    }
    boolean isLdapUser = false;
    try {
        env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, AppConfig.getConfiguration()
                .getString(Property.JUDDI_AUTHENTICATOR_INITIAL_CONTEXT, "com.sun.jndi.ldap.LdapCtxFactory"));
        env.put(Context.SECURITY_AUTHENTICATION,
                AppConfig.getConfiguration().getString(Property.JUDDI_AUTHENTICATOR_STYLE, "simple"));
        env.put(Context.PROVIDER_URL, url); // organization ldap url, example ldap://localhost:389
        env.put(Context.SECURITY_PRINCIPAL, authorizedName);
        env.put(Context.SECURITY_CREDENTIALS, cred);
        ctx = new InitialLdapContext(env, null);
        isLdapUser = true;
        logger.info(authorizedName + " is authenticated");

    } catch (ConfigurationException e) {
        logger.error(authorizedName + " is not authenticated", e);
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } catch (NamingException e) {
        logger.error(authorizedName + " is not authenticated");
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    } finally {
        try {
            ctx.close();
        } catch (NamingException e) {
            logger.error("Context close failure " + e);
        }
    }

    if (isLdapUser) {
        EntityManager em = PersistenceManager.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        try {
            tx.begin();
            Publisher publisher = em.find(Publisher.class, authorizedName);
            if (publisher == null) {
                logger.warn("Publisher was not found, adding the publisher in on the fly.");
                publisher = new Publisher();
                publisher.setAuthorizedName(authorizedName);
                publisher.setIsAdmin("false");
                publisher.setIsEnabled("true");
                publisher.setMaxBindingsPerService(MaxBindingsPerService);
                publisher.setMaxBusinesses(MaxBusinesses);
                publisher.setMaxServicesPerBusiness(MaxServicesPerBusiness);
                publisher.setMaxTmodels(MaxTmodels);
                publisher.setPublisherName("Unknown");
                em.persist(publisher);
                tx.commit();
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            em.close();
        }
    } else {
        throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
    }
    return authorizedName;
}

From source file:org.easy.ldap.LdapContextFactory.java

/**
 * @param orgId//  www.  j a  v a 2 s .c o m
 * @param role
 * @return
 * @throws NamingException
 */
public DirContext createRoleContext(String orgId, String role) throws NamingException {
    Hashtable<String, String> properties = getEnviroment();
    properties.put(Context.PROVIDER_URL, createProviderUrl(namingFactory.createRoleDn(orgId, role).toString()));

    return createContext(properties);
}

From source file:com.aurel.track.util.LdapUtil.java

public static boolean authenticate(TSiteBean siteBean, String loginName, String ppassword)
        throws NamingException {
    boolean userIsOK = false;
    ArrayList<String> trace = new ArrayList<String>();

    trace.add("Ldap trying to authenticate user with loginname >" + loginName + "<");

    if (siteBean.getLdapServerURL().startsWith("ldaps:")) {
        System.setProperty("javax.net.ssl.trustStore", PATH_TO_KEY_STORE);
    }//from   www  .  j a  v  a2  s  .com
    // get the CN
    String keyDn = getCn(siteBean, loginName);

    try {
        if (keyDn != null) {
            trace.add("Using keyDn >" + keyDn + "<");
            // Set up the environment for creating the initial context
            Hashtable<String, String> env = new Hashtable<String, String>(11);
            env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
            env.put(Context.PROVIDER_URL, siteBean.getLdapServerURL());
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, keyDn);
            env.put(Context.SECURITY_CREDENTIALS, ppassword);
            // Create initial context
            DirContext itest = new InitialDirContext(env);
            itest.close();
            // user was validated
            userIsOK = true;
        }
        return userIsOK;
    } catch (NamingException e) {
        for (String msg : trace) {
            LOGGER.warn(msg);
        }
        throw e;
    }
}

From source file:org.talend.dataquality.email.checkerImpl.CallbackMailServerCheckerImpl.java

public void init() {
    // Prepare naming directory context.
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); //$NON-NLS-1$ //$NON-NLS-2$

    // if the user add the paramter for: java.naming.provider.url, if has then add it to env
    // Added TDQ-6918 Allow user add parameter: java.naming.provider.url
    String dnsUrl = dns;/*from  w ww  .  ja v a2s.com*/
    if (dnsUrl != null) {
        env.put(Context.PROVIDER_URL, dnsUrl);
    } // ~

    try {
        ictx = new InitialDirContext(env);
    } catch (NamingException e) {
        LOG.error("Invalid DNS: " + e); //$NON-NLS-1$
    }

}

From source file:org.rhq.jndi.AccessCheckingInitialContextFactoryBuilder.java

private static InitialContextFactory createSecureWrapper(InitialContextFactory factory,
        Hashtable<?, ?> environment) {
    String providerUrl = (String) environment.get(Context.PROVIDER_URL);

    if (providerUrl == null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Wrapping " + factory + " of class " + factory.getClass()
                    + " in an access checking wrapper. No provider URL detected.");
        }/*from w ww  .  j  a va  2s  . c o  m*/
        return getAccessCheckingFactory(factory);
    } else {
        try {
            URI uri = new URI(providerUrl);
            InetAddress providerHost = InetAddress.getByName(uri.getHost());

            //check if we are accessing the RHQ server through some remoting
            //interface.
            if (uri.getPort() == JNP_PORT && SERVER_BIND_IPS.contains(providerHost)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Wrapping " + factory + " of class " + factory.getClass()
                            + " in an access checking wrapper. The provider URL points to this server.");
                }
                return getAccessCheckingFactory(factory);
            } else {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Wrapping " + factory + " of class " + factory.getClass()
                            + " in an URL preferring wrapper to enable remote connections.");
                }
                return getURLPreferringFactory(factory);
            }
        } catch (URISyntaxException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("The " + Context.PROVIDER_URL
                        + " is not a valid URI. Falling back to using the access checking wrapper for the factory "
                        + factory + " of class " + factory.getClass() + ".", e);
            }
            return getAccessCheckingFactory(factory);
        } catch (UnknownHostException e) {
            //let the factory deal with the unknown host...
            //this most probably shouldn't be secured because localhost addresses
            //should be resolvable.
            if (LOG.isDebugEnabled()) {
                LOG.debug("The " + Context.PROVIDER_URL
                        + " is not resolvable. Falling back to using the URL preferring wrapper for the factory "
                        + factory + " of class " + factory.getClass() + ".", e);
            }
            return getURLPreferringFactory(factory);
        }
    }
}

From source file:org.grouter.common.hibernate.HibernateUtilContextAware.java

/**
 * Create session factories and configurations and store in hibernateConfigMap. On
 * completion we enter INITIALISED state.
 *///w ww. j  a v  a 2  s .  co m
private static void createSessionFactoriesFromConfigMap() {
    // read in all config and create session factories
    Iterator iter = hibernateConfigMap.keySet().iterator();
    while (iter.hasNext()) {
        SessionFactory sessionFactory;
        String key = (String) iter.next();
        HibernateConfigItem hibernateConfigItem = hibernateConfigMap.get(key);
        String file = hibernateConfigItem.getConfigFile();
        Configuration configuration;
        if (file == null) {
            log.info("Loading properties config and not from file ");
            configuration = hibernateConfigItem.getConfiguration();
        } else {
            log.info("Loading properties from : " + file);
            configuration = new Configuration();
            configuration = configuration.configure(file);
        }
        try {
            String sessionFactoryName = configuration.getProperty(Environment.SESSION_FACTORY_NAME);
            if (sessionFactoryName != null) {
                log.debug("Looking up SessionFactory in JNDI with name : " + sessionFactoryName);
                try {
                    Hashtable env = new Hashtable();
                    env.put(Context.INITIAL_CONTEXT_FACTORY, configuration.getProperty(Environment.JNDI_CLASS));
                    env.put(Context.URL_PKG_PREFIXES, configuration.getProperty(Environment.JNDI_PREFIX));
                    env.put(Context.PROVIDER_URL, configuration.getProperty(Environment.JNDI_URL));
                    Context context = new InitialContext(env);
                    JNDIUtils.printJNDI(context, log);
                    sessionFactory = (SessionFactory) context.lookup(sessionFactoryName);
                    if (sessionFactory == null) {
                        throw new IllegalStateException(
                                "SessionFactory from JNDI lookup returned a null implemenation  using file : "
                                        + file);
                    }
                } catch (NamingException ex) {
                    log.error("Failed looking up sessinfactory : " + sessionFactoryName, ex);
                    throw new RuntimeException(ex);
                }
            } else {
                sessionFactory = configuration.buildSessionFactory();
                if (sessionFactory == null) {
                    throw new IllegalStateException(
                            "SessionFactory could not be createed from the configuration using file : " + file);
                }
            }
            hibernateConfigItem.setConfiguration(configuration);
            hibernateConfigItem.setSessionFactory(sessionFactory);
            // We need to have a default sessionfactory / configuration
            if (hibernateConfigItem.isDeafult()) {
                hibernateConfigItemDefault = hibernateConfigItem;
            }
            // setInterceptor(configuration, null);
            // hibernateConfigMap.put(key)
        } catch (Throwable ex) {
            log.error("Failed initializing from configuration.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    currentState = STATE.INITIALISED;
    log.info("Entered state : " + currentState);
}

From source file:org.sonar.plugins.ldap.LdapContextFactory.java

private InitialDirContext createInitialDirContextUsingGssapi(String principal, String credentials)
        throws NamingException {
    Configuration.setConfiguration(new Krb5LoginConfiguration());
    InitialDirContext initialDirContext;
    try {//from w w  w .  j  a v a2s  .co m
        LoginContext lc = new LoginContext(getClass().getName(),
                new CallbackHandlerImpl(principal, credentials));
        lc.login();
        initialDirContext = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<InitialDirContext>() {
            @Override
            public InitialDirContext run() throws NamingException {
                Properties env = new Properties();
                env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
                env.put(Context.PROVIDER_URL, providerUrl);
                env.put(Context.REFERRAL, DEFAULT_REFERRAL);
                return new InitialLdapContext(env, null);
            }
        });
    } catch (LoginException | PrivilegedActionException e) {
        NamingException namingException = new NamingException(e.getMessage());
        namingException.initCause(e);
        throw namingException;
    }
    return initialDirContext;
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.LDAPUserDataProvider.java

/**
 * @throws NoSuchElementException if no user could be found with the given login
 * @throws AuthenticationException if the password does not match
 * @throws CommunicationException e.g. on server timeout
 * @throws NamingException on any other LDAP error
 *///from  w ww .  java2 s.  c  o m
private HashMap<String, String> auth(String login, String password) throws NamingException {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put("com.sun.jndi.ldap.read.timeout", timeout);
    env.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    if (binddn != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, binddn);
        env.put(Context.SECURITY_CREDENTIALS, bindpw);
    }

    HashMap<String, String> userAttrs = new HashMap<String, String>();
    String uid;

    DirContext ctx = new InitialDirContext(env);
    try {
        uid = searchUser(login, userAttrs, ctx);
    } finally {
        ctx.close();
    }

    if (passwordAttribute != null) {
        if (!userAttrs.containsKey("_pass"))
            throw new NoSuchElementException();
        String pass = userAttrs.get("_pass");
        if (pass == null || !pass.startsWith("{x-plain}"))
            throw new NoSuchElementException();
        log.debug("found password");
        pass = pass.substring(9);
        if (!pass.equals(password))
            throw new NoSuchElementException();
        userAttrs.remove("_pass");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, uid + "," + base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        DirContext ctx2 = new InitialDirContext(env);
        try {
            if (readAttributesAsSelf)
                searchUser(login, userAttrs, ctx2);
        } finally {
            ctx2.close();
        }
    }
    return userAttrs;
}

From source file:org.apache.synapse.util.DataSourceRegistrar.java

/**
 * Register data sources in the JNDI context
 * Given properties should contains all the properties need for construct JNDI naming references
 *
 * @param dsProperties The source properties
 *//*from   w ww  .j  a va2s . c  o  m*/
public static void registerDataSources(Properties dsProperties) {

    if (dsProperties == null) {
        if (log.isDebugEnabled()) {
            log.debug("DataSource properties cannot be found..");
        }
        return;
    }

    String dataSources = getProperty(dsProperties, SynapseConstants.SYNAPSE_DATASOURCES, null);

    if (dataSources == null || "".equals(dataSources)) {
        if (log.isDebugEnabled()) {
            log.debug("No DataSources defined for initialization..");
        }
        return;
    }

    String[] dataSourcesNames = dataSources.split(",");
    if (dataSourcesNames == null || dataSourcesNames.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug("No DataSource definitions found for initialization..");
        }
        return;
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append(SynapseConstants.SYNAPSE_DATASOURCES);
    buffer.append(DOT_STRING);
    // The prefix for root level properties
    String rootPrefix = buffer.toString();

    // setting naming provider
    Hashtable props = new Hashtable();
    Properties jndiEvn = new Properties(); //This is needed for PerUserPoolDatasource

    String namingFactory = getProperty(dsProperties, rootPrefix + PROP_ICFACTORY,
            "com.sun.jndi.rmi.registry.RegistryContextFactory");

    props.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);
    jndiEvn.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);

    String providerHost = "localhost";
    try {
        InetAddress addr = InetAddress.getLocalHost();
        if (addr != null) {
            String hostname = addr.getHostName();
            if (hostname == null) {
                String ipAddr = addr.getHostAddress();
                if (ipAddr != null) {
                    providerHost = ipAddr;
                }
            } else {
                providerHost = hostname;
            }
        }
    } catch (UnknownHostException e) {
        log.warn("Unable to determine hostname or IP address.. Using localhost", e);
    }

    // default port for RMI registry
    int port = 2199;
    String providerPort = getProperty(dsProperties, rootPrefix + PROP_PROVIDER_PORT, String.valueOf(port));
    try {
        port = Integer.parseInt(providerPort);
    } catch (NumberFormatException ignored) {
    }

    // Create a RMI local registry
    RMIRegistryController.getInstance().createLocalRegistry(port);

    String providerUrl = getProperty(dsProperties, rootPrefix + PROP_PROVIDER_URL,
            "rmi://" + providerHost + ":" + providerPort);

    props.put(Context.PROVIDER_URL, providerUrl);
    jndiEvn.put(Context.PROVIDER_URL, providerUrl);

    log.info("DataSources will be registered in the JNDI context with provider PROP_URL : " + providerUrl);

    try {
        InitialContext initialContext = new InitialContext(props);
        //Registering data sources with the initial context
        for (int i = 0; i < dataSourcesNames.length; i++) {
            registerDataSource(dataSourcesNames[i], dsProperties, initialContext, jndiEvn);
        }

    } catch (NamingException e) {
        String msg = "Error constructing an InitialContext to register DataSources";
        handleException(msg, e);
    }
}

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

/**
 * @return connection parameters to use for all LDAP queries
 */// ww w.j a v a  2  s .  com
protected Properties computeContextProperties() throws DirectoryException {
    LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor();
    // Initialization of LDAP connection parameters from parameters
    // registered in the LDAP "server" extension point
    Properties props = new Properties();
    LDAPServerDescriptor serverConfig = getServer();

    if (null == serverConfig) {
        throw new DirectoryException(
                "LDAP server configuration not found: " + ldapDirectoryDesc.getServerName());
    }

    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /*
     * Get initial connection URLs, dynamic URLs may cause the list to be updated when creating the session
     */
    String ldapUrls = serverConfig.getLdapUrls();
    if (ldapUrls == null) {
        throw new DirectoryException("Server LDAP URL configuration is missing for directory " + getName());
    }
    props.put(Context.PROVIDER_URL, ldapUrls);

    // define how referrals are handled
    if (!getDescriptor().getFollowReferrals()) {
        props.put(Context.REFERRAL, "ignore");
    } else {
        // this is the default mode
        props.put(Context.REFERRAL, "follow");
    }

    /*
     * SSL Connections do not work with connection timeout property
     */
    if (serverConfig.getConnectionTimeout() > -1) {
        if (!serverConfig.useSsl()) {
            props.put("com.sun.jndi.ldap.connect.timeout",
                    Integer.toString(serverConfig.getConnectionTimeout()));
        } else {
            log.warn("SSL connections do not operate correctly"
                    + " when used with the connection timeout parameter, disabling timout");
        }
    }

    String bindDn = serverConfig.getBindDn();
    if (bindDn != null) {
        // Authenticated connection
        props.put(Context.SECURITY_PRINCIPAL, bindDn);
        props.put(Context.SECURITY_CREDENTIALS, serverConfig.getBindPassword());
    }

    if (serverConfig.isPoolingEnabled()) {
        // Enable connection pooling
        props.put("com.sun.jndi.ldap.connect.pool", "true");
        props.put("com.sun.jndi.ldap.connect.pool.protocol", "plain ssl");
        props.put("com.sun.jndi.ldap.connect.pool.authentication", "none simple DIGEST-MD5");
        props.put("com.sun.jndi.ldap.connect.pool.timeout", "1800000"); // 30
        // min
    }

    if (!serverConfig.isVerifyServerCert() && serverConfig.useSsl) {
        props.put("java.naming.ldap.factory.socket",
                "org.nuxeo.ecm.directory.ldap.LDAPDirectory$TrustingSSLSocketFactory");
    }

    return props;
}