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.vnet.demo.service.azure.servicebus.AzureServiceBusServiceFactory.java

public AzureServiceBusService create() {
    if (this.azureServiceBusService == null) {
        try {/* www .j a v  a 2  s.  c o  m*/
            PropertiesFactoryBean properties = SpringUtil.getBean(PropertiesFactoryBean.class);
            this.username = (String) properties.getObject().get("azure.servicebus.username");
            this.password = (String) properties.getObject().get("azure.servicebus.password");
            this.host = (String) properties.getObject().get("azure.servicebus.host");
            String defaultQueue = (String) properties.getObject().get("azure.servicebus.queue");

            String connectionString = "amqps://" + username + ":" + encode(password) + "@" + host;
            Hashtable<String, String> env = new Hashtable<String, String>();
            env.put(Context.INITIAL_CONTEXT_FACTORY,
                    "org.apache.qpid.amqp_1_0.jms.jndi.PropertiesFileInitialContextFactory");
            env.put("connectionfactory.ServiceBusConnectionFactory", connectionString);

            Context context = new InitialContext(env);
            ConnectionFactory connectionFactory = (ConnectionFactory) context
                    .lookup("ServiceBusConnectionFactory");
            azureServiceBusService = new AzureServiceBusService(connectionFactory, defaultQueue);
        } catch (NamingException | IOException e) {
            e.printStackTrace();
        }
        ;
    }
    return this.azureServiceBusService;
}

From source file:org.apache.servicemix.jms.AbstractJmsTestSupport.java

protected void createInitContext() throws Exception {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, ActiveMQInitialContextFactory.class.getName());
    System.setProperty(Context.PROVIDER_URL, "vm://localhost");
}

From source file:org.pepstock.jem.junit.test.springbatch.java.RestRunnableAndContext.java

