Java Code Examples for javax.naming.InitialContext#lookup()
The following examples show how to use
javax.naming.InitialContext#lookup() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityUtil.java From lams with GNU General Public License v2.0 | 7 votes |
/** * <p> * Performs a JNDI lookup to retrieve the configured {@code PolicyRegistration}. * </p> * * @return a reference to the configured {@code PolicyRegistration} implementation, or {@code null} if the look up * fails. */ public static PolicyRegistration getPolicyRegistration() { String lookupURL = "java:/policyRegistration"; PolicyRegistration registration = null; try { InitialContext ic = new InitialContext(); registration = (PolicyRegistration) ic.lookup(lookupURL); } catch (Exception e) { PicketBoxLogger.LOGGER.debugIgnoredException(e); } return registration; }
Example 2
Source File: EncBmpBean.java From tomee with Apache License 2.0 | 6 votes |
public void lookupFloatEntry() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final Float expected = new Float(1.0F); final Float actual = (Float) ctx.lookup("java:comp/env/entity/bmp/references/Float"); Assert.assertNotNull("The Float looked up is null", actual); Assert.assertEquals(expected, actual); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 3
Source File: EncStatefulBean.java From tomee with Apache License 2.0 | 6 votes |
public void lookupEntityBean() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final BasicBmpHome home = (BasicBmpHome) ctx.lookup("java:comp/env/stateful/beanReferences/bmp_entity"); Assert.assertNotNull("The EJBHome looked up is null", home); final BasicBmpObject object = home.createObject("Enc Bean"); Assert.assertNotNull("The EJBObject is null", object); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 4
Source File: ConnectionsRestApiTest.java From ballerina-message-broker with Apache License 2.0 | 6 votes |
/** * Creates a AMQP connection with the number of channels specified, registered on top of it. * * @param numberOfChannels number of channels to be created using the connection * @param userName admin user * @param password admin password * @param hostName localhost * @param port the AMQP port for which the broker listens to * @return the created JMS connection * @throws NamingException if an error occurs while creating the context/connection factory using given properties. * @throws JMSException if an error occurs while creating/starting the connection/session */ private Connection createConnection(int numberOfChannels, String userName, String password, String hostName, String port) throws NamingException, JMSException { InitialContext initialContext = ClientHelper.getInitialContextBuilder(userName, password, hostName, port).build(); QueueConnectionFactory connectionFactory = (QueueConnectionFactory) initialContext.lookup(ClientHelper.CONNECTION_FACTORY); QueueConnection connection = connectionFactory.createQueueConnection(); connection.start(); for (int i = 0; i < numberOfChannels; i++) { QueueSession session = connection.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE); /* For each channel, create a number of consumers that is equal to the channel number. e.g. if the channel count is 3, channel1 has 1 consumer, channel2 has 2 consumers and channel3 has 3 consumers */ for (int j = 0; j < i; j++) { Queue queue = session.createQueue("queue"); session.createReceiver(queue); } } return connection; }
Example 5
Source File: EncCmp2Bean.java From tomee with Apache License 2.0 | 6 votes |
public void lookupCharacterEntry() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final Character expected = new Character('D'); final Character actual = (Character) ctx.lookup("java:comp/env/entity/cmp/references/Character"); Assert.assertNotNull("The Character looked up is null", actual); Assert.assertEquals(expected, actual); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 6
Source File: RmiIiopCmp2Bean.java From tomee with Apache License 2.0 | 5 votes |
public ObjectGraph returnNestedHandle() { ObjectGraph data = null; try { final InitialContext ctx = new InitialContext(); final EncCmpHome home = (EncCmpHome) ctx.lookup("java:comp/env/cmp/rmi-iiop/home"); final EncCmpObject object = home.create("Test04 CmpBean"); data = new ObjectGraph(object.getHandle()); } catch (final Exception e) { throw new EJBException(e); } return data; }
Example 7
Source File: JndiNameFormatTest.java From tomee with Apache License 2.0 | 5 votes |
public void testShouldLookupDeployBeanWithCamelCaseInterfaceName() throws Exception { deploy("{ejbName}/{interfaceType.annotationName.cc}"); final Properties p = new Properties(); p.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory"); final InitialContext context = new InitialContext(p); final Echo echo = (Echo) context.lookup("EchoImpl/Remote"); assertEquals("Echoing: This is a test", echo.echo("This is a test")); assembler.destroy(); }
Example 8
Source File: JdbcTempSSOSource.java From jivejdon with Apache License 2.0 | 5 votes |
public JdbcTempSSOSource(String jndiname) { try { InitialContext ic = new InitialContext(); dataSource = (DataSource) ic.lookup(jndiname); jdbcTemp = new JdbcTemp(dataSource); } catch (NamingException e) { logger.error("NamingException" + e); } catch (Exception slx) { logger.error(slx); } }
Example 9
Source File: RMIConnector.java From jdk1.8-source-analysis with Apache License 2.0 | 5 votes |
/** * Lookup the RMIServer stub in a directory. * @param jndiURL A JNDI URL indicating the location of the Stub * (see {@link javax.management.remote.rmi}), e.g.: * <ul><li><tt>rmi://registry-host:port/rmi-stub-name</tt></li> * <li>or <tt>iiop://cosnaming-host:port/iiop-stub-name</tt></li> * <li>or <tt>ldap://ldap-host:port/java-container-dn</tt></li> * </ul> * @param env the environment Map passed to the connector. * @param isIiop true if the stub is expected to be an IIOP stub. * @return The retrieved RMIServer stub. * @exception NamingException if the stub couldn't be found. **/ private RMIServer findRMIServerJNDI(String jndiURL, Map<String, ?> env, boolean isIiop) throws NamingException { InitialContext ctx = new InitialContext(EnvHelp.mapToHashtable(env)); Object objref = ctx.lookup(jndiURL); ctx.close(); if (isIiop) return narrowIIOPServer(objref); else return narrowJRMPServer(objref); }
Example 10
Source File: QueueLocalTransactionCommitTest.java From ballerina-message-broker with Apache License 2.0 | 5 votes |
@Parameters({"broker-port", "admin-username", "admin-password", "broker-hostname"}) @Test(expectedExceptions = javax.jms.IllegalStateException.class, expectedExceptionsMessageRegExp = ".*Session is not transacted") public void testCommitOnNonTransactionSession(String port, String adminUsername, String adminPassword, String brokerHostname) throws NamingException, JMSException { String queueName = "testCommitOnNonTransactionSession"; InitialContext initialContextForQueue = ClientHelper .getInitialContextBuilder(adminUsername, adminPassword, brokerHostname, port) .withQueue(queueName) .build(); ConnectionFactory connectionFactory = (ConnectionFactory) initialContextForQueue.lookup(ClientHelper.CONNECTION_FACTORY); Connection connection = connectionFactory.createConnection(); connection.start(); // send 100 messages Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue queue = producerSession.createQueue(queueName); MessageProducer producer = producerSession.createProducer(queue); int numberOfMessages = 100; for (int i = 0; i < numberOfMessages; i++) { producer.send(producerSession.createTextMessage("Test message " + i)); } //catch exception and re-throw it since we need the connection to be closed try { // commit all sent messages on non transactional session producerSession.commit(); } catch (Exception e) { throw e; } finally { producerSession.close(); connection.close(); } }
Example 11
Source File: TestUtil.java From apiman with Apache License 2.0 | 5 votes |
/** * Ensure that the given name is bound to a context. * @param ctx * @param name * @throws NamingException */ public static final Context ensureCtx(InitialContext ctx, String name) throws NamingException { try { return ctx.createSubcontext(name); } catch (NameAlreadyBoundException e) { // this is ok return (Context) ctx.lookup(name); } }
Example 12
Source File: RmiIiopBmpBean.java From tomee with Apache License 2.0 | 5 votes |
public ObjectGraph returnNestedEJBObject() throws javax.ejb.EJBException { ObjectGraph data = null; try { final InitialContext ctx = new InitialContext(); final EncBmpHome home = (EncBmpHome) ctx.lookup("java:comp/env/bmp/rmi-iiop/home"); final EncBmpObject object = home.create("Test02 BmpBean"); data = new ObjectGraph(object); } catch (final Exception e) { throw new javax.ejb.EJBException(e); } return data; }
Example 13
Source File: EncStatefulBean.java From tomee with Apache License 2.0 | 5 votes |
public void lookupStatefulBusinessRemote() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final BasicStatefulBusinessRemote object = (BasicStatefulBusinessRemote) ctx.lookup("java:comp/env/stateful/beanReferences/stateful-business-remote"); Assert.assertNotNull("The EJB BusinessRemote is null", object); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example 14
Source File: MyTest.java From wildfly-camel with Apache License 2.0 | 5 votes |
@Test public void testMyRoute() throws NamingException { InitialContext context = new InitialContext(); CamelContext camelContext = (CamelContext) context.lookup("java:jboss/camel/context/spring-context"); Assert.assertNotNull("Expecting camelContext to not be null", camelContext); ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); String result = producerTemplate.requestBody("direct:start", "Kermit", String.class); Assert.assertEquals("Hello Kermit", result); }
Example 15
Source File: RmiIiopStatefulBean.java From tomee with Apache License 2.0 | 5 votes |
public EJBObject returnEJBObject() throws javax.ejb.EJBException { EncStatefulObject data = null; try { final InitialContext ctx = new InitialContext(); final EncStatefulHome home = (EncStatefulHome) ctx.lookup("java:comp/env/stateful/rmi-iiop/home"); data = home.create("Test01 StatefulBean"); } catch (final Exception e) { throw new javax.ejb.EJBException(e); } return data; }
Example 16
Source File: DtxStartNegativeTestCase.java From product-ei with Apache License 2.0 | 4 votes |
/** * Tests if resuming a new XID will throw an exception */ @Test(groups = { "wso2.mb", "dtx" }, expectedExceptions = XAException.class, expectedExceptionsMessageRegExp = ".*Error while starting dtx session.*") public void startAnAlreadyStartedDtxBranch() throws NamingException, JMSException, XAException, XPathExpressionException { String queueName = "DtxStartTestCaseStartAnAlreadyStartedDtxBranch"; InitialContext initialContext = JMSClientHelper .createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort()) .withQueue(queueName) .build(); // Publish to queue and rollback XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY); XAConnection xaConnection = connectionFactory.createXAConnection(); xaConnection.start(); XASession xaSession = xaConnection.createXASession(); XAResource xaResource = xaSession.getXAResource(); Session session = xaSession.getSession(); Destination xaTestQueue = (Destination) initialContext.lookup(queueName); session.createQueue(queueName); MessageProducer producer = session.createProducer(xaTestQueue); Xid xid = JMSClientHelper.getNewXid(); xaResource.start(xid, XAResource.TMNOFLAGS); // XAConnection xaConnectionDuplicate = connectionFactory.createXAConnection(); xaConnection.start(); XASession xaSessionDuplicate = xaConnectionDuplicate.createXASession(); XAResource xaResourceDuplicate = xaSessionDuplicate.getXAResource(); Session sessionDuplicate = xaSessionDuplicate.getSession(); MessageProducer producerDuplicate = sessionDuplicate.createProducer(xaTestQueue); xaResourceDuplicate.start(xid, XAResource.TMNOFLAGS); // Below this line should not execute producer.send(session.createTextMessage("Test 1")); xaResource.end(xid, XAResource.TMSUCCESS); xaResource.prepare(xid); xaResource.rollback(xid); session.close(); xaConnection.close(); }
Example 17
Source File: TopicDistributedTransactionTest.java From ballerina-message-broker with Apache License 2.0 | 4 votes |
@Test public void testPublisherWithCommit() throws Exception { String subscriptionId = "sub-testPublisherWithCommit"; String topicName = "testPublisherWithCommit"; String testMessage = "testPublisherWithCommit-Message"; InitialContext initialContext = initialContextBuilder.withXaConnectionFactory().withTopic(topicName).build(); Topic topic = (Topic) initialContext.lookup(topicName); // Setup XA producer. XATopicConnectionFactory xaTopicConnectionFactory = (XATopicConnectionFactory) initialContext.lookup(ClientHelper.XA_CONNECTION_FACTORY); XATopicConnection xaTopicConnection = xaTopicConnectionFactory.createXATopicConnection(); XATopicSession xaTopicSession = xaTopicConnection.createXATopicSession(); XAResource xaResource = xaTopicSession.getXAResource(); MessageProducer producer = xaTopicSession.createProducer(topic); // Setup non-transactional consumer. TopicSession topicSession = xaTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE); TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId); xaTopicConnection.start(); // Send message within XA transaction. XidImpl xid = new XidImpl(0, "branchId".getBytes(), "globalId".getBytes()); xaResource.start(xid, XAResource.TMNOFLAGS); producer.send(xaTopicSession.createTextMessage(testMessage)); xaResource.end(xid, XAResource.TMSUCCESS); int response = xaResource.prepare(xid); Assert.assertEquals(response, XAResource.XA_OK, "Prepare stage failed."); xaResource.commit(xid, false); TextMessage message = (TextMessage) durableSubscriber.receive(2000); Assert.assertNotNull(message, "Didn't receive a message"); Assert.assertEquals(message.getText(), testMessage, "Received message content didn't match sent message."); topicSession.close(); xaTopicSession.close(); xaTopicConnection.close(); }
Example 18
Source File: GlobalLookupScopesTest.java From tomee with Apache License 2.0 | 4 votes |
public Object lookup(final String s) throws javax.naming.NamingException { final InitialContext context = new InitialContext(); return context.lookup(s); }
Example 19
Source File: DtxStartPositiveTestCase.java From product-ei with Apache License 2.0 | 4 votes |
/** * Tests if publishing messages works correctly with session suspending and resuming.Steps are, * 1. Using a distributed transaction a message is published to a queue and session is suspended * 2. Subscribe to the published queue and see if any message is received. * 3. Resume the suspended session and publish another message and commit * 4. Subscribe to the queue and see if two messages are received */ @Test(groups = { "wso2.mb", "dtx" }) public void suspendResumeQueuePublishTestCase() throws NamingException, JMSException, XAException, XPathExpressionException { String queueName = "DtxStartPositiveTestCaseSuspendResumeQueuePublishTestCase"; InitialContext initialContext = JMSClientHelper.createInitialContextBuilder("admin", "admin", "localhost", getAMQPPort()).withQueue(queueName).build(); // Publish to queue and rollback XAConnectionFactory connectionFactory = (XAConnectionFactory) initialContext .lookup(JMSClientHelper.QUEUE_XA_CONNECTION_FACTORY); XAConnection xaConnection = connectionFactory.createXAConnection(); xaConnection.start(); XASession xaSession = xaConnection.createXASession(); XAResource xaResource = xaSession.getXAResource(); Session session = xaSession.getSession(); Destination xaTestQueue = (Destination) initialContext.lookup(queueName); session.createQueue(queueName); MessageProducer producer = session.createProducer(xaTestQueue); Xid xid = JMSClientHelper.getNewXid(); xaResource.start(xid, XAResource.TMNOFLAGS); producer.send(session.createTextMessage("Test 1")); xaResource.end(xid, XAResource.TMSUSPEND); // subscribe and see if the message is received ConnectionFactory queueConnectionFactory = (ConnectionFactory) initialContext .lookup(JMSClientHelper.QUEUE_CONNECTION_FACTORY); Connection queueConnection = queueConnectionFactory.createConnection(); queueConnection.start(); Session queueSession = queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer messageConsumer = queueSession.createConsumer(xaTestQueue); // wait 5 seconds Message receive = messageConsumer.receive(5000); Assert.assertNull(receive, "Message received. Message was not rolled back"); xaResource.start(xid, XAResource.TMRESUME); producer.send(session.createTextMessage("Test 2")); xaResource.end(xid, XAResource.TMSUCCESS); xaResource.prepare(xid); xaResource.commit(xid, false); session.close(); xaConnection.close(); receive = messageConsumer.receive(5000); Assert.assertNotNull(receive, "Message not received"); receive = messageConsumer.receive(5000); Assert.assertNotNull(receive, "Message not received"); queueConnection.close(); }
Example 20
Source File: PersistenceContextStatefulBean.java From tomee with Apache License 2.0 | 4 votes |
public void testPropagatedPersistenceContext() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/ExtendedTestContext"); Assert.assertNotNull("The EntityManager is null", em); // call a do nothing method to assure entity manager actually exists em.getFlushMode(); // get the raw entity manager so we can test it below inheritedDelegate = (EntityManager) em.getDelegate(); // The extended entity manager is not propigated to a non-extended entity manager unless there is a transaction final EntityManager nonExtendedEm = (EntityManager) ctx.lookup("java:comp/env/persistence/TestContext"); nonExtendedEm.getFlushMode(); final EntityManager nonExtendedDelegate = ((EntityManager) nonExtendedEm.getDelegate()); Assert.assertTrue("non-extended entity manager should be open", nonExtendedDelegate.isOpen()); Assert.assertNotSame("Extended non-extended entity manager shound not be the same instance as extendend entity manager when accessed out side of a transactions", inheritedDelegate, nonExtendedDelegate); // When the non-extended entity manager is accessed within a transaction is should see the stateful extended context. // // Note: this code also tests EBJ 3.0 Persistence spec 5.9.1 "UserTransaction is begun within the method, the // container associates the persistence context with the JTA transaction and calls EntityManager.joinTransaction." // If our the extended entity manager were not associted with the transaction, the non-extended entity manager would // not see it. final UserTransaction userTransaction = ejbContext.getUserTransaction(); userTransaction.begin(); try { Assert.assertSame("Extended non-extended entity manager to be same instance as extendend entity manager", inheritedDelegate, nonExtendedEm.getDelegate()); } finally { userTransaction.commit(); } // When a stateful bean with an extended entity manager creates another stateful bean, the new bean will // inherit the extended entity manager (assuming it contains an extended entity manager for the same persistence // unit). final PersistenceContextStatefulHome home = (PersistenceContextStatefulHome) ejbContext.getEJBHome(); final PersistenceContextStatefulObject object = home.create(); // test the new stateful bean recieved the context object.testPropgation(); // remove the bean object.remove(); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }