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:ru.runa.wfe.security.logic.LdapLogic.java

private Pattern getPatternForMissedPeople() {
    if (patternForMissedPeople == null) {
        String providerUrl = LdapProperties.getAllProperties().get(Context.PROVIDER_URL);
        String dc = providerUrl.substring(providerUrl.lastIndexOf("/") + 1);
        patternForMissedPeople = Pattern.compile("," + dc, Pattern.CASE_INSENSITIVE);
    }/*from w  w  w.  j a  v  a  2 s.c om*/
    return patternForMissedPeople;
}

From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java

/**
 * return false if user or password is wrong
 *    /*from   ww  w .  j  a  v a2s.  c  om*/
 * here we expand attributes: %u, %d, %s
 *    if defined userSearch, retrieve user's DN  and try to bind with it
 * @param username
 * @param password
 * @return
 */
private boolean ldapBind(String username, String password) {
    String userDN = null;
    try {
        TempParams t = new TempParams();
        // if username  is an email substitute %u e %d in baseDn:  
        expandSearchAndBaseDn(username, t);

        // setup the default LdapInterface configured with bean data
        ldapInterface = LDAPManagerFactory.createLdapInterface(getLdapInterfaceClassName());
        ldapInterface.init(getLdapUrl(), getBaseDn(), getSearchBindDn(), getSearchBindPassword(),
                isFollowReferral(), isConnectionPooling(), null);

        // set the userDN when custom user search
        if (!StringUtils.isEmpty(getUserSearch())) {
            // customize the field used to search the user.

            SearchResult sr = ldapInterface.searchOneEntry(getUserSearch(), new String[] { "dn" },
                    SearchControls.SUBTREE_SCOPE);

            if (sr == null) {
                log.info("Username " + username + " not found");
                return false;
            }

            userDN = sr.getNameInNamespace().trim();
            log.info("binding with dn:" + userDN);

        }
        // on failure, set the user DN with append
        if (userDN == null) {
            userDN = "uid=" + username + "," + baseDn;
        }
    } catch (Exception e) {
        log.error("Can't instantiate LdapInterface: " + e.getMessage());
        return false;
    }
    // Set up environment for creating 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, getLdapUrl());

    // Authenticate as  User and password  
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, userDN);
    env.put(Context.SECURITY_CREDENTIALS, password);

    try {
        DirContext ctx = new InitialDirContext(env);
        log.debug(ctx.lookup(userDN));
        ctx.close();
    } catch (AuthenticationException e) {
        log.info("User not authenticated: " + e.getMessage());
        return false;
    } catch (NamingException e) {
        log.warn("User not authenticated: problem while accessing ldap " + e.getMessage());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.mule.transport.ldap.util.DSManager.java

protected void setContexts(final Hashtable<String, Object> env) throws Exception {
    final Hashtable<String, Object> envFinal = new Hashtable<String, Object>(env);
    // envFinal.put( Context.PROVIDER_URL, "dc=example,dc=com" );
    // exampleRoot = new InitialLdapContext( envFinal, null );

    // Hashtable<String, Object> envFinal = new Hashtable<String, Object>(
    // env );/*from  ww  w  .jav  a  2s . com*/
    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.SYSTEM_DN);
    sysRoot = new InitialLdapContext(envFinal, null);

    envFinal.put(Context.PROVIDER_URL, "");
    rootDSE = directoryService.getAdminSession();
    root = new InitialLdapContext(envFinal, null);

    envFinal.put(Context.PROVIDER_URL, ServerDNConstants.OU_SCHEMA_DN);
    schemaRoot = new InitialLdapContext(envFinal, null);
}

From source file:net.sf.farrago.namespace.jdbc.MedJdbcDataServer.java

