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:org.apache.axis2.transport.jms.JMSListener.java

/**
 * Initialize the defined connection factories, parsing the TransportIn
 * descriptions/*  w  w  w  . j  a  v a2  s .co m*/
 *
 * @param transprtIn The Axis2 Transport in for the JMS
 */
private void initializeConnectionFactories(TransportInDescription transprtIn) {
    // iterate through all defined connection factories
    Iterator conFacIter = transprtIn.getParameters().iterator();

    while (conFacIter.hasNext()) {

        Parameter param = (Parameter) conFacIter.next();
        JMSConnectionFactory jmsConFactory = new JMSConnectionFactory(param.getName());

        ParameterIncludeImpl pi = new ParameterIncludeImpl();
        try {
            pi.deserializeParameters((OMElement) param.getValue());
        } catch (AxisFault axisFault) {
            handleException(
                    "Error reading Parameters for JMS connection " + "factory" + jmsConFactory.getName(),
                    axisFault);
        }

        // read connection facotry properties
        Iterator params = pi.getParameters().iterator();

        while (params.hasNext()) {
            Parameter p = (Parameter) params.next();

            if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) {
                jmsConFactory.addProperty(Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue());
            } else if (Context.PROVIDER_URL.equals(p.getName())) {
                jmsConFactory.addProperty(Context.PROVIDER_URL, (String) p.getValue());
            } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) {
                jmsConFactory.addProperty(Context.SECURITY_PRINCIPAL, (String) p.getValue());
            } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) {
                jmsConFactory.addProperty(Context.SECURITY_CREDENTIALS, (String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) {
                jmsConFactory.setJndiName((String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_USER.equals(p.getName())) {
                jmsConFactory.setJndiUser((String) p.getValue());
            } else if (JMSConstants.CONFAC_JNDI_NAME_PASS.equals(p.getName())) {
                jmsConFactory.setJndiPass((String) p.getValue());
            } else if (JMSConstants.DEST_PARAM.equals(p.getName())) {
                StringTokenizer st = new StringTokenizer((String) p.getValue(), " ,");
                while (st.hasMoreTokens()) {
                    jmsConFactory.addDestination(st.nextToken(), null);
                }
            }
        }

        // connect to the actual connection factory
        try {
            jmsConFactory.connect();
            connectionFactories.put(jmsConFactory.getName(), jmsConFactory);
        } catch (NamingException e) {
            handleException("Error connecting to JMS connection factory : " + jmsConFactory.getJndiName(), e);
        }
    }
}

From source file:org.openadaptor.auxil.connector.jndi.JNDIConnection.java

protected Properties getConnectionProperties(Properties customProperties, String contextFactory,
        String providerUrl, String authentication, String principal, String credentials) {
    Properties env = new Properties();
    if (customProperties != null) {
        env.putAll(customProperties);/* w  w w  .  j  a va 2 s .  c o m*/
    }
    if (contextFactory != null) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
    }
    if (providerUrl != null) {
        env.put(Context.PROVIDER_URL, _providerUrl);
    }
    // Authentication details
    if (authentication != null) {
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
    }
    if (principal != null) {
        env.put(Context.SECURITY_PRINCIPAL, principal);
    }
    if (credentials != null) {
        env.put(Context.SECURITY_CREDENTIALS, credentials);
    }
    return env;
}

From source file:org.sonar.plugins.activedirectory.server.ApacheDS.java

/**
 * This seems to be required for objectClass posixGroup.
 *///w w w . j a  va  2s . c  o  m
private ApacheDS activateNis() throws Exception {
    Preconditions.checkState(ldapServer.isStarted());

    Attribute disabled = new BasicAttribute("m-disabled", "TRUE");
    Attribute disabled2 = new BasicAttribute("m-disabled", "FALSE");
    ModificationItem[] mods = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, disabled),
            new ModificationItem(DirContext.ADD_ATTRIBUTE, disabled2) };

    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, getUrl());

    DirContext ctx = new InitialDirContext(env);
    ctx.modifyAttributes("cn=nis,ou=schema", mods);

    return this;
}

