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.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Return the service name using the JMS destination and its JNDI name
 *
 * @param dest the JMS Destination Queue or Topic
 * @param jmsDestinationName the JMS destination name
 * @return the name of the service using the destination
 *//* w  ww  .  j  a v  a2 s  .c  o  m*/
public String getServiceNameForDestination(Destination dest, String jmsDestinationName) {
    String serviceName = (String) serviceDestinationNameMapping.get(jmsDestinationName);

    // hack to get around the crazy Active MQ dynamic queue and topic issues
    if (serviceName == null) {
        String provider = (String) getJndiProperties().get(Context.INITIAL_CONTEXT_FACTORY);
        if (provider.indexOf("activemq") != -1) {
            serviceName = getServiceNameForJNDIName((dest instanceof Queue ? JMSConstants.ACTIVEMQ_DYNAMIC_QUEUE
                    : JMSConstants.ACTIVEMQ_DYNAMIC_TOPIC) + jmsDestinationName);
        }
    }
    return serviceName;
}

From source file:org.apache.syncope.fit.AbstractITCase.java

@SuppressWarnings({ "unchecked", "rawtypes", "UseOfObsoleteCollectionType" })
protected InitialDirContext getLdapResourceDirContext(final String bindDn, final String bindPwd)
        throws NamingException {
    ResourceTO ldapRes = resourceService.read(RESOURCE_NAME_LDAP);
    ConnInstanceTO ldapConn = connectorService.read(ldapRes.getConnector(), Locale.ENGLISH.getLanguage());

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://" + ldapConn.getConf("host").get().getValues().get(0) + ":"
            + ldapConn.getConf("port").get().getValues().get(0) + "/");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL,
            bindDn == null ? ldapConn.getConf("principal").get().getValues().get(0) : bindDn);
    env.put(Context.SECURITY_CREDENTIALS,
            bindPwd == null ? ldapConn.getConf("credentials").get().getValues().get(0) : bindPwd);

    return new InitialDirContext(env);
}

From source file:org.wso2.carbon.andes.core.QueueManagerServiceImpl.java

/**
 * Publish message to given JMS queue//from w  w w.  ja va  2 s. com
 *
 * @param nameOfQueue queue name
 * @param userName username
 * @param accessKey access key
 * @param jmsType jms type
 * @param jmsCorrelationID message correlation id
 * @param numberOfMessages number of messages to publish
 * @param message message body
 * @param deliveryMode delivery mode
 * @param priority message priority
 * @param expireTime message expire time
 * @throws QueueManagerException
 */
private void send(String nameOfQueue, String userName, String accessKey, String jmsType,
        String jmsCorrelationID, int numberOfMessages, String message, int deliveryMode, int priority,
        long expireTime) throws QueueManagerException {
    QueueConnectionFactory connFactory;
    QueueConnection queueConnection = null;
    QueueSession queueSession = null;
    QueueSender queueSender = null;
    try {
        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
        properties.put(CF_NAME_PREFIX + CF_NAME, Utils.getTCPConnectionURL(userName, accessKey));
        properties.put(QUEUE_NAME_PREFIX + nameOfQueue, nameOfQueue);
        properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
        InitialContext ctx = new InitialContext(properties);
        connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        Queue queue = (Queue) ctx.lookup(nameOfQueue);
        queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queueSender = queueSession.createSender(queue);
        queueConnection.start();
        TextMessage textMessage = queueSession.createTextMessage();
        if (queueSender != null && textMessage != null) {
            if (jmsType != null) {
                textMessage.setJMSType(jmsType);
            }
            if (jmsCorrelationID != null) {
                textMessage.setJMSCorrelationID(jmsCorrelationID);
            }

            if (message != null) {
                textMessage.setText(message);
            } else {
                textMessage.setText("Type message here..");
            }

            for (int i = 0; i < numberOfMessages; i++) {
                queueSender.send(textMessage, deliveryMode, priority, expireTime);
            }
        }
    } catch (FileNotFoundException | NamingException | UnknownHostException | XMLStreamException
            | JMSException e) {
        throw new QueueManagerException("Unable to send message.", e);
    } finally {
        try {
            if (queueConnection != null) {
                queueConnection.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue connection", e);
        }
        try {
            if (queueSession != null) {
                queueSession.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue session", e);
        }
        try {
            if (queueSender != null) {
                queueSender.close();
            }
        } catch (JMSException e) {
            log.error("Unable to close queue sender", e);
        }
    }
}

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

/**
 * return the user dn of an ldap entry//from   ww  w . j a v  a  2  s.c om
 * 
 * search: base, filter, attrs, user, pass
 * @return
 */
protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter,
        String[] attributes) {
    SearchResult ret = null;
    Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11);
    bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    bindEnv.put(Context.PROVIDER_URL, getLdapUrl());

    // remove null attributes
    List<String> goodAttributes = new ArrayList<String>();
    for (String s : attributes) {
        if (s != null) {
            goodAttributes.add(s);
        }
    }

    // get the DN 
    DirContext authenticationContext;
    try {
        SearchControls ctls = new SearchControls();
        ctls.setCountLimit(1);
        ctls.setReturningObjFlag(true);
        ctls.setReturningAttributes(goodAttributes.toArray(new String[0]));
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Authenticate as  User and password  
        if (bindUser != null && bindPass != null) {
            log.debug("NBinding with credential as user: " + bindUser);
            bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
            bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser);
            bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass);
        }
        authenticationContext = new InitialDirContext(bindEnv);
        // %u, %d in baseDN are still expanded 
        NamingEnumeration<SearchResult> answer;
        try {
            answer = authenticationContext.search(base, filter, ctls);

            if (answer.hasMore()) {
                ret = (SearchResult) answer.next();
            }
        } catch (NamingException e) {
            log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage());
        }
        authenticationContext.close();
        return ret;

    } catch (NamingException e) {
        log.error("Error while creating context: " + e.getMessage());
        if (e.getCause() != null) {
            log.error("Error is: " + e.getCause().getMessage());
        }
        return null;
    }
}