private void initializeDataSource() throws SQLException {
    assert (!disableConnectionPool);

    if (jndiName != null) {
        try {//  www.  j a va  2 s  .  c  o  m
            // TODO: Allow specification of initial context factory and
            // provider URL via addition options.  These should be stored
            // in jndiEnv before the initJndi call and the names (keys) of
            // the those properties would be used in the JndiUtil
            // constructor. Can also allow artibrary env properties.
            JndiUtil jndiUtil = new JndiUtil("", Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL);

            Properties jndiEnv = new Properties();
            jndiUtil.initJndi(jndiEnv);
            InitialContext initCtx = jndiUtil.newInitialContext(jndiEnv);

            dataSource = jndiUtil.lookup(initCtx, jndiName, DataSource.class);

            if (dataSource == null) {
                throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName);
            }

            return;
        } catch (NamingException e) {
            throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName, e);
        }
    }

    String userName = getUserName();
    String password = getPassword();

    ConnectionFactory connectionFactory;
    if (connectProps != null) {
        if (userName != null) {
            connectProps.setProperty("user", userName);
        }
        if (password != null) {
            connectProps.setProperty("password", password);
        }

        connectionFactory = new DriverManagerConnectionFactory(url, connectProps);
    } else if (userName == null) {
        connectionFactory = new DriverManagerConnectionFactory(url, new Properties());
    } else {
        if (password == null) {
            password = "";
        }

        connectionFactory = new DriverManagerConnectionFactory(url, userName, password);
    }

    if (validateWhileIdle && (evictionTimerPeriodMillis <= 0L)) {
        logger.warning("Request to validate on idle ignored: property " + PROP_EVICTION_TIMER_PERIOD_MILLIS
                + " must be > 0");

        if ((validationQuery != null) && !validateOnBorrow && !validateOnReturn) {
            validateOnBorrow = true;

            logger.warning("Enabling validation on request");
        }
    }

    connectionPool = new GenericObjectPool();
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setMaxActive(-1);

    connectionPool.setTestOnBorrow(validateOnBorrow);
    connectionPool.setTestOnReturn(validateOnReturn);
    connectionPool.setTestWhileIdle(validateWhileIdle);

    connectionPool.setMaxIdle(maxIdleConnections);
    connectionPool.setTimeBetweenEvictionRunsMillis(evictionTimerPeriodMillis);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictionIdleMillis);

    CustomPoolableConnectionFactory poolableConnectionFactory = new CustomPoolableConnectionFactory(
            connectionFactory, connectionPool, validationQuery, autocommit, null);

    connectionPool.setFactory(poolableConnectionFactory);
    PoolingDataSource pds = new PoolingDataSource(connectionPool);
    pds.setAccessToUnderlyingConnectionAllowed(true);
    dataSource = pds;
}

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected DirContext getConnection() {
    //JNDI boilerplate to connect to an initial context
    DirContext context = (DirContext) contexts.get("context");
    if (context == null) {
        Hashtable jndienv = new Hashtable();
        jndienv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        jndienv.put(Context.SECURITY_AUTHENTICATION, "simple");
        if (url.startsWith("ldaps")) { // Handle SSL connections
            String newurl = url.substring(0, 4) + url.substring(5);
            jndienv.put(Context.SECURITY_PROTOCOL, "ssl");
            jndienv.put(Context.PROVIDER_URL, newurl);
        } else {//ww w .  j av a 2s. c o m
            jndienv.put(Context.PROVIDER_URL, url);
        }
        if (logonid != null)
            jndienv.put(Context.SECURITY_PRINCIPAL, logonid);
        if (logonpassword != null)
            jndienv.put(Context.SECURITY_CREDENTIALS, logonpassword);
        try {
            context = new InitialDirContext(jndienv);
        } catch (NamingException nex) {
            log.error("LDAPGroupStore: unable to get context", nex);
        }
        contexts.put("context", context);
    }
    return context;
}

From source file:org.wso2.carbon.connector.integration.test.ldap.LdapConnectorIntegrationTest.java

public void deleteSampleEntry() throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    env.put(Context.PROVIDER_URL, providerUrl);
    env.put(Context.SECURITY_PRINCIPAL, securityPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, securityCredentials);

    DirContext ctx = new InitialDirContext(env);
    String dn = "uid=" + testUserId + "," + userBase;
    ctx.destroySubcontext(dn);/*from  w w  w . j  a v  a2s. c  o  m*/
}

From source file:org.apache.synapse.commons.datasource.JNDIBasedDataSourceRepository.java