From source file:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {//  www  . ja  v a2 s  .co  m
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:it.doqui.index.ecmengine.client.engine.EcmEngineDirectDelegateImpl.java

protected EcmEngineSecurityBusinessInterface createSecurityService() throws Throwable {
    this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] BEGIN ");

    Properties properties = new Properties();

    // Caricamento del file contenenti le properties su cui fare il binding
    rb = ResourceBundle.getBundle(ECMENGINE_PROPERTIES_FILE);

    // Caricamento delle proprieta' su cui fare il binding all'oggetto di business delle funzionalita'
    // implementate per la ricerca.
    try {/*from w  w w.  j a v a 2  s.c o m*/
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] P-Delegata di backoffice.");

        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] context factory vale : "
                + rb.getString(ECMENGINE_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] url to connect vale : "
                + rb.getString(ECMENGINE_URL_TO_CONNECT));
        properties.put(Context.PROVIDER_URL, rb.getString(ECMENGINE_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_CLUSTER_PARTITION);
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug("[" + getClass().getSimpleName() + "::createSearchService] disable discovery vale : "
                    + rb.getString(ECMENGINE_DISABLE_DISCOVERY));
            properties.put("jnp.disableDiscovery", rb.getString(ECMENGINE_DISABLE_DISCOVERY));
        }

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

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

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

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

    } catch (Throwable e) {
        this.log.error("[" + getClass().getSimpleName() + "::createSecurityService] "
                + "Impossibile l'EJB di security: " + e.getMessage());
        throw e;
    } finally {
        this.log.debug("[" + getClass().getSimpleName() + "::createSecurityService] END ");
    }
}

From source file:org.jboss.ejb3.locator.client.Ejb3ServiceLocatorImpl.java

/**
 * Return vendor-specific properties for the naming context
 * //  w ww  . ja  v  a  2  s.c o  m
 * @return
 */
// TODO Externalize to allow for other vendor implementations
private Properties getVendorNamingContextProperties() {
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
    props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
    return props;
}

From source file:de.sub.goobi.helper.ldap.Ldap.java

/**
 * retrieve home directory of given user.
 *
 * @param inBenutzer//w ww  .  j  a v  a2 s .  com
 *            User object
 * @return path as string
 */
public String getUserHomeDirectory(User inBenutzer) {
    if (ConfigCore.getBooleanParameter("useLocalDirectory", false)) {
        return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
    }
    Hashtable<String, String> env = getLdapConnectionSettings();
    if (ConfigCore.getBooleanParameter("ldap_useTLS", false)) {

        env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ConfigCore.getParameter("ldap_url"));
        env.put("java.naming.ldap.version", "3");
        LdapContext ctx = null;
        StartTlsResponse tls = null;
        try {
            ctx = new InitialLdapContext(env, null);

            // Authentication must be performed over a secure channel
            tls = (StartTlsResponse) ctx.extendedOperation(new StartTlsRequest());
            tls.negotiate();

            // Authenticate via SASL EXTERNAL mechanism using client X.509
            // certificate contained in JVM keystore
            ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple");
            ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
            ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

            ctx.reconnect(null);

            Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
            Attribute la = attrs.get("homeDirectory");
            return (String) la.get(0);

            // Perform search for privileged attributes under authenticated
            // context

        } catch (IOException e) {
            logger.error("TLS negotiation error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } catch (NamingException e) {

            logger.error("JNDI error:", e);

            return ConfigCore.getParameter("dir_Users") + inBenutzer.getLogin();
        } finally {
            if (tls != null) {
                try {
                    // Tear down TLS connection
                    tls.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
            if (ctx != null) {
                try {
                    // Close LDAP connection
                    ctx.close();
                } catch (NamingException e) {
                    logger.error(e);
                }
            }
        }
    } else if (ConfigCore.getBooleanParameter("useSimpleAuthentification", false)) {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    } else {
        env.put(Context.SECURITY_PRINCIPAL, ConfigCore.getParameter("ldap_adminLogin"));
        env.put(Context.SECURITY_CREDENTIALS, ConfigCore.getParameter("ldap_adminPassword"));

    }
    DirContext ctx;
    String rueckgabe = "";
    try {
        ctx = new InitialDirContext(env);
        Attributes attrs = ctx.getAttributes(getUserDN(inBenutzer));
        Attribute la = attrs.get("homeDirectory");
        rueckgabe = (String) la.get(0);
        ctx.close();
    } catch (NamingException e) {
        logger.error(e);
    }
    return rueckgabe;
}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAOTest.java

private static void initializeDatabase(String configFilePath) {
    InputStream in;//from   w w  w. j av a  2  s  .  c  o m
    try {
        in = FileUtils.openInputStream(new File(configFilePath));
        StAXOMBuilder builder = new StAXOMBuilder(in);
        String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
                .getText();
        OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
        String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
        String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
        String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
        String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriver);
        basicDataSource.setUrl(databaseURL);
        basicDataSource.setUsername(databaseUser);
        basicDataSource.setPassword(databasePass);

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        try {
            InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
        } catch (NamingException e) {
            InitialContext ic = new InitialContext();
            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");
            ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
        }
    } catch (XMLStreamException | IOException | NamingException e) {
        log.error(e);
    }
}

From source file:org.sonatype.security.ldap.realms.DefaultLdapContextFactory.java

@VisibleForTesting
Hashtable<String, String> getSetupEnvironment(String username, final String password,
        final boolean systemContext) {
    Preconditions.checkNotNull(url, "No ldap URL specified (ldap://<hostname>:<port>)");

    if (username != null && principalSuffix != null) {
        username += principalSuffix;/*  w  w  w.  j  av a 2  s  . co  m*/
    }

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

    if (additionalEnvironment != null) {
        env.putAll(additionalEnvironment);
    }

    // if the Authentication scheme is none, and this is not the system ctx we need to set the scheme to 'simple'
    if ("none".equals(authentication) && !systemContext) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, authentication);
    }

    if (username != null) {
        env.put(Context.SECURITY_PRINCIPAL, username);
    }
    if (password != null) {
        env.put(Context.SECURITY_CREDENTIALS, password);
    }
    env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactoryClassName);
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.REFERRAL, referral);

    // Only pool connections for system contexts
    if (usePooling && username != null && systemContext) {
        // Enable connection pooling
        env.put(SUN_CONNECTION_POOLING_PROPERTY, "true");
        // Enable pooling for plain and ssl connections
        env.put(SUN_CONNECTION_POOLING_PROTOCOL_PROPERTY, "plain ssl");
    }

    if (log.isDebugEnabled()) {
        log.debug("Initializing LDAP context using URL [" + url + "] and username [" + systemUsername + "] "
                + "with pooling [" + (usePooling ? "enabled" : "disabled") + "]");
    }
    return env;
}