From source file:com.adito.activedirectory.ActiveDirectoryUserDatabaseConfiguration.java

public InitialLdapContext getInitialContext(String url, Map<String, String> properties) throws NamingException {
    Hashtable<String, String> variables = new Hashtable<String, String>(properties);
    variables.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    variables.put(Context.PROVIDER_URL, url); // Must use fully qualified hostname

    if (isSslProtcolType()) {
        variables.put("java.naming.ldap.factory.socket", "com.adito.boot.CustomSSLSocketFactory");
        // Add the custom socket factory
    }/*  ww w  .  j  a  v a2s . c  om*/

    if (isFollowReferrals()) {
        variables.put(Context.REFERRAL, "follow");
    }

    variables.put("com.sun.jndi.ldap.connect.timeout", String.valueOf(getTimeout()));
    variables.put("java.naming.ldap.version", "3");
    variables.put("com.sun.jndi.ldap.connect.pool", "true");
    variables.put("javax.security.sasl.qop", "auth-conf,auth-int,auth");
    variables.put(Context.SECURITY_PROTOCOL, getProtocolType());

    InitialLdapContext context = new InitialLdapContext(variables, null);
    String usedUrl = (String) context.getEnvironment().get(Context.PROVIDER_URL);
    setLastContactedActiveDirectoryUrl(usedUrl);
    return context;
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testAddConnection_BindsToJndiWhenStarted() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());/*  w w  w .  jav  a  2 s  .  c om*/
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        start(adapter);
        stop(adapter);
        adapter.getSharedComponents().addConnection(new NullConnection(getName()));
        start(adapter);
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertNotNull(lookedup);
        assertEquals(getName(), lookedup.getUniqueId());
    } finally {
        stop(adapter);
    }
}

From source file:com.adaptris.core.SharedComponentListTest.java

