Пример #1
0
  public BeanManager getBeanManager() {

    if (beanManager == null) {
      Object result = null;

      try {
        InitialContext initialContext = new InitialContext();
        result = initialContext.lookup("java:comp/BeanManager");
      } catch (NamingException exception) {
        try {
          InitialContext initialContext = new InitialContext();
          result = initialContext.lookup("java:comp/env/BeanManager");
        } catch (NamingException exception2) {
        }
      }

      if (result != null) {
        beanManager = (BeanManager) result;
      } else {
        beanManager = null;
      }
    }

    return beanManager;
  }
  @Test
  public void testClusteredTopic() throws Exception {

    InitialContext contextFromServer0 = createJNDIContextFromServer0();
    InitialContext contextFromServer1 = createJNDIContextFromServer1();

    try (JMSContext jmsContext0 = createJMSContext(createJNDIContextFromServer0());
        JMSContext jmsContext1 = createJMSContext(createJNDIContextFromServer1())) {
      JMSConsumer consumer0 =
          jmsContext0.createConsumer((Destination) contextFromServer0.lookup(jmsTopicLookup));
      JMSConsumer consumer1 =
          jmsContext1.createConsumer((Destination) contextFromServer1.lookup(jmsTopicLookup));

      String text = UUID.randomUUID().toString();

      // WIP test if the problem is that the view is not yet propagated
      Thread.sleep(ClusteringTestConstants.GRACE_TIME_TO_MEMBERSHIP_CHANGE);

      // send a message to the topic on server 0
      sendMessage(contextFromServer0, jmsTopicLookup, text);
      // consumers receive it on both servers
      receiveMessage(consumer0, text);
      receiveMessage(consumer1, text);

      String anotherText = UUID.randomUUID().toString();
      // send another message to topic on server 1
      sendMessage(contextFromServer1, jmsTopicLookup, anotherText);
      // consumers receive it on both servers
      receiveMessage(consumer0, anotherText);
      receiveMessage(consumer1, anotherText);
    }
  }
  /** Constructor del encargado de enviar mensajes JMS. */
  public RespuestaConsultaValue() {
    try {
      final Properties env = new Properties();
      env.put("org.jboss.ejb.client.scoped.context", true);
      env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
      env.put("endpoint.name", "endpoint-client");

      ictx = new InitialContext(env);

      Object tmp = ictx.lookup("ConnectionFactory");
      QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
      conn = qcf.createQueueConnection();
      this.cola = (Queue) ictx.lookup("queue/test");

      queueSession = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);

      conn.start();

    } catch (JMSException e) {
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public void test() throws Exception {
    MyBean.instances.set(0);

    InitialContext context = new InitialContext();
    MyBean myBean = (MyBean) context.lookup("MyBeanLocalBean");

    assertEquals("pan", myBean.echo("nap"));
    assertEquals(1, MyBean.instances.get());

    context.lookup("MyBeanLocalBean");
    assertEquals(2, MyBean.instances.get());

    // TODO -- implement this
    //        assertTrue(myBean.noTransaction());
    //        assertTrue(myBean.inTransaction());
    //
    //        try {
    //            myBean.noDestroyBean();
    //            fail("Should have thrown MyRuntimeException");
    //        } catch (MyRuntimeException e) {
    //            // good -- this was expected
    //        }
    //
    //        // Instance should still be alive
    //        assertEquals("pan", myBean.echo("nap"));
  }
 @BeforeClass
 public void setup() throws Exception {
   InitialContext context = new InitialContext(Util.getInitProperties());
   orderService = (OrderService) context.lookup(Util.ORDER_SERVICE_NAME);
   customerService = (CustomerService) context.lookup(Util.CUSTOMER_SERVICE_NAME);
   catalogService = (CatalogService) context.lookup(Util.CATALOG_SERVICE_NAME);
 }
Пример #6
0
 public void init(ServletConfig config) throws ServletException {
   super.init(config);
   try {
     InitialContext ic = new InitialContext();
     woggle = (Integer) ic.lookup("java:comp/env/woggle");
     envEntryGlobalScopeResult =
         "EnvEntry defined in context xml lookup result (java:comp/env/woggle): "
             + (woggle == 4000
                 ? "<span class=\"pass\">PASS"
                 : "<span class=\"fail\">FAIL(expected 4000, got " + woggle + ")")
             + "</span>";
     gargle = (Double) ic.lookup("java:comp/env/gargle");
     envEntryWebAppScopeResult =
         "EnvEntry defined in jetty-env.xml lookup result (java:comp/env/gargle): "
             + (gargle == 100.0
                 ? "<span class=\"pass\">PASS"
                 : "<span class=\"fail\">FAIL(expected 100, got " + gargle + ")")
             + "</span>";
     UserTransaction utx = (UserTransaction) ic.lookup("java:comp/UserTransaction");
     userTransactionResult =
         "UserTransaction lookup result (java:comp/UserTransaction): "
             + (utx != null ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL")
             + "</span>";
     myMailSession = (Session) ic.lookup("java:comp/env/mail/Session");
     mailSessionResult =
         "Mail Session lookup result (java:comp/env/mail/Session): "
             + (myMailSession != null ? "<span class=\"pass\">PASS" : "<span class=\"fail\">FAIL")
             + "</span>";
   } catch (Exception e) {
     throw new ServletException(e);
   }
 }
Пример #7
0
  @Before
  public void setUp() throws Exception {
    log.debug("getting jndi initial context");
    jndi = new InitialContext();
    log.debug("jndi=" + jndi.getEnvironment());

    log.debug("looking up:" + auctionmgmtJNDI);
    auctionmgmt = (AuctionMgmtRemote) jndi.lookup(auctionmgmtJNDI);

    log.debug("looking up:" + usermgmtJNDI);
    usermgmt = (UserMgmtRemote) jndi.lookup(usermgmtJNDI);

    log.debug("looking up:" + sellerJNDI);
    seller = (SellerRemote) jndi.lookup(sellerJNDI);

    log.debug("looking up:" + buyerJNDI);
    buyer = (BuyerRemote) jndi.lookup(buyerJNDI);

    try {
      cleanup();
    } catch (UndeclaredThrowableException ue) {
      log.error("error in cleanup:", ue.getUndeclaredThrowable());
      fail("" + ue.getUndeclaredThrowable());
    }
  }
Пример #8
0
  public static void main(String[] argv) {
    try {

      String dmds_name = null;
      String cpds_name = null;
      String pbds_name = null;

      if (argv.length == 3) {
        dmds_name = argv[0];
        cpds_name = argv[1];
        pbds_name = argv[2];
      } else usage();

      InitialContext ctx = new InitialContext();
      DataSource dmds = (DataSource) ctx.lookup(dmds_name);
      dmds.getConnection().close();
      System.out.println(
          "DriverManagerDataSource " + dmds_name + " sucessfully looked up and checked.");
      ConnectionPoolDataSource cpds = (ConnectionPoolDataSource) ctx.lookup(cpds_name);
      cpds.getPooledConnection().close();
      System.out.println(
          "ConnectionPoolDataSource " + cpds_name + " sucessfully looked up and checked.");
      DataSource pbds = (DataSource) ctx.lookup(pbds_name);
      pbds.getConnection().close();
      System.out.println(
          "PoolBackedDataSource " + pbds_name + " sucessfully looked up and checked.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #9
0
  @Test
  public void testSendMessage() throws Exception {
    ConnectionFactory cf = null;
    Connection connection = null;
    Session session = null;

    try {
      cf = (ConnectionFactory) initialContext.lookup("jms/RemoteConnectionFactory");
      Queue queue = (Queue) initialContext.lookup(QUEUE_NAME);
      connection = cf.createConnection("guest", "guest");
      connection.start(); // for consumer we need to start connection
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      TemporaryQueue replyQueue = session.createTemporaryQueue();
      TextMessage message = session.createTextMessage("hello goodbye");
      message.setJMSReplyTo(replyQueue);
      sender.send(message);
      log.trace("testSendMessage(): Message sent!");

      MessageConsumer consumer = session.createConsumer(replyQueue);
      Message replyMsg = consumer.receive(5000);
      Assert.assertNotNull(replyMsg);
      Assert.assertTrue(replyMsg instanceof TextMessage);
      String actual = ((TextMessage) replyMsg).getText();
      Assert.assertEquals("Howdy Fred! GoodBye user1", actual);
    } finally {
      if (session != null) {
        session.close();
      }
      closeConnection(connection);
    }
  }
 /**
  * - We first create a {@link Context}, do a lookup and then stop the server. - Next we do the
  * lookup and it's expected to fail, since the server is down. - We restart the server and use the
  * same previously created {@link Context} and do the lookup again. The lookup is expected to
  * succeed
  *
  * @throws Exception
  */
 @Test
 public void testReconnect() throws Exception {
   Properties env = new Properties();
   env.put(
       Context.INITIAL_CONTEXT_FACTORY,
       org.jboss.naming.remote.client.InitialContextFactory.class.getName());
   env.put(Context.PROVIDER_URL, "remote://localhost:7999");
   env.put("jboss.naming.client.ejb.context", "false");
   final InitialContext context = new InitialContext(env);
   assertEquals("TestValue", context.lookup("test"));
   // now stop the server
   stopServer();
   logger.info("Stopped server");
   // lookup again, should fail since server is stopped
   try {
     context.lookup("test");
     fail("Lookup was expected to fail when server was down");
   } catch (NamingException ne) {
     // expected
   }
   // now restart the server
   startServer();
   // now lookup again, this should succeed (internally a reconnect to the restarted server should
   // happen)
   final String lookupValueAfterServerRestart = (String) context.lookup("test");
   assertEquals(
       "Unexpected lookup value after server was restarted",
       "TestValue",
       lookupValueAfterServerRestart);
 }
Пример #11
0
  public static void main(String[] args) {
    try { // Create and start connection
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory f = (QueueConnectionFactory) ctx.lookup("myQueueConnectionFactory");
      QueueConnection con = f.createQueueConnection();
      con.start();
      // 2) create queue session
      QueueSession ses = con.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      // 3) get the Queue object
      Queue t = (Queue) ctx.lookup("myQueue");
      // 4)create QueueSender object
      QueueSender sender = ses.createSender(t);
      // 5) create TextMessage object
      TextMessage msg = ses.createTextMessage();

      // 6) write message
      BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
      while (true) {
        System.out.println("Enter Msg, end to terminate:");
        String s = b.readLine();
        if (s.equals("end")) break;
        msg.setText(s);
        // 7) send message
        sender.send(msg);
        System.out.println("Message successfully sent.");
      }
      // 8) connection close
      con.close();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Пример #12
0
  /**
   * @param inId
   * @param command
   * @param parameters
   * @return
   * @throws NamingException
   */
  @Override
  public boolean executeProcessOnInMail(long inId, String command, String parameters)
      throws NamingException, JMSException {

    boolean suc = false;
    InitialContext ic = null;
    Connection connection = null;
    String msgFactoryJndiName = getJNDIPrefix() + SEDValues.EBMS_JMS_CONNECTION_FACTORY_JNDI;
    String msgQueueJndiName = getJNDI_JMSPrefix() + SEDValues.JNDI_QUEUE_EXECUTION;
    try {
      ic = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ic.lookup(msgFactoryJndiName);
      Queue queue = (Queue) ic.lookup(msgQueueJndiName);
      connection = cf.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer sender = session.createProducer(queue);
      Message message = session.createMessage();

      message.setLongProperty(SEDValues.EBMS_QUEUE_PARAM_MAIL_ID, inId);
      message.setStringProperty(SEDValues.EXEC_COMMAND, command);
      message.setStringProperty(SEDValues.EXEC_PARAMS, parameters);
      sender.send(message);
      suc = true;
    } finally {
      if (ic != null) {
        try {
          ic.close();
        } catch (Exception ignore) {
        }
      }
      closeConnection(connection);
    }

    return suc;
  }
Пример #13
0
  public void testSFSBCollocation() throws Exception {
    InitialContext ctx = new InitialContext();
    StatefulTestLocal local =
        (StatefulTestLocal) ctx.lookup("initial-ejb3-test/StatefulTestBean/local");
    StatefulTestRemote remote =
        (StatefulTestRemote) ctx.lookup("initial-ejb3-test/StatefulTestBean/remote");

    if (local.getObject() != StatefulTestBean.obj)
      throw new RuntimeException("Local call not equal");
    if (local.getObject() == remote.getObject())
      throw new RuntimeException("Remote should not be equal");
    Map map = remote.getObject();
    map.put("hello", "world");

    Object obj = local.echo(map);
    if (obj != map) throw new RuntimeException("argument and return should be the same");
    map = (Map) obj;
    if (!map.containsKey("hello")) throw new RuntimeException("not good return");

    obj = remote.echo(map);
    if (obj == map) throw new RuntimeException("argument and return should not be the same");

    map = (Map) obj;
    if (!map.containsKey("hello")) throw new RuntimeException("not good return");
  }
  public DigitalLibraryServer() {
    try {
      Properties properties = new Properties();
      properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
      properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
      properties.put(Context.PROVIDER_URL, "localhost");

      InitialContext jndi = new InitialContext(properties);
      ConnectionFactory conFactory = (ConnectionFactory) jndi.lookup("XAConnectionFactory");
      connection = conFactory.createConnection();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      try {
        counterTopic = (Topic) jndi.lookup("counterTopic");
      } catch (NamingException NE1) {
        System.out.println("NamingException: " + NE1 + " : Continuing anyway...");
      }

      if (null == counterTopic) {
        counterTopic = session.createTopic("counterTopic");
        jndi.bind("counterTopic", counterTopic);
      }

      consumer = session.createConsumer(counterTopic);
      consumer.setMessageListener(this);
      System.out.println("Server started waiting for client requests");
      connection.start();
    } catch (NamingException NE) {
      System.out.println("Naming Exception: " + NE);
    } catch (JMSException JMSE) {
      System.out.println("JMS Exception: " + JMSE);
      JMSE.printStackTrace();
    }
  }
Пример #15
0
  public void lookupJMSConnectionFactory() throws TestFailureException {
    try {
      try {
        final InitialContext ctx = new InitialContext();
        Assert.assertNotNull("The InitialContext is null", ctx);
        Object obj = ctx.lookup("java:comp/env/jms");
        Assert.assertNotNull("The JMS ConnectionFactory is null", obj);
        Assert.assertTrue("Not an instance of ConnectionFactory", obj instanceof ConnectionFactory);
        final ConnectionFactory connectionFactory = (ConnectionFactory) obj;
        testJmsConnection(connectionFactory.createConnection());

        obj = ctx.lookup("java:comp/env/TopicCF");
        Assert.assertNotNull("The JMS TopicConnectionFactory is null", obj);
        Assert.assertTrue(
            "Not an instance of TopicConnectionFactory", obj instanceof TopicConnectionFactory);
        final TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) obj;
        testJmsConnection(topicConnectionFactory.createConnection());

        obj = ctx.lookup("java:comp/env/QueueCF");
        Assert.assertNotNull("The JMS QueueConnectionFactory is null", obj);
        Assert.assertTrue(
            "Not an instance of QueueConnectionFactory", obj instanceof QueueConnectionFactory);
        final QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) obj;
        testJmsConnection(queueConnectionFactory.createConnection());
      } catch (final Exception e) {
        e.printStackTrace();
        Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
      }
    } catch (final AssertionFailedError afe) {
      throw new TestFailureException(afe);
    }
  }
  public void testMultipleSenders() throws Exception {
    ConnectionFactory cf = (ConnectionFactory) ic.lookup("/ConnectionFactory");
    Queue queue = (Queue) ic.lookup("/queue/StressTestQueue");
    drainDestination(cf, queue);

    Connection conn = cf.createConnection();

    Session[] sessions = new Session[CorruptMessageStressTest.PRODUCER_COUNT];
    MessageProducer[] producers = new MessageProducer[CorruptMessageStressTest.PRODUCER_COUNT];

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      sessions[i] = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      producers[i] = sessions[i].createProducer(queue);
      producers[i].setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    }

    Thread[] threads = new Thread[CorruptMessageStressTest.PRODUCER_COUNT];

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      threads[i] = new Thread(new Sender(sessions[i], producers[i]), "Sender Thread #" + i);
      threads[i].start();
    }

    // wait for the threads to finish

    for (int i = 0; i < CorruptMessageStressTest.PRODUCER_COUNT; i++) {
      threads[i].join();
    }

    conn.close();
  }
Пример #17
0
  public void sendResponse(
      Destination destination, Serializable message, String correlationId, String transactionId)
      throws JMSException {
    Connection connection = null;
    Session session = null;

    try {
      InitialContext initialContext = new InitialContext(initialContextProperties);
      // InitialContext initialContext = new InitialContext();

      connectionFactoryName = "/ConnectionFactory";

      if (connectionFactory == null)
        connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);

      if (destination == null) destination = (Destination) initialContext.lookup(destinationName);

      if (userName == null || password == null) connection = connectionFactory.createConnection();
      else connection = connectionFactory.createConnection(userName, password);

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      // session.

      MessageProducer producer = session.createProducer(destination);
      connection.start();

      ObjectMessage objectMessage = session.createObjectMessage(message);
      // objectMessage.setLongProperty(MessageConstants.PROPERTY_REQUEST_ID, requestId);
      objectMessage.setStringProperty(MessageConstants.PROPERTY_CORRELATION_ID, correlationId);
      objectMessage.setStringProperty(MessageConstants.PROPERTY_TRANSACTION_ID, transactionId);
      // objectMessage.setObjectProperty(MessageConstants.PROPERTY_MESSAGE_CONTENT, message);
      objectMessage.setJMSReplyTo(null);

      producer.send(objectMessage);

    } catch (NamingException e) {
      connectionFactory = null;
      destination = null;
      throw ExceptionUtil.rewrap(e);

    } catch (JMSException e) {
      connectionFactory = null;
      destination = null;
      throw e;

    } finally {
      // it is important to close session
      if (session != null) session.close();
      try {
        // Closing a connection automatically returns the connection and
        // its session plus producer to the resource reference pool.
        if (connection != null) connection.close();
      } catch (JMSException e) {
        // ignore
      }
      ;
    }
  }
Пример #18
0
  @Test
  public void testIt() throws Exception {
    final InitialContext ctx = getRemoteContext();
    final ClassLoader current = Thread.currentThread().getContextClassLoader();

    try {
      Thread.currentThread().setContextClassLoader(Remote.class.getClassLoader());

      Remote remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME + "/" + Bean.class.getSimpleName() + "!" + Remote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME
                      + "/"
                      + Singleton.class.getSimpleName()
                      + "!"
                      + BinderRemote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      remote =
          (Remote)
              ctx.lookup(
                  ARCHIVE_NAME
                      + "/"
                      + StatefulBean.class.getSimpleName()
                      + "!"
                      + Remote.class.getName());
      assertNotNull(remote);
      assertEquals("Echo: test", remote.echo("test"));

      final Set<String> expected = new HashSet<String>();
      expected.add(Bean.class.getSimpleName() + "!" + Remote.class.getName());
      expected.add(Singleton.class.getSimpleName() + "!" + BinderRemote.class.getName());
      expected.add(StatefulBean.class.getSimpleName() + "!" + Remote.class.getName());

      NamingEnumeration<NameClassPair> e = ctx.list("test");
      while (e.hasMore()) {
        NameClassPair binding = e.next();
        if (!expected.remove(binding.getName())) {
          Assert.fail("unknown binding " + binding.getName());
        }
      }
      if (!expected.isEmpty()) {
        Assert.fail("bindings not found " + expected);
      }

    } finally {
      ctx.close();
      Thread.currentThread().setContextClassLoader(current);
    }
  }
Пример #19
0
  @Test
  public void testRemoteNamingGracefulShutdown() throws Exception {

    ModelNode op = new ModelNode();
    op.get(ModelDescriptionConstants.OP).set("suspend");
    managementClient.getControllerClient().execute(op);

    Thread.currentThread().setContextClassLoader(Remote.class.getClassLoader());

    final InitialContext ctx = getRemoteContext();
    final ClassLoader current = Thread.currentThread().getContextClassLoader();
    try {

      try {

        Remote remote =
            (Remote)
                ctx.lookup(
                    ARCHIVE_NAME + "/" + Bean.class.getSimpleName() + "!" + Remote.class.getName());
        Assert.fail();
      } catch (NamingException expected) {
      }

      try {
        Remote remote =
            (Remote)
                ctx.lookup(
                    ARCHIVE_NAME
                        + "/"
                        + Singleton.class.getSimpleName()
                        + "!"
                        + BinderRemote.class.getName());
        Assert.fail();
      } catch (NamingException expected) {
      }

      try {
        Remote remote =
            (Remote)
                ctx.lookup(
                    ARCHIVE_NAME
                        + "/"
                        + StatefulBean.class.getSimpleName()
                        + "!"
                        + Remote.class.getName());
        Assert.fail();
      } catch (NamingException expected) {
      }
    } finally {
      op = new ModelNode();
      op.get(ModelDescriptionConstants.OP).set("resume");
      managementClient.getControllerClient().execute(op);

      ctx.close();
      Thread.currentThread().setContextClassLoader(current);
    }
  }
  public void testPojoStyleBean() throws Exception {
    List expected = Arrays.asList(Lifecycle.values());
    InitialContext ctx = new InitialContext();

    {
      WidgetBean.lifecycle.clear();

      Object object = ctx.lookup("WidgetBeanLocal");

      assertTrue("instanceof widget", object instanceof Widget);

      Widget widget = (Widget) object;

      // Do a business method...
      Stack<Lifecycle> lifecycle = widget.getLifecycle();
      assertNotNull("lifecycle", lifecycle);
      assertSame("lifecycle", lifecycle, WidgetBean.lifecycle);

      // Check the lifecycle of the bean
      assertEquals(join("\n", expected), join("\n", lifecycle));
    }
    {
      WidgetBean.lifecycle.clear();

      Object object = ctx.lookup("WidgetBeanLocalBean");

      assertTrue("instanceof widget", object instanceof WidgetBean);

      WidgetBean widget = (WidgetBean) object;

      // Do a business method...
      Stack<Lifecycle> lifecycle = widget.getLifecycle();
      assertNotNull("lifecycle", lifecycle);
      assertSame("lifecycle", lifecycle, WidgetBean.lifecycle);

      // Check the lifecycle of the bean
      assertEquals(
          Lifecycle.CONSTRUCTOR + "\n" + Lifecycle.BUSINESS_METHOD + "\n", join("\n", lifecycle));
    }
    {
      WidgetBean.lifecycle.clear();

      Object object = ctx.lookup("WidgetBeanRemote");

      assertTrue("instanceof widget", object instanceof RemoteWidget);

      RemoteWidget remoteWidget = (RemoteWidget) object;

      // Do a business method...
      Stack<Lifecycle> lifecycle = remoteWidget.getLifecycle();
      assertNotNull("lifecycle", lifecycle);
      assertNotSame("lifecycle", lifecycle, WidgetBean.lifecycle);

      // Check the lifecycle of the bean
      assertEquals(Lifecycle.BUSINESS_METHOD + "\n", join("\n", lifecycle));
    }
  }
 @Test
 public void testInterceptors() throws NamingException {
   final InitialContext ctx = new InitialContext();
   TestEjb bean = (TestEjb) ctx.lookup("java:module/Test1");
   Assert.assertEquals(EJB_SIMPLE_RETURN, bean.test());
   bean = (TestEjb) ctx.lookup("java:module/Test2");
   Assert.assertEquals(EJB_SIMPLE_RETURN, bean.test());
   bean = (TestEjb) ctx.lookup("java:module/Production");
   Assert.assertEquals(EJB_SIMPLE_RETURN, bean.test());
 }
Пример #22
0
 public BusinessLogicEjbDto() throws Exception {
   InitialContext ctx = new InitialContext();
   movieService =
       (RmiMovieService) ctx.lookup("movies/RmiFacade!ch.fhnw.edu.rental.service.RmiMovieService");
   userService =
       (RmiUserService) ctx.lookup("movies/RmiFacade!ch.fhnw.edu.rental.service.RmiUserService");
   rentalService =
       (RmiRentalService)
           ctx.lookup("movies/RmiFacade!ch.fhnw.edu.rental.service.RmiRentalService");
 }
Пример #23
0
 public DBConnector(InitialContext ic) {
   this.ic = ic;
   try {
     networkHandler = (NetworkHandler) ic.lookup("NetworkHandlerBean/local");
     compositionHandler = (CompositionHandler) ic.lookup("CompositionHandlerBean/local");
     eventHandler = (EventHandler) ic.lookup("EventHandlerBean/local");
   } catch (NamingException e) {
     e.printStackTrace();
   }
 }
Пример #24
0
  public void ejbCreate() throws CreateException {
    try {
      InitialContext initial = new InitialContext();
      Object objref = initial.lookup("java:comp/env/ejb/Customer");
      custHome = (CustomerHome) PortableRemoteObject.narrow(objref, CustomerHome.class);

      objref = initial.lookup("java:comp/env/ejb/Address");
      addressHome = (AddressHome) PortableRemoteObject.narrow(objref, AddressHome.class);

      objref = initial.lookup("java:comp/env/ejb/Country");
      countryHome = (CountryHome) PortableRemoteObject.narrow(objref, CountryHome.class);

      objref = initial.lookup("java:comp/env/ejb/Order");
      orderHome = (OrderHome) PortableRemoteObject.narrow(objref, OrderHome.class);

      objref = initial.lookup("java:comp/env/ejb/OrderLine");
      orderLineHome = (OrderLineHome) PortableRemoteObject.narrow(objref, OrderLineHome.class);

      objref = initial.lookup("java:comp/env/ejb/Cc_xact");
      xactHome = (Cc_xactHome) PortableRemoteObject.narrow(objref, Cc_xactHome.class);

      objref = initial.lookup("java:comp/env/ejb/Item");
      itemHome = (ItemHome) PortableRemoteObject.narrow(objref, ItemHome.class);

      objref = initial.lookup("java:comp/env/ejb/Author");
      authorHome = (AuthorHome) PortableRemoteObject.narrow(objref, AuthorHome.class);

      datasource = (DataSource) initial.lookup("java:comp/env/jdbc/TPCWDS");

      rand = new Random(System.currentTimeMillis());
    } catch (Exception ex) {
      throw new EJBException(ex.getMessage());
    }
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String firstName = request.getParameter("nome");
    String lastName = request.getParameter("cognome");

    try {
      ctx = new InitialContext();
      sb = (SearchBeanLocal) ctx.lookup("SearchBean/local");
      fb = (FriendshipBeanLocal) ctx.lookup("FriendshipBean/local");

      List<String> results = (List<String>) sb.searchByName(firstName, lastName);

      if (!results.isEmpty()) {
        List<String> resultsHTML = new ArrayList<String>();
        for (String result : results) {
          String userEmail1 = request.getSession().getAttribute("email").toString();
          String userEmail2 = result.split("\t")[2];
          if (!userEmail1.equals(userEmail2)) {
            if (fb.areAlreadyFriends(userEmail1, userEmail2)) {
              if (!fb.isUnconfirmedFriendship(userEmail1, userEmail2)) {
                result += "\t" + "2";
              } else if (fb.isUnconfirmedFriendship(userEmail1, userEmail2)) {
                result += "\t" + "1";
              }
            } else {
              result += "\t" + "0";
            }
            resultsHTML.add(result);
          } else if (results.size() == 1) {
            request.getSession().setAttribute("alert", "L'unico risultato trovato sei tu. (:");
            getServletConfig()
                .getServletContext()
                .getRequestDispatcher("/search.jsp")
                .forward(request, response);
          }
        }
        request.getSession().setAttribute("resultslist", resultsHTML);
        getServletConfig()
            .getServletContext()
            .getRequestDispatcher("/searchresult.jsp")
            .forward(request, response);
      } else {
        request.getSession().setAttribute("alert", "Nessun risultato trovato.");
        getServletConfig()
            .getServletContext()
            .getRequestDispatcher("/search.jsp")
            .forward(request, response);
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (Exception e) {
      System.out.println("La ricerca non ha prodotto risultati, si prega di riprovare");
    }
  }
  public void testUnderscoreMethods() throws Exception {
    InitialContext ctx = new InitialContext();
    StatefulRemote stateful = (StatefulRemote) ctx.lookup("StatefulBean/remote");
    stateful._method();

    StatelessRemote stateless = (StatelessRemote) ctx.lookup("StatelessBean/remote");
    stateless._method();

    ServiceRemote service = (ServiceRemote) ctx.lookup("ServiceBean/remote");
    service._method();
  }
  @PostConstruct
  public void postConstruct() {

    InitialContext ctx = null;

    if (getExecutorService() == null) {

      try {
        ctx = new InitialContext();
      } catch (NamingException e) {
        e.printStackTrace();
      }
      try {
        executorService =
            (ManagedExecutorService) ctx.lookup("java:comp/DefaultManagedExecutorService");
      } catch (NamingException e) {
        e.printStackTrace();
      }
    } else {
    }

    if (getUtx() == null) {

      try {
        ctx = new InitialContext();
      } catch (NamingException e) {
        e.printStackTrace();
      }
      try {
        utx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");
      } catch (NamingException e) {
        e.printStackTrace();
      }
    } else {
    }

    if (getTsr() == null) {

      try {
        ctx = new InitialContext();
      } catch (NamingException e) {
        e.printStackTrace();
      }
      try {
        setTsr(
            (TransactionSynchronizationRegistry)
                ctx.lookup("java:comp/TransactionSynchronizationRegistry"));
      } catch (NamingException e) {
        e.printStackTrace();
      }
    } else {
    }
  }
Пример #28
0
  public void testRebind_1() throws Exception {
    try {
      ic.lookup("/nosuchsubcontext");
      fail("the name is not supposed to be there");
    } catch (NameNotFoundException e) {
      // OK
    }

    JNDIUtil.rebind(ic, "/nosuchsubcontext/sub1/sub2/sub3/name", new Integer(7));

    assertEquals(7, ((Integer) ic.lookup("/nosuchsubcontext/sub1/sub2/sub3/name")).intValue());
  }
Пример #29
0
 @SuppressWarnings("unchecked")
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
   InitialContext ctx = new InitialContext();
   try {
     iBusRouteService = (IBusRouteService<BusRoute>) ctx.lookup("BusRouteService/remote");
     iBusStationService = (IBusStationService<BusStation>) ctx.lookup("BusStationService/remote");
     iCollectInfoService = (ICollectInfoService) ctx.lookup("CollectInfoService/local");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  private JaxbCommandsResponse sendJmsJaxbCommandsRequest(
      String sendQueueName, JaxbCommandsRequest req) throws Exception {
    InitialContext context = getRemoteInitialContext();
    ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
    Queue jbpmQueue = (Queue) context.lookup(sendQueueName);
    Queue responseQueue = (Queue) context.lookup(RESPONSE_QUEUE_NAME);

    Connection connection = null;
    Session session = null;
    JaxbCommandsResponse cmdResponse = null;
    try {
      // setup
      connection = factory.createConnection(USER, PASSWORD);
      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(jbpmQueue);
      String corrId = UUID.randomUUID().toString();
      String selector = "JMSCorrelationID = '" + corrId + "'";
      MessageConsumer consumer = session.createConsumer(responseQueue, selector);

      connection.start();

      // Create msg
      BytesMessage msg = session.createBytesMessage();
      msg.setJMSCorrelationID(corrId);
      msg.setIntProperty("serialization", 1);
      String xmlStr = JaxbSerializationProvider.convertJaxbObjectToString(req);
      msg.writeUTF(xmlStr);

      // send
      producer.send(msg);

      // receive
      Message response = consumer.receive(QUALITY_OF_SERVICE_THRESHOLD_MS);

      // check
      assertNotNull("Response is empty.", response);
      assertEquals(
          "Correlation id not equal to request msg id.", corrId, response.getJMSCorrelationID());
      assertNotNull("Response from MDB was null!", response);
      xmlStr = ((BytesMessage) response).readUTF();
      cmdResponse =
          (JaxbCommandsResponse) JaxbSerializationProvider.convertStringToJaxbObject(xmlStr);
      assertNotNull("Jaxb Cmd Response was null!", cmdResponse);
    } finally {
      if (connection != null) {
        connection.close();
        session.close();
      }
    }
    return cmdResponse;
  }