Example usage for javax.naming Context INITIAL_CONTEXT_FACTORY

List of usage examples for javax.naming Context INITIAL_CONTEXT_FACTORY

Introduction

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

Prototype

String INITIAL_CONTEXT_FACTORY

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

Click Source Link

Document

Constant that holds the name of the environment property for specifying the initial context factory to use.

Usage

From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????/*from w w  w . jav  a  2 s  . c om*/
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

        bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException e) {
                    m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(DNS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:org.projectforge.business.ldap.LdapConnector.java

private Hashtable<String, String> createEnv(final String user, final String password) {
    // Set up the environment for creating the initial context
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapConfig.getCompleteServerUrl());
    final String authentication = ldapConfig.getAuthentication();
    if (StringUtils.isNotBlank(authentication) == true) {
        env.put(Context.SECURITY_AUTHENTICATION, ldapConfig.getAuthentication());
        if ("none".equals(authentication) == false && user != null && password != null) {
            env.put(Context.SECURITY_PRINCIPAL, user);
            env.put(Context.SECURITY_CREDENTIALS, password);
        }/*from   ww w .ja  va 2s . c o  m*/
    }
    if (ldapConfig != null && StringUtils.isNotBlank(ldapConfig.getSslCertificateFile()) == true) {
        env.put("java.naming.ldap.factory.socket", "org.projectforge.business.ldap.MySSLSocketFactory");
    }
    log.info("Trying to connect the LDAP server: url=[" + ldapConfig.getCompleteServerUrl()
            + "], authentication=[" + ldapConfig.getAuthentication() + "], principal=[" + user + "]");
    return env;
}

From source file:org.apache.openejb.assembler.classic.ResourcesJsonTest.java

@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));

    final AppModule app = new AppModule(ResourcesJsonTest.class.getClassLoader(),
            ResourcesJsonTest.class.getSimpleName());

    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(ConfiguredThroughJSonBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));
    app.getEjbModules().iterator().next().getAltDDs().put("resources.json",
            getClass().getClassLoader().getResource("appresource.resources.json"));

    assembler.createApplication(config.configureApplication(app));

    final Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
    properties.setProperty("openejb.embedded.initialcontext.close", "destroy");

    // some hack to be sure to call destroy()
    context = new InitialContext(properties);

    bean = (ConfiguredThroughJSonBean) context.lookup("ConfiguredThroughJSonBeanLocalBean");
}

From source file:org.apache.openejb.assembler.classic.OpenEJBXmlByModuleTest.java

@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
    final ConfigurationFactory config = new ConfigurationFactory();
    final Assembler assembler = new Assembler();

    assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
    assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));

    final AppModule app = new AppModule(OpenEJBXmlByModuleTest.class.getClassLoader(),
            OpenEJBXmlByModuleTest.class.getSimpleName());

    final EjbJar ejbJar = new EjbJar();
    ejbJar.addEnterpriseBean(new SingletonBean(UselessBean.class));
    app.getEjbModules().add(new EjbModule(ejbJar));
    app.getEjbModules().iterator().next().getAltDDs().put("resources.xml",
            getClass().getClassLoader().getResource("META-INF/resource/appresource.openejb.xml"));

    assembler.createApplication(config.configureApplication(app));

    final Properties properties = new Properties();
    properties.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY,
            LocalInitialContextFactory.class.getName());
    properties.setProperty("openejb.embedded.initialcontext.close", "destroy");

    // some hack to be sure to call destroy()
    context = new InitialContext(properties);

    bean = (UselessBean) context.lookup("UselessBeanLocalBean");
}

From source file:org.exoplatform.services.jcr.util.TesterConfigurationHelper.java

private TesterConfigurationHelper() {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.exoplatform.services.naming.SimpleContextFactory");
}

From source file:org.eclipselabs.etrack.util.security.ldap.impl.LdapSecurityService.java

void activate(Map<?, ?> configuration) throws NamingException {
    this.url = (String) configuration.get(CONFIG_URL);
    this.baseDN = (String) configuration.get(CONFIG_BASE_DN);
    String managerDN = (String) configuration.get(CONFIG_MANAGER_DN);
    String managerPassword = (String) configuration.get(CONFIG_MANAGER_PASSWORD);

    Hashtable<String, String> environment = new Hashtable<String, String>();
    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.PROVIDER_URL, url);

    if (managerDN != null) {
        environment.put(Context.SECURITY_AUTHENTICATION, "simple");
        environment.put(Context.SECURITY_PRINCIPAL, managerDN);
        environment.put(Context.SECURITY_CREDENTIALS, managerPassword);
    } else//  ww w. j  av  a 2 s.com
        environment.put(Context.SECURITY_AUTHENTICATION, "none");

    searchContext = new InitialDirContext(environment);
}