public void testClose_UnbindsFromJNDI() throws Exception {
    Adapter adapter = new Adapter();
    adapter.setUniqueId(getName());//from   w  w  w .  j av a  2 s . c  om
    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JndiContextFactory.class.getName());
    InitialContext initialContext = new InitialContext(env);

    try {
        adapter.getSharedComponents().addConnection(new NullConnection(getName()));
        adapter.getSharedComponents().addConnection(new NullConnection(getName() + "_2"));
        start(adapter);
        NullConnection lookedup = (NullConnection) initialContext.lookup("adapter:comp/env/" + getName());
        assertEquals(getName(), lookedup.getUniqueId());
        stop(adapter);
        try {
            initialContext.lookup("adapter:comp/env/" + getName());
            fail();
        } catch (NamingException expected) {

        }
        // Now a start request should rebind to JNDI.
        start(adapter);
        initialContext.lookup("adapter:comp/env/" + getName());
        initialContext.lookup("adapter:comp/env/" + getName() + "_2");
    } finally {
        stop(adapter);
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.JNDIConnectionWrapper.java

private void doConnect(final StudioProgressMonitor monitor) throws NamingException {
    context = null;//from  w  ww  . j  av  a  2s .  c  o m
    isConnected = true;

    // setup connection parameters
    String host = connection.getConnectionParameter().getHost();
    int port = connection.getConnectionParameter().getPort();
    long timeout = connection.getConnectionParameter().getTimeout();

    useLdaps = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.LDAPS;
    useStartTLS = connection.getConnectionParameter()
            .getEncryptionMethod() == ConnectionParameter.EncryptionMethod.START_TLS;

    environment = new Hashtable<>();
    Preferences preferences = ConnectionCorePlugin.getDefault().getPluginPreferences();
    final boolean validateCertificates = preferences
            .getBoolean(ConnectionCoreConstants.PREFERENCE_VALIDATE_CERTIFICATES);
    String ldapCtxFactory = preferences.getString(ConnectionCoreConstants.PREFERENCE_LDAP_CONTEXT_FACTORY);
    environment.put(Context.INITIAL_CONTEXT_FACTORY, ldapCtxFactory);
    environment.put(JAVA_NAMING_LDAP_VERSION, "3"); //$NON-NLS-1$

    // timeouts
    /*
     *  Don't use a timeout when using ldaps: JNDI throws a SocketException  when setting a timeout on SSL connections.
     *  See https://bugs.openjdk.java.net/browse/JDK-8173451
     */
    if (!useLdaps) {
        if (timeout < 0) {
            timeout = 0;
        }
        environment.put(COM_SUN_JNDI_LDAP_CONNECT_TIMEOUT, Long.toString(timeout)); //$NON-NLS-1$
    }

    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_INITIAL, "2000"); //$NON-NLS-1$
    environment.put(COM_SUN_JNDI_DNS_TIMEOUT_RETRIES, "3"); //$NON-NLS-1$

    // ldaps://
    if (useLdaps) {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAPS_SCHEME + host + ':' + port);
        environment.put(Context.SECURITY_PROTOCOL, "ssl"); //$NON-NLS-1$
        // host name verification is done in StudioTrustManager
        environment.put(JAVA_NAMING_LDAP_FACTORY_SOCKET,
                validateCertificates ? StudioSSLSocketFactory.class.getName()
                        : DummySSLSocketFactory.class.getName());
    } else {
        environment.put(Context.PROVIDER_URL, LdapUrl.LDAP_SCHEME + host + ':' + port);
    }

    if (binaryAttributes != null) {
        setBinaryAttributes(binaryAttributes);
    }

    InnerRunnable runnable = new InnerRunnable() {
        public void run() {
            try {
                context = new InitialLdapContext(environment, null);

                if (useStartTLS) {
                    try {
                        StartTlsResponse tls = (StartTlsResponse) context
                                .extendedOperation(new StartTlsRequest());
                        // deactivate host name verification at this level,
                        // host name verification is done in StudioTrustManager
                        tls.setHostnameVerifier((hostname, session) -> true);

                        if (validateCertificates) {
                            tls.negotiate(StudioSSLSocketFactory.getDefault());
                        } else {
                            tls.negotiate(DummySSLSocketFactory.getDefault());
                        }
                    } catch (Exception e) {
                        namingException = new NamingException(e.getMessage() != null ? e.getMessage()
                                : "Error while establishing TLS session"); //$NON-NLS-1$
                        namingException.setRootCause(e);
                        context.close();
                    }
                }
            } catch (NamingException ne) {
                namingException = ne;
            }
        }
    };

    runAndMonitor(runnable, monitor);

    if (runnable.getException() != null) {
        throw runnable.getException();
    } else if (context != null) {
        // all OK
    } else {
        throw new NamingException("???"); //$NON-NLS-1$
    }
}

From source file:com.emc.ecs.smart.SmartUploader.java

/**
 * Use JNDI to bind to DNS and resolve ALL the 'A' records for a host.
 * @param hostname host to resolve//from  w  w  w . j  a v  a2s. c om
 * @return the list of IP addresses for the host.
 */
public List<String> getIPAddresses(String hostname) throws NamingException {
    InitialDirContext idc;

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
    idc = new InitialDirContext(env);

    List<String> ipAddresses = new ArrayList<String>();
    Attributes attrs = idc.getAttributes(hostname, ADDR_ATTRIBS);
    Attribute attr = attrs.get(ADDR_ATTRIB);

    if (attr != null) {
        for (int i = 0; i < attr.size(); i++) {
            ipAddresses.add((String) attr.get(i));
        }
    }

    return ipAddresses;
}