Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext(Hashtable<?, ?> environment) throws NamingException 

Source Link

Document

Constructs an initial context using the supplied environment.

Usage

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

protected EcmEngineManagementBusinessInterface createManagementService() throws Throwable {
    this.log.debug("[" + getClass().getSimpleName() + "::createManagementService] BEGIN ");
    Properties properties = new Properties();

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

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

        this.log.debug("[" + getClass().getSimpleName() + "::createManagementService] context factory vale : "
                + rb.getString(ECMENGINE_CONTEXT_FACTORY));
        properties.put(Context.INITIAL_CONTEXT_FACTORY, rb.getString(ECMENGINE_CONTEXT_FACTORY));
        this.log.debug("[" + getClass().getSimpleName() + "::createManagementService] 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() + "::createManagementService] clusterPartition vale : "
                + clusterPartition);
        if (clusterPartition != null && clusterPartition.length() > 0) {
            properties.put("jnp.partitionName", clusterPartition);
            this.log.debug(
                    "[" + getClass().getSimpleName() + "::createManagementService] 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() + "::createManagementService] context istanziato");

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

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

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

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

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizConn() throws Exception {

    Hashtable<String, String> vars = new Hashtable<String, String>();
    Context ctx;/*from w ww . ja  va  2s . c o m*/
    Object obj;

    if (!isEmpty(_ctxFac)) {
        vars.put(Context.INITIAL_CONTEXT_FACTORY, _ctxFac);
    }

    if (!isEmpty(_url)) {
        vars.put(Context.PROVIDER_URL, _url);
    }

    if (!isEmpty(_JNDIPwd)) {
        vars.put("jndi.password", _JNDIPwd);
    }

    if (!isEmpty(_JNDIUser)) {
        vars.put("jndi.user", _JNDIUser);
    }

    ctx = new InitialContext(vars);
    obj = ctx.lookup(_connFac);

    if (obj instanceof QueueConnectionFactory) {
        inizQueue(ctx, obj);
    } else if (obj instanceof TopicConnectionFactory) {
        inizTopic(ctx, obj);
    } else if (obj instanceof ConnectionFactory) {
        inizFac(ctx, obj);
    } else {
        throw new Exception("JmsIO: unsupported JMS Connection Factory");
    }

    if (_conn != null) {
        _conn.start();
    }
}

From source file:com.att.ajsc.csilogging.common.QueueConnector.java

@PostConstruct
public void init() {

    if (csiEnable && StringUtils.isNotEmpty(initialContextFactoryName)
            && StringUtils.isNotEmpty(connectionFactoryName) && StringUtils.isNotEmpty(providerURL)) {

        if (StringUtils.isNotEmpty(System.getenv(("com_att_aft_config_file")))) {
            System.setProperty("com.att.aft.config.file", System.getenv("com_att_aft_config_file"));
        }//  w  w w .j a  v a2  s.c o m

        if (StringUtils.isEmpty(System.getProperty("com.att.aft.config.file"))) {
            logger.error("Environment or System properties dont have the property com.att.aft.config.file");
            return;
        }

        QueueConnectionFactory queueConnectionFactory;
        InitialContext jndi = null;
        ConnectionFactory connectionFactory = null;
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName);
            env.put(Context.PROVIDER_URL, providerURL);
            jndi = new InitialContext(env);
            connectionFactory = (ConnectionFactory) jndi.lookup(connectionFactoryName);
            queueConnectionFactory = (QueueConnectionFactory) connectionFactory;
            if (StringUtils.isNotEmpty(auditDestinationName)) {
                auditQueueConnection = queueConnectionFactory.createQueueConnection();
                auditQueueSession = auditQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue auditQueue = (Queue) auditQueueSession.createQueue(auditDestinationName);
                auditQueueSender = auditQueueSession.createSender(auditQueue);
                auditQueueConnection.start();
                logger.info("*************CONNECTED :" + auditDestinationName + "*************");

            }

            if (StringUtils.isNotEmpty(perfDestinationName)) {
                pefQueueConnection = queueConnectionFactory.createQueueConnection();
                pefQueueSession = pefQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue perfQueue = (Queue) pefQueueSession.createQueue(perfDestinationName);
                pefQueueSender = pefQueueSession.createSender(perfQueue);
                pefQueueConnection.start();
                logger.info("*************CONNECTED :" + perfDestinationName + "*************");
            }

        } catch (Exception e) {
            logger.error("Error while connecting to the Queue" + e);
        }
    }

}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void doUnbind(String[] vals) throws NamingException {
    String url = "rmi://localhost:" + vals[1];
    String serviceName = vals[0];
    System.out.println("Unbinding " + url + "/" + serviceName);
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
    env.put(Context.PROVIDER_URL, url);

    Context ictx = new InitialContext(env);
    try {/*from   w ww.  ja va2 s  .  com*/
        ictx.unbind(serviceName);
        System.out.println("Done");
    } catch (Exception ex) {
        System.err.println(ex.getMessage() + ex.getCause().getMessage());
    }
}