From source file:org.apache.synapse.transport.jms.JMSUtils.java

/**
 * Set JNDI properties and any other connection factory parameters to the connection factory
 * passed in, looing at the parameter in axis2.xml
 * @param param the axis parameter that holds the connection factory settings
 * @param jmsConFactory the JMS connection factory to which the parameters should be applied
 *///  w w w . j a v a  2  s.  co  m
public static void setConnectionFactoryParameters(Parameter param, JMSConnectionFactory jmsConFactory) {

    ParameterIncludeImpl pi = new ParameterIncludeImpl();
    try {
        pi.deserializeParameters((OMElement) param.getValue());
    } catch (AxisFault axisFault) {
        log.error("Error reading parameters for JMS connection factory" + jmsConFactory.getName(), axisFault);
    }

    Iterator params = pi.getParameters().iterator();
    while (params.hasNext()) {

        Parameter p = (Parameter) params.next();

        if (JMSConstants.CONFAC_TYPE.equals(p.getName())) {
            String connectionFactoryType = (String) p.getValue();
            jmsConFactory.setConnectionFactoryType(connectionFactoryType);

        } else if (JMSConstants.RECONNECT_TIMEOUT.equals(p.getName())) {
            String strTimeout = (String) p.getValue();
            int reconnectTimeoutSeconds = Integer.parseInt(strTimeout);
            long reconnectTimeoutMillis = reconnectTimeoutSeconds * 1000;
            jmsConFactory.setReconnectTimeout(reconnectTimeoutMillis);

        } else if (Context.INITIAL_CONTEXT_FACTORY.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.INITIAL_CONTEXT_FACTORY, (String) p.getValue());
        } else if (Context.PROVIDER_URL.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.PROVIDER_URL, (String) p.getValue());
        } else if (Context.SECURITY_PRINCIPAL.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.SECURITY_PRINCIPAL, (String) p.getValue());
        } else if (Context.SECURITY_CREDENTIALS.equals(p.getName())) {
            jmsConFactory.addJNDIContextProperty(Context.SECURITY_CREDENTIALS, (String) p.getValue());
        } else if (JMSConstants.CONFAC_JNDI_NAME_PARAM.equals(p.getName())) {
            jmsConFactory.setConnFactoryJNDIName((String) p.getValue());
            jmsConFactory.addJNDIContextProperty(JMSConstants.CONFAC_JNDI_NAME_PARAM, (String) p.getValue());
        }
    }
}