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.wso2.carbon.appfactory.s4.integration.TenantStratosSubscriptionMessagePublisher.java

/**
 * Publish message to MB/ActiveMQ Queue//from   w  ww .  jav a 2  s . com
 * @param runtimeJson runtimebeans as a json
 * @param tenantInfoJson tenantInfoBean as a json
 * @param restServiceProperties propertyMap
 * @param stage current stage
 * @throws AppFactoryEventException
 */
public void publishMessage(String runtimeJson, String tenantInfoJson, Map<String, String> restServiceProperties,
        String stage) throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnection topicConnection = null;
    TopicSession topicSession = null;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic = topicSession.createTopic(topicName);
        MapMessage mapMessage = topicSession.createMapMessage();
        mapMessage.setString(AppFactoryConstants.STAGE, stage);
        mapMessage.setString(AppFactoryConstants.RUNTIMES_INFO, runtimeJson);
        mapMessage.setString(AppFactoryConstants.TENANT_INFO, tenantInfoJson);
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.publish(mapMessage);

        //TODO remove this log
        log.info("Message with Id:" + mapMessage.getJMSMessageID() + " was successfully published to the"
                + " topic " + topicName);

        if (log.isDebugEnabled()) {
            log.debug("Message with Id:" + mapMessage.getJMSMessageID() + " was successfully published to the"
                    + " topic " + topicName);
        }
    } catch (NamingException e) {
        String msg = "Failed to initialize InitialContext";
        throw new AppFactoryEventException(msg, e);
    } catch (JMSException e) {
        String msg = "Failed to publish message due to " + e.getMessage();
        throw new AppFactoryEventException(msg, e);
    } finally {
        if (topicSession != null) {
            try {
                topicSession.close();
            } catch (JMSException e) {
                log.error("Failed to close topic session", e);
            }
        }
        if (topicConnection != null) {
            try {
                topicConnection.close();
            } catch (JMSException e) {
                log.error("Failed to close topic connection", e);
            }
        }
    }

}

From source file:org.malaguna.cmdit.service.ldap.LDAPBase.java

public Attributes loadUser(String uid, String[] attrs) {

    // Preparar las variables de entorno para la conexin JNDI
    Hashtable<String, String> entorno = new Hashtable<String, String>();

    // Credenciales del usuario para realizar la bsqueda
    String cadena = "uid=" + user + "," + context;

    entorno.put(Context.PROVIDER_URL, server);
    entorno.put(Context.INITIAL_CONTEXT_FACTORY, initContext);
    if (password != null && user != null) {
        entorno.put(Context.SECURITY_PRINCIPAL, cadena);
        entorno.put(Context.SECURITY_CREDENTIALS, password);
    }/*from   w  w  w. j a v a  2 s  . com*/

    Attributes atributos = null;

    try {
        // Crear contexto de directorio inicial
        DirContext ctx = new InitialDirContext(entorno);

        // Recuperar atributos del usuario que se est buscando
        if (attrs != null)
            atributos = ctx.getAttributes("uid=" + uid + "," + context, attrs);
        else
            atributos = ctx.getAttributes("uid=" + uid + "," + context);

        // Cerrar la conexion
        ctx.close();
    } catch (NamingException e) {
        logger.error(messages.getMessage("err.ldap.attribute", new Object[] { e }, Locale.getDefault()));
    }

    return atributos;

}

From source file:io.apiman.gateway.engine.policies.auth.LDAPIdentityValidator.java

/**
 * @see io.apiman.gateway.engine.policies.auth.IIdentityValidator#validate(java.lang.String, java.lang.String, io.apiman.gateway.engine.beans.ServiceRequest, io.apiman.gateway.engine.policy.IPolicyContext, java.lang.Object, io.apiman.gateway.engine.async.IAsyncHandler)
 *///  w  w  w.j av a  2s.  co  m