From source file:com.mirth.connect.connectors.jms.JmsClient.java

private ConnectionFactory lookupConnectionFactoryWithJndi() throws Exception {
    String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();

    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    try {/*from  w w  w . ja  va2 s  . co m*/
        MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
        Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.PROVIDER_URL,
                replacer.replaceValues(connectorProperties.getJndiProviderUrl(), channelId, channelName));
        env.put(Context.INITIAL_CONTEXT_FACTORY, replacer
                .replaceValues(connectorProperties.getJndiInitialContextFactory(), channelId, channelName));
        env.put(Context.SECURITY_PRINCIPAL,
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName));
        env.put(Context.SECURITY_CREDENTIALS,
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));

        initialContext = new InitialContext(env);
        String connectionFactoryName = replacer
                .replaceValues(connectorProperties.getJndiConnectionFactoryName(), channelId, channelName);
        return (ConnectionFactory) initialContext.lookup(connectionFactoryName);
    } finally {
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.sterlingcommerce.xpedx.webchannel.services.XPEDXGetAllReportsAction.java

public void getConnection() throws SQLException {
    String XCOM_MST_CUST = getCustomerNo(getWCContext().getBuyerOrgCode());
    String DBUrl = YFSSystem.getProperty("datasource_url");
    String DBName = YFSSystem.getProperty("datasource_name");

    //String DBUrl= "t3://localhost:7002";
    //String DBName= "SeptJNDI";
    Connection connection = null;
    Statement stmt = null;/*  ww  w  . j av  a  2s  . com*/
    ResultSet rs = null;
    XPEDXReportBean rpBean = null;
    try {
        Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        ht.put("java.naming.provider.url", DBUrl);
        Context env = new InitialContext(ht);

        //InitialContext context = new InitialContext(ht);
        DataSource dataSource = (DataSource) env.lookup(DBName);
        connection = dataSource.getConnection();
        if (log.isDebugEnabled()) {
            log.debug("Connection successful..");
        }
        //String schemaName=YFSSystem.getProperty("schemaname");
        //String Query="select distinct RPT_CUID, RPT_NAME,RPT_ID,RPT_KIND, RPT_DESC from " + schemaName + ".xpedx_custom_rpt_dtl where XCOM_MST_CUST=" + "'"+ XCOM_MST_CUST +"'"+"AND CUST_ROLE in (";
        String Query = "select distinct RPT_CUID, RPT_NAME,RPT_ID,RPT_KIND, RPT_DESC from DH.xpedx_custom_rpt_dtl where XCOM_MST_CUST="
                + "'" + XCOM_MST_CUST + "'" + "AND CUST_ROLE in (";
        Query = getUserRole(Query);
        stmt = connection.createStatement();
        boolean test = stmt.execute(Query);
        dataExchangeReportList = new ArrayList<Report>();
        if (test == true) {
            rs = stmt.getResultSet();
            while (rs.next()) {
                Report report = new Report();
                report.setCuid(rs.getString("RPT_CUID"));
                report.setName(rs.getString("RPT_NAME"));
                report.setKind(rs.getString("RPT_KIND"));
                report.setId(rs.getInt("RPT_ID"));
                report.setDescription(rs.getString("RPT_DESC"));

                dataExchangeReportList.add(report);
            }
        }
    } catch (Exception e) {
        LOG.debug("Not able to connect to DEV Datasource:->" + e.getMessage());
    } finally {
        stmt.close();
        connection.close();
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.attribute.resolver.dataConnector.RDBMSDataConnectorBeanDefinitionParser.java

/**
 * Builds a JDBC {@link javax.sql.DataSource} from a ContainerManagedConnection configuration element.
 * //from   w w  w. ja va 2  s .  c o m
 * @param pluginId ID of this data connector
 * @param cmc the container managed configuration element
 * 
 * @return the built data source
 */
protected DataSource buildContainerManagedConnection(String pluginId, Element cmc) {
    String jndiResource = cmc.getAttributeNS(null, "resourceName");
    jndiResource = DatatypeHelper.safeTrim(jndiResource);

    Hashtable<String, String> initCtxProps = buildProperties(XMLHelper.getChildElementsByTagNameNS(cmc,
            DataConnectorNamespaceHandler.NAMESPACE, "JNDIConnectionProperty"));
    try {
        InitialContext initCtx = new InitialContext(initCtxProps);
        DataSource dataSource = (DataSource) initCtx.lookup(jndiResource);
        if (dataSource == null) {
            log.error("DataSource " + jndiResource + " did not exist in JNDI directory");
            throw new BeanCreationException("DataSource " + jndiResource + " did not exist in JNDI directory");
        }
        if (log.isDebugEnabled()) {
            log.debug("Retrieved data source for data connector {} from JNDI location {} using properties ",
                    pluginId, initCtxProps);
        }
        return dataSource;
    } catch (NamingException e) {
        log.error("Unable to retrieve data source for data connector " + pluginId + " from JNDI location "
                + jndiResource + " using properties " + initCtxProps, e);
        return null;
    }
}

From source file:eu.learnpad.simulator.mon.probe.GlimpseAbstractProbe.java

/**
 * This method setup the connection parameters using the {@link Properties} object {@link #settings}
 * /*from   w w w  .j a v a  2 s.c om*/
 * @param settings the parameter to setup the connection to the Enterprise Service Bus<br /> to send messages
 * @param debug
 * @return it provides an {@link InitialContext} object that will be used<br />during the Consumer <-> Monitoring interaction.
 * @throws NamingException
 */
protected InitialContext initConnection(Properties settings, boolean debug) throws NamingException {
    if (debug)
        DebugMessages.print(TimeStamp.getCurrentTime(), this.getClass().getSimpleName(),
                "Creating InitialContext with settings ");
    InitialContext initConn = new InitialContext(settings);
    if (debug) {
        DebugMessages.ok();
        DebugMessages.line();
    }
    return initConn;
}

From source file:com.clican.pluto.common.util.JndiUtils.java

/**
 * Look up the object with the specified JNDI name in the JNDI server.
 * /*from w  ww. j a v a 2 s  . c o  m*/
 * @param jndiName
 *            the JNDI name specified
 * @return the object bound with the name specified, null if this method
 *         fails
 */
public static Object lookupObject(String jndiName) {
    Context ctx = null;
    try {
        Hashtable<String, String> ht = new Hashtable<String, String>();
        // If a special JNDI initial context factory was specified in the
        // constructor, then use it.
        if (jndiInitialContextFactory != null) {
            ht.put(Context.INITIAL_CONTEXT_FACTORY, jndiInitialContextFactory);
        }
        ctx = new InitialContext(ht);
        Object obj = null;
        try {
            obj = ctx.lookup(jndiName);
        } catch (Exception e) {
            if (log.isInfoEnabled()) {
                log.info(
                        "Lookup for an object from Non-Serializable JNDI (relookup from Serializable JNDI) using the JNDI name ["
                                + jndiName + "] : ");
            }
            obj = NonSerializableFactory.lookup(jndiName);
        }

        if (log.isDebugEnabled()) {
            log.debug("JNDI lookup with path [" + jndiName + "] returned object [" + obj + "].");
        }
        return obj;
    } catch (NamingException ex) {
        log.debug("Failed to lookup for an object using the JNDI name [" + jndiName + "] : " + ex);
        return null;
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException ne) {
                log.error("Close context error:", ne);
            }
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.JMSStream.java

@Override
protected void initialize() throws Exception {
    super.initialize();

    if (StringUtils.isEmpty(serverURL)) {
        throw new IllegalStateException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "TNTInputStream.property.undefined", StreamProperties.PROP_SERVER_URI));
    }//  w w  w  .j  a v a 2s.com

    if (StringUtils.isEmpty(queueName) && StringUtils.isEmpty(topicName)) {
        throw new IllegalStateException(StreamsResources.getStringFormatted(
                StreamsResources.RESOURCE_BUNDLE_NAME, "TNTInputStream.property.undefined.one.of",
                StreamProperties.PROP_QUEUE_NAME, StreamProperties.PROP_TOPIC_NAME));
    }

    jmsDataReceiver = new JMSDataReceiver();
    Hashtable<String, String> env = new Hashtable<>(2);
    env.put(Context.INITIAL_CONTEXT_FACTORY, jndiFactory);
    env.put(Context.PROVIDER_URL, serverURL);

    Context ic = new InitialContext(env);

    jmsDataReceiver.initialize(ic, StringUtils.isEmpty(queueName) ? topicName : queueName, jmsConnFactory);
}