private Properties createJNDIEnvironment(Properties dsProperties, String name) {

    String namingFactory = DataSourceConstants.DEFAULT_IC_FACTORY;
    String providerUrl = null;/*from w  ww.ja va2s. c  o m*/
    int port = DataSourceConstants.DEFAULT_PROVIDER_PORT;
    String providerPort = null;
    // setting naming provider
    Properties jndiEvn = new Properties(); //This is needed for PerUserPoolDatasource

    if (dsProperties != null && !dsProperties.isEmpty()) {

        if (log.isDebugEnabled()) {
            log.debug("Using properties " + dsProperties + " to create JNDI Environment");
        }

        StringBuffer buffer = new StringBuffer();
        buffer.append(DataSourceConstants.PROP_SYNAPSE_PREFIX_DS);
        buffer.append(DataSourceConstants.DOT_STRING);
        if (name != null && !"".equals(name)) {
            buffer.append(name);
            buffer.append(DataSourceConstants.DOT_STRING);
        }
        // The prefix for root level jndiProperties
        String rootPrefix = buffer.toString();

        namingFactory = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_IC_FACTORY, DataSourceConstants.DEFAULT_IC_FACTORY);

        //Provider URL
        providerUrl = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_PROVIDER_URL, null);
        providerPort = MiscellaneousUtil.getProperty(dsProperties,
                rootPrefix + DataSourceConstants.PROP_PROVIDER_PORT,
                String.valueOf(DataSourceConstants.DEFAULT_PROVIDER_PORT));

    }

    jndiEvn.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);

    if (providerUrl != null && !"".equals(providerUrl)) {
        if (log.isDebugEnabled()) {
            log.debug("Using provided initial context provider url :" + providerUrl);
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("No initial context provider url...creaeting a new one");
        }
        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

        if (providerPort != null) {
            try {
                port = Integer.parseInt(providerPort);
            } catch (NumberFormatException ignored) {
            }
        }

        // Create a RMI local registry
        RMIRegistryController.getInstance().createLocalRegistry(port);
        cachedPorts.add(port);
        providerUrl = "rmi://" + providerHost + ":" + port;

    }

    jndiEvn.put(Context.PROVIDER_URL, providerUrl);

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

From source file:org.hyperic.hq.plugin.jboss.JBossDetector.java

private List<ServiceResource> discoverJBossServices(ConfigResponse serverConfig) throws PluginException {

    String url = serverConfig.getValue(Context.PROVIDER_URL);
    MBeanServerConnection mServer;

    try {/*from   ww  w.  ja va  2  s . c o  m*/
        mServer = JBossUtil.getMBeanServerConnection(serverConfig.toProperties());
    } catch (Exception e) {
        throw new PluginException(e.getMessage(), e);
    }

    // ******* A BORRAR ********** //
    /*try {
    Iterator res=mServer.queryNames(null, null).iterator();
    while(res.hasNext()){
    getLog().debug("---> "+res.next());
    }
    } catch (IOException ex) {
    Logger.getLogger(JBossDetector.class.getName()).log(Level.SEVERE, null, ex);
    }*/
    // ***************** //

    configure(serverConfig); //for ServerQuery to use detector.getConfig()
    ServerQuery serverQuery = new ServerQuery(this);
    serverQuery.setURL(url);
    serverQuery.getAttributes(mServer);

    serverQuery.findServices(mServer);

    List queries = serverQuery.getServiceQueries();
    getLog().debug("discovered " + queries.size() + " services");

    List<ServiceResource> services = new ArrayList<ServiceResource>();

    for (int i = 0; i < queries.size(); i++) {
        ServiceQuery query = (ServiceQuery) queries.get(i);
        ServiceResource service = new ServiceResource();
        service.setName(query.getQualifiedName());
        service.setType(query.getResourceType());

        ConfigResponse _config = new ConfigResponse(query.getResourceConfig());

        if (query.hasControl()) {
            ConfigResponse controlConfig = new ConfigResponse(query.getControlConfig());
            service.setControlConfig(controlConfig);
        }

        service.setProductConfig(_config);
        service.setMeasurementConfig();

        _config = new ConfigResponse(query.getCustomProperties());
        service.setCustomProperties(_config);

        services.add(service);
    }

    //look for any cprop keys in the attributes
    ConfigResponse cprops = new ConfigResponse();
    String[] attrs = this.getCustomPropertiesSchema().getOptionNames();
    for (int i = 0; i < attrs.length; i++) {
        String key = attrs[i];
        String val = serverQuery.getAttribute(key);
        if (val != null) {
            cprops.setValue(key, val);
        }
    }
    setCustomProperties(cprops);

    return services;
}