From source file:it.doqui.index.ecmengine.client.backoffice.EcmEngineBackofficeDirectDelegateImpl.java

@Override
protected EcmEngineBackofficeBusinessInterface createBackofficeService() throws Throwable {
    Properties properties = new Properties();
    this.log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] BEGIN ");

    rb = ResourceBundle.getBundle(ECMENGINE_BKO_PROPERTIES_FILE);
    /*/*from  w w  w. j  a  v  a 2s  .  c  o m*/
     * Caricamento della porta delegata del backoffice.
     */
    try {
        this.log.debug(
                "[" + getClass().getSimpleName() + "::createBackofficeService] P-Delegata di backoffice.");

        this.log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] context factory vale : "
                + rb.getString(ECMENGINE_BKO_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_BKO_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] url to connect vale : "
                + rb.getString(ECMENGINE_BKO_URL_TO_CONNECT));
        properties.put(Context.PROVIDER_URL, rb.getString(ECMENGINE_BKO_URL_TO_CONNECT));

        /* Controllo che la property cluster partition sia valorizzata per capire se 
         * sto lavorando in una configurazione in cluster oppure no */
        String clusterPartition = rb.getString(ECMENGINE_BKO_CLUSTER_PARTITION);
        this.log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug(
                    "[" + getClass().getSimpleName() + "::createBackofficeService] disable discovery vale : "
                            + rb.getString(ECMENGINE_BKO_DISABLE_DISCOVERY));
            properties.put("jnp.disableDiscovery", rb.getString(ECMENGINE_BKO_DISABLE_DISCOVERY));
        }

        // Get an initial context
        InitialContext jndiContext = new InitialContext(properties);
        log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] context istanziato");

        // Get a reference to the Bean
        Object ref = jndiContext.lookup(ECMENGINE_BKO_JNDI_NAME);

        // Get a reference from this to the Bean's Home interface
        EcmEngineBackofficeHome home = (EcmEngineBackofficeHome) PortableRemoteObject.narrow(ref,
                EcmEngineBackofficeHome.class);

        // Create an Adder object from the Home interface
        return home.create();

    } catch (Throwable e) {
        this.log.error("[" + getClass().getSimpleName() + "::createBackofficeService] "
                + "Impossibile istanziare la P-Delegata di backoffice: " + e.getMessage());
        throw e;
    } finally {
        this.log.debug("[" + getClass().getSimpleName() + "::createBackofficeService] END ");
    }
}