@Override
public void validate(String username, String password, ServiceRequest request, IPolicyContext context,
        LDAPIdentitySource config, IAsyncResultHandler<Boolean> handler) {
    String url = config.getUrl();
    String dn = formatDn(config.getDnPattern(), username, request);

    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); //$NON-NLS-1$
    env.put(Context.PROVIDER_URL, url);

    env.put(Context.SECURITY_AUTHENTICATION, "simple"); //$NON-NLS-1$
    env.put(Context.SECURITY_PRINCIPAL, dn);
    env.put(Context.SECURITY_CREDENTIALS, password);
    try {
        new InitialDirContext(env);
        handler.handle(AsyncResultImpl.create(Boolean.TRUE));
    } catch (AuthenticationException e) {
        handler.handle(AsyncResultImpl.create(Boolean.FALSE));
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * // w  w  w.  j  a  v  a 2  s . c o  m
 */
@ToBeExecuted
public void exec() {

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

    try {
        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.sample.jms.SampleQueueSender.java

public void sendMessages() throws NamingException, JMSException {

    PropertyConfigurator.configure("log4j.properties");
    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_NAME_PREFIX + queueName, queueName);
    InitialContext ctx = new InitialContext(properties);
    // Lookup connection factory
    QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.lookup(CF_NAME);
    queueConnection = connFactory.createQueueConnection();
    queueConnection.start();//w w w.j  a v  a  2 s.  c o m
    queueSession = queueConnection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
    Queue queue = (Queue) ctx.lookup(queueName);
    QueueSender queueSender = queueSession.createSender(queue);
    TextMessage textMessage;

    for (long i = 0; i < RECORD_COUNT; i++) {
        // create the message to send
        textMessage = queueSession.createTextMessage("Test Message Content" + messageCount);
        // Send message
        queueSender.send(textMessage);
        messageCount++;
    }
    queueSender.close();
    queueSession.close();
    queueConnection.close();
}

From source file:org.grouter.common.jndi.JNDIUtils.java

public static void createInMemoryJndiProvider(List<BindingItem> bindings) {
    if (bindings == null) {
        throw new IllegalArgumentException("Can not bind null to jndi tree.");
    }/*from   w  ww.ja  va2s  .c o  m*/
    try {
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.commons.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");

        Iterator<BindingItem> bindingItemIterator = bindings.iterator();
        while (bindingItemIterator.hasNext()) {
            BindingItem item = bindingItemIterator.next();
            InitialContext initialContext = new InitialContext();
            logger.debug("Creating component context : " + item.getJndipath()[0]);
            Context compContext = initialContext.createSubcontext(item.getJndipath()[0]);
            logger.debug("Creating environment context : " + item.getJndipath()[1]);
            Context envContext = compContext.createSubcontext(item.getJndipath()[1]);
            logger.debug("Bidning : " + item.getJndiName() + " to implementation : " + item.getImplemenation());
            envContext.bind(item.getJndiName(), item.getImplemenation());
            printJNDI(envContext, logger);
            //logger.debug(envContext.listBindings(initialContext.getNameInNamespace()));
        }

    } catch (NamingException e) {
        logger.error(e, e);
    }

}

From source file:org.wso2.carbon.appfactory.resource.mgt.listeners.TenantCreationDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException/*w w w  . ja va2s  .co  m*/
 */
public void subscribe() throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnectionFactory connFactory;
    TopicConnection topicConnection;
    TopicSession topicSession;
    TopicSubscriber topicSubscriber;
    InitialContext ctx;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(
                new TenantCreationMessageListener(topicConnection, topicSession, topicSubscriber));
        topicConnection.start();
        if (log.isDebugEnabled()) {
            log.debug("Durable Subscriber created for topic " + topicName + " with subscription id : "
                    + subscriptionId);
        }
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    } catch (JMSException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    }
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void createConnection(Properties config) {
    try {/* ww  w.j a va 2s  .c o m*/
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, config.getProperty("initialContextFactory"));
        props.put(Context.PROVIDER_URL, config.getProperty("providerUrl"));
        props.put(Context.SECURITY_PRINCIPAL, config.getProperty("securityPrincipal"));
        props.put(Context.SECURITY_CREDENTIALS, config.getProperty("securityCredentials"));
        props.put("topic.cacheInvalidateTopic", config.getProperty("cacheInvalidateTopic"));
        InitialContext jndi = new InitialContext(props);
        ConnectionFactory connectionFactory = (ConnectionFactory) jndi.lookup("ConnectionFactory");
        destination = (Destination) jndi.lookup("cacheInvalidateTopic");

        connection = connectionFactory.createConnection(config.getProperty("securityPrincipal"),
                config.getProperty("securityCredentials"));
        connection.start();
    } catch (NamingException | JMSException e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

From source file:org.wso2.carbon.appfactory.eventing.jms.Subscriber.java

public void subscribe() throws AppFactoryEventException {

    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, ANDES_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    properties.put("topic", topicName);

    try {//w w w .  j  a v a 2s.c om
        ctx = new InitialContext(properties);
        // Lookup connection factory
        connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        TopicSession topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        // create durable subscriber with subscription ID
        Topic topic = null;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(messageListener);
        topicConnection.start();
    } catch (NamingException e) {
        String errorMsg = "Failed to subscribe to topic:" + topicName + " due to " + e.getMessage();
        throw new AppFactoryEventException(errorMsg, e);
    } catch (JMSException e) {
        String errorMsg = "Failed to subscribe to topic:" + topicName + " due to " + e.getMessage();
        throw new AppFactoryEventException(errorMsg, e);
    }

}

From source file:org.wso2.carbon.appfactory.stratos.listeners.StratosSubscriptionDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException// w  w  w . jav  a2  s.c o m
 */
public void subscribe() throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, true);
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnectionFactory connFactory;
    TopicConnection topicConnection;
    TopicSession topicSession;
    TopicSubscriber topicSubscriber;
    InitialContext ctx;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(
                new StratosSubscriptionMessageListener(topicConnection, topicSession, topicSubscriber));
        topicConnection.start();
        if (log.isDebugEnabled()) {
            log.debug("Durable Subscriber created for topic " + topicName + " with subscription id : "
                    + subscriptionId);
        }
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    } catch (JMSException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    }
}