@Override
public void run() {
    try {/*from w  w  w.j a v  a 2 s .  com*/

        if (stepContribution == null || chunkContext == null) {
            throw new RuntimeException("StepContribution or ChuckContext is null");
        }

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.pepstock.jem.node.tasks.jndi.JemContextFactory");

        InitialContext context = new InitialContext(env);
        RestClient rest = (RestClient) context.lookup("JUNIT-REST-RESOURCE");
        System.err.println();
        System.err.println("*** REST XML");
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
        get(rest, MediaType.APPLICATION_XML);
        get(rest, MediaType.APPLICATION_JSON);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    try {
        System.err.println();
        System.err.println("*** REST XML");
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
        get(restC, MediaType.APPLICATION_XML);
        get(restC, MediaType.APPLICATION_JSON);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.wso2.mb.integration.common.clients.operations.queue.QueueMessageBrowser.java

public QueueMessageBrowser(String host, String port, String userName, String password, String destination,
        int printNumberOfMessagesPer, boolean isToPrintMessage) {
    this.hostName = host;
    this.port = port;
    this.queueName = destination;
    this.printNumberOfMessagesPer = printNumberOfMessagesPer;
    this.isToPrintEachMessage = isToPrintMessage;

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, getTCPConnectionURL(userName, password));
    properties.put("queue." + queueName, queueName);

    log.info("getTCPConnectionURL(userName,password) = " + getTCPConnectionURL(userName, password));

    try {//from   w ww .  j av  a2s  .c  o  m
        InitialContext ctx = new InitialContext(properties);
        // Lookup connection factory
        QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
        queueConnection = connFactory.createQueueConnection();
        queueConnection.start();
        queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
        Queue queue = (Queue) ctx.lookup(queueName);
        queueBrowser = queueSession.createBrowser(queue);

    } catch (NamingException e) {
        log.error("Error while looking up for queue", e);
    } catch (JMSException e) {
        log.error("Error while initializing queue connection", e);
    }

}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPConnectionContext.java

@SuppressWarnings({ "rawtypes", "unchecked" })
LDAPConnectionContext(Map<String, String> userStoreProperties) throws UserStoreException {

    String connectionURL = userStoreProperties.get(LDAPConstants.CONNECTION_URL);
    String connectionName = userStoreProperties.get(LDAPConstants.CONNECTION_NAME);
    String connectionPassword = userStoreProperties.get(LDAPConstants.CONNECTION_PASSWORD);

    if (log.isDebugEnabled()) {
        log.debug("Connection Name :: " + connectionName + ", Connection URL :: " + connectionURL);
    }//w w  w  . j  ava2 s  .  c  o m

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

    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 = userStoreProperties.get(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 (userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL) != null) {
        environment.put("java.naming.referral", userStoreProperties.get(LDAPConstants.PROPERTY_REFERRAL));
    }
    //Set connect timeout if provided in configuration. Otherwise set default value
    String connectTimeout = userStoreProperties.get(CONNECTION_TIME_OUT);
    String readTimeout = userStoreProperties.get(READ_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");
    }

    if (StringUtils.isNotEmpty(readTimeout)) {
        environment.put("com.sun.jndi.ldap.read.timeout", readTimeout);
    }
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.CEPServerClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.CEP);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.CEP_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        InitialContext ctx;//from  w  w w  . j  a va2 s. c  om
        try {
            ctx = new InitialContext(properties);

            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_CEP + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();
            if (log.isDebugEnabled()) {
                log.debug("Message in the execute() of CEPServer Client: " + message.getText());
            }
            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send or retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "JMS Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming Exception in inserting stats into the DB for the CEPServerClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.sonar.server.database.JndiDatabaseConnectorTest.java

@After
public void restore() {
    if (currentInitialContextFacto != null) {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, currentInitialContextFacto);
    }
}

From source file:org.apache.stratos.status.monitor.agent.clients.service.MessageBrokerServiceClient.java

private static void executeService() throws SQLException {
    int serviceID = MySQLConnectionInitializer.getServiceID(StatusMonitorConstants.MESSAGING);
    AuthConfigBean authConfigBean = StatusMonitorConfigurationBuilder.getAuthConfigBean();

    String userName = authConfigBean.getUserName();
    tcpUserName = userName.replace('@', '!');

    //check whether login success
    if (ServiceLoginClient.loginChecker(StatusMonitorConstants.MESSAGING_HOST, serviceID)) {

        Properties properties = new Properties();
        properties.put(Context.INITIAL_CONTEXT_FACTORY, StatusMonitorAgentConstants.QPID_ICF);
        properties.put(StatusMonitorAgentConstants.CF_NAME_PREFIX + StatusMonitorAgentConstants.CF_NAME,
                getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));

        if (log.isDebugEnabled()) {
            log.debug("getTCPConnectionURL(username,password) = "
                    + getTCPConnectionURL(tcpUserName, authConfigBean.getPassword()));
        }//from   www .  j  a  v  a 2  s  . com
        try {
            InitialContext ctx = new InitialContext(properties);
            // Lookup connection factory
            QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx
                    .lookup(StatusMonitorAgentConstants.CF_NAME);
            QueueConnection queueConnection = connFactory.createQueueConnection();
            queueConnection.start();
            QueueSession queueSession = queueConnection.createQueueSession(false,
                    QueueSession.AUTO_ACKNOWLEDGE);

            // Send message
            Queue queue = queueSession.createQueue(
                    StatusMonitorAgentConstants.QUEUE_NAME_MB + ";{create:always, node:{durable: True}}");

            // create the message to send
            TextMessage textMessage = queueSession.createTextMessage("Test Message Hello");
            javax.jms.QueueSender queueSender = queueSession.createSender(queue);
            queueSender.setTimeToLive(100000000);

            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            queueSender.send(textMessage);

            TextMessage message = (TextMessage) queueReceiver.receiveNoWait();

            if (message.getText().equals("Test Message Hello")) {
                MySQLConnector.insertStats(serviceID, true);
                MySQLConnector.insertState(serviceID, true, "");
            } else {
                MySQLConnector.insertStats(serviceID, false);
                MySQLConnector.insertState(serviceID, false, "Send and retrieve messages failed");
            }
            queueSender.close();
            queueSession.close();
            queueConnection.close();

        } catch (JMSException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Exception in executing the client - "
                    + "Status Monitor Agent for MessageBrokerServiceClient";
            log.warn(msg, e);

        } catch (NamingException e) {
            MySQLConnector.insertStats(serviceID, false);
            MySQLConnector.insertState(serviceID, false, e.getMessage());
            String msg = "Naming exception in executing the client - "
                    + "Status Monitor agent for MessageBrokerServiceClient";
            log.warn(msg, e);
        }
    }
}

From source file:org.wso2.esb.integration.common.utils.clients.jmsclient.JMSQueueMessageProducer.java

public JMSQueueMessageProducer(JMSBrokerConfiguration jmsBrokerConfiguration) throws NamingException {
    Properties properties = new Properties();
    properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, jmsBrokerConfiguration.getInitialNamingFactory());
    if (jmsBrokerConfiguration.getProviderURL().startsWith(MB_BROKER_URL_PREFIX)) {
        //setting property for Qpid running on WSO2 MB
        properties.put("connectionfactory.QueueConnectionFactory", jmsBrokerConfiguration.getProviderURL());
    } else {//from   www  . j  ava  2 s .  c om
        //setting property for ActiveMQ
        properties.setProperty(Context.PROVIDER_URL, jmsBrokerConfiguration.getProviderURL());
    }
    Context context = new InitialContext(properties);
    connectionFactory = (QueueConnectionFactory) context.lookup("QueueConnectionFactory");
}

From source file:org.wso2.carbon.andes.ui.client.QueueReceiverClient.java

/**
 * Method used to register a subscriber to a queue.
 * @param nameOfQueue name of queue//ww  w. j a  v a2  s  .  co  m
 * @param username User's username as per user store
 * @param accesskey as generated by andes authentication service for the user.
 * @return javax.jms.Queue
 * @throws NamingException
 * @throws JMSException
 * @throws FileNotFoundException
 * @throws XMLStreamException
 * @throws AndesException
 */
public Queue registerReceiver(String nameOfQueue, String username, String accesskey)
        throws NamingException, JMSException, FileNotFoundException, XMLStreamException, AndesException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, UIUtils.getTCPConnectionURL(username, accesskey));
    properties.put("queue." + nameOfQueue, nameOfQueue);
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    InitialContext ctx = new InitialContext(properties);
    // Lookup connection factory
    QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
    queueConnection = connFactory.createQueueConnection();
    queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    //Receive message
    Queue queue = (Queue) ctx.lookup(nameOfQueue);
    queueConsumer = queueSession.createConsumer(queue);
    queueConnection.start();
    return queue;

}