From source file:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public LDAPConnectionContext(RealmConfiguration realmConfig) throws UserStoreException {

    //if DNS is enabled, populate DC Map
    String DNSUrl = realmConfig.getUserStoreProperty(LDAPConstants.DNS_URL);
    if (DNSUrl != null) {
        DNSDomainName = realmConfig.getUserStoreProperty(LDAPConstants.DNS_DOMAIN_NAME);
        if (DNSDomainName == null) {
            throw new UserStoreException("DNS is enabled, but DNS domain name not provided.");
        } else {/*from   ww w .  j a  v a  2  s.c o m*/
            environmentForDNS = new Hashtable();
            environmentForDNS.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
            environmentForDNS.put("java.naming.provider.url", DNSUrl);
            populateDCMap();
        }
        //need to keep track of if the user store config is read only
        String readOnlyString = realmConfig
                .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_READ_ONLY);
        if (readOnlyString != null) {
            readOnly = Boolean.parseBoolean(readOnlyString);
        }
    }

    String rawConnectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
    String connectionURL = null;
    //if DNS enabled in AD case, this can be null
    if (rawConnectionURL != null) {
        String portInfo = rawConnectionURL.split(":")[2];

        String port = null;

        // if the port contains a template string that refers to carbon.xml
        if ((portInfo.contains("${")) && (portInfo.contains("}"))) {
            port = Integer.toString(CarbonUtils.getPortFromServerConfig(portInfo));
        }

        if (port != null) {
            connectionURL = rawConnectionURL.replace(portInfo, port);
        } else {
            // if embedded-ldap is not enabled,
            connectionURL = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_URL);
        }
    }

    String connectionName = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }

    environment = new Hashtable();

    environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    environment.put(Context.SECURITY_AUTHENTICATION, "simple");

    /**
     * In carbon JNDI context we need to by pass specific tenant context and we need the base
     * context for LDAP operations.
     */
    environment.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");

    if (connectionName != null) {
        environment.put(Context.SECURITY_PRINCIPAL, connectionName);
    }

    if (connectionPassword != null) {
        environment.put(Context.SECURITY_CREDENTIALS, connectionPassword);
    }

    if (connectionURL != null) {
        environment.put(Context.PROVIDER_URL, connectionURL);
    }

    // Enable connection pooling if property is set in user-mgt.xml
    boolean isLDAPConnectionPoolingEnabled = false;
    String value = realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_POOLING_ENABLED);

    if (value != null && !value.trim().isEmpty()) {
        isLDAPConnectionPoolingEnabled = Boolean.parseBoolean(value);
    }

    environment.put("com.sun.jndi.ldap.connect.pool", isLDAPConnectionPoolingEnabled ? "true" : "false");

    // set referral status if provided in configuration.
    if (realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral",
                realmConfig.getUserStoreProperty(LDAPConstants.PROPERTY_REFERRAL));
    }

    String binaryAttribute = realmConfig.getUserStoreProperty(LDAPConstants.LDAP_ATTRIBUTES_BINARY);

    if (binaryAttribute != null) {
        environment.put(LDAPConstants.LDAP_ATTRIBUTES_BINARY, binaryAttribute);
    }

    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = realmConfig.getUserStoreProperty(CONNECTION_TIME_OUT);
    if (connectTimeout != null && !connectTimeout.trim().isEmpty()) {
        environment.put("com.sun.jndi.ldap.connect.timeout", connectTimeout);
    } else {
        environment.put("com.sun.jndi.ldap.connect.timeout", "5000");
    }
}

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

public void collect() {

    // Setup initial LDAP properties
    Properties env = new Properties();
    Properties props = getProperties();

    // Set our default factory name if one is not given
    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    }/*www.  j a  v  a  2s  .  c om*/

    // Set the LDAP url
    if (isSSL()) {
        env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName());
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    String providerUrl = "ldap://" + getHostname() + ":" + getPort();
    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // For log track
    setSource(providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "follow");

    // Base DN
    String baseDN = props.getProperty(PROP_BASEDN);
    if (baseDN == null) {
        setErrorMessage("No Base DN given, refusing login");
        setAvailability(false);
        return;
    }

    // Search filter
    String filter = props.getProperty(PROP_FILTER);

    // Load any information we may need to bind
    String bindDN = props.getProperty(PROP_BINDDN);
    String bindPW = props.getProperty(PROP_BINDPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    if (log.isDebugEnabled()) {
        log.debug("Using LDAP environment: " + env);
    }

    try {
        startTime();
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        endTime();

        setAvailability(true);

        // If a search filter is specified, run the search and return the
        // number of matches as a metric
        if (filter != null) {
            log.debug("Using LDAP filter=" + filter);
            NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls());

            long matches = 0;
            while (answer.hasMore()) {
                matches++;
                answer.next();
            }

            setValue("NumberofMatches", matches);
        }
    } catch (Exception e) {
        setAvailability(false);
        if (log.isDebugEnabled()) {
            log.debug("LDAP check failed: " + e, e);
        }

        setErrorMessage("LDAP check failed: " + e);
    }
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

/**
 Access an unchecked method with a valid login that calls the same method
 on another bean using a run-as role./*from  w w w.j a  v a2  s .  c  om*/
        
 @throws Exception
 */
public void testPublicMethod() throws Exception {
    log.debug("+++ testPublicMethod()");
    Properties env = new Properties();
    env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.security.jndi.JndiLoginInitialContextFactory");
    env.setProperty(Context.SECURITY_PRINCIPAL, "jduke");
    env.setProperty(Context.SECURITY_CREDENTIALS, "theduke");
    InitialContext ctx = new InitialContext(env);
    Object obj = ctx.lookup("jacc/Secured");
    obj = PortableRemoteObject.narrow(obj, SecuredServiceRemoteHome.class);
    SecuredServiceRemoteHome home = (SecuredServiceRemoteHome) obj;
    log.debug("Found SecuredServiceRemoteHome");
    SecuredServiceRemote bean = home.create();
    log.debug("Created SecuredServiceRemote");

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);
    bean.publicMethod(info);
    bean.remove();
}