/* (non-Javadoc)
   * @see org.ikasan.spec.management.ManagedResource#startManagedResource()
   */
  public void startManagedResource() {
    ConnectionFactory _connectionFactory = null;

    try {
      if (this.configuration.isRemoteJNDILookup()) {
        Context context = getInitialContext();
        if (this.configuration.getConnectionFactoryName() == null) {
          throw new RuntimeException(
              "ConnectionFactory name cannot be 'null' when using remoteJNDILookup");
        }
        _connectionFactory =
            (ConnectionFactory) context.lookup(this.configuration.getConnectionFactoryName());

        if (this.configuration.getDestinationName() == null) {
          throw new RuntimeException(
              "DestinationName name cannot be 'null' when using remoteJNDILookup");
        }
        this.destination = (Destination) context.lookup(this.configuration.getDestinationName());
      } else {
        if (this.connectionFactory == null) {
          throw new RuntimeException(
              "You must specify the remoteJNDILookup as true or provide a ConnectionFactory instance for this class.");
        }

        _connectionFactory = this.connectionFactory;
      }

      if (this.configuration.getUsername() != null
          && this.configuration.getUsername().trim().length() > 0) {
        connection =
            _connectionFactory.createConnection(
                this.configuration.getUsername(), this.configuration.getPassword());
      } else {
        connection = _connectionFactory.createConnection();
      }

      this.session =
          connection.createSession(
              this.configuration.isTransacted(), this.configuration.getAcknowledgement());
      if (this.destination == null) {
        if (destinationResolver == null) {
          throw new RuntimeException(
              "destination and destinationResolver are both 'null'. No means of resolving a destination.");
        }

        this.destination = this.destinationResolver.getDestination();
      }
    } catch (JMSException e) {
      throw new EndpointException(e);
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }
  }
  /*
   * Initiate the snapshot by sending a Marker message to one of the Players (Player0)
   * Any Player could have been used to initiate the snapshot.
   */
  private void sendInitSnapshot() {
    try {
      // Gather necessary JMS resources
      Context ctx = new InitialContext();
      ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/myConnectionFactory");
      Queue q = (Queue) ctx.lookup("jms/PITplayer0");
      Connection con = cf.createConnection();
      Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer writer = session.createProducer(q);

      /*
       * As part of the snapshot algorithm, players need to record
       * what other Players they receive markers from.
       * "-1" indicates to the PITplayer0 that this marker is coming from
       * the monitor, not another Player.
       */
      Marker m = new Marker(-1);
      ObjectMessage msg = session.createObjectMessage(m);
      System.out.println("Initiating Snapshot");
      writer.send(msg);
      con.close();
    } catch (JMSException e) {
      System.out.println("JMS Exception thrown" + e);
    } catch (Throwable e) {
      System.out.println("Throwable thrown" + e);
    }
  }
 public UserMessageService(String brokerURL, String queueName) throws JMSException {
   this.queueName = queueName;
   ConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
   this.con = factory.createConnection();
   session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
   this.producer = session.createProducer(null);
 }
  public static void main(String[] args) {
    try {

      // Gets the JgetTopicName()NDI context
      Context jndiContext = new InitialContext();

      // Looks up the administered objects
      ConnectionFactory connectionFactory =
          (ConnectionFactory) jndiContext.lookup("jms/javaee6/ConnectionFactory");
      Queue queue = (Queue) jndiContext.lookup("jms/javaee6/Queue");

      // Creates the needed artifacts to connect to the queue
      Connection connection = connectionFactory.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(queue);
      connection.start();

      // Loops to receive the messages
      System.out.println("\nInfinite loop. Waiting for a message...");
      while (true) {
        TextMessage message = (TextMessage) consumer.receive();
        System.out.println("Message received: " + message.getText());
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #5
0
  /**
   * Creates and configures a new instance.
   *
   * @param dataDirectory root directory where persistent messages are stored
   * @param useLibAio true to use libaio, false if not installed. See <a
   *     href="http://docs.jboss.org/hornetq/2.2.5.Final/user-manual/en/html/libaio.html">Libaio
   *     Native Libraries</a>
   * @param injector Google Guice injector. Used to inject dependency members into commands if
   *     needed.
   * @param queueConfigs vararg of QueueConfig> instances.
   */
  public HornetNest(
      String dataDirectory, boolean useLibAio, Injector injector, QueueConfig... queueConfigs) {
    jmsServer = new EmbeddedJMS();
    config = new ConfigurationImpl();
    jmsConfig = new JMSConfigurationImpl();

    try {
      configureLocations(dataDirectory);
      configureAcceptor();
      configureConnectionFactory();
      configurePaging();
      config.setJournalType(useLibAio ? JournalType.ASYNCIO : JournalType.NIO);
      configureQueues(queueConfigs);

      config.setThreadPoolMaxSize(-1);
      config.setScheduledThreadPoolMaxSize(10);
      jmsServer.setConfiguration(config);
      jmsServer.setJmsConfiguration(jmsConfig);
      jmsServer.start();

      ConnectionFactory connectionFactory = (ConnectionFactory) jmsServer.lookup("/cf");
      if (connectionFactory == null) {
        throw new HornetNestException(
            "Failed to start EmbeddedJMS due to previous errors. Please, see earlier output from HornetQ.");
      }
      consumerConnection = connectionFactory.createConnection();
      producerConnection = connectionFactory.createConnection();
      configureListeners(injector, queueConfigs);
    } catch (HornetNestException e) {
      throw e;
    } catch (Exception e) {
      throw new HornetNestException("Failed to start EmbeddedJMS", e);
    }
  }
  public static void main(String[] args) {
    try {
      Context ctx = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory");
      Queue queue = (Queue) ctx.lookup("inbound");

      Connection con = factory.createConnection();
      final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
      final MessageConsumer consumer = session.createConsumer(queue);

      consumer.setMessageListener(
          new MessageListener() {
            @Override
            public void onMessage(Message message) {
              final String type;
              try {
                type = message.getStringProperty("type");
                if (type != null && type.equals("xml")) {

                  System.out.println(((TextMessage) message).getText());
                }

              } catch (JMSException e) {
                e.printStackTrace();
              }
            }
          });

      con.start();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  private static void createTable() throws Exception {
    try {
      Configuration configuration = HBaseConfiguration.create();
      HBaseAdmin.checkHBaseAvailable(configuration);
      Connection connection = ConnectionFactory.createConnection(configuration);

      // Instantiating HbaseAdmin class
      Admin admin = connection.getAdmin();

      // Instantiating table descriptor class
      HTableDescriptor stockTableDesc =
          new HTableDescriptor(TableName.valueOf(Constants.STOCK_DATES_TABLE));

      // Adding column families to table descriptor
      HColumnDescriptor stock_0414 = new HColumnDescriptor(Constants.STOCK_DATES_CF);
      stockTableDesc.addFamily(stock_0414);

      // Execute the table through admin
      if (!admin.tableExists(stockTableDesc.getTableName())) {
        admin.createTable(stockTableDesc);
        System.out.println("Stock table created !!!");
      }

      // Load hbase-site.xml
      HBaseConfiguration.addHbaseResources(configuration);
    } catch (ServiceException e) {
      log.error("Error occurred while creating HBase tables", e);
      throw new Exception("Error occurred while creating HBase tables", e);
    }
  }
  /**
   * Establishes a connection to a registry.
   *
   * @param queryUrl the URL of the query registry
   * @param publishUrl the URL of the publish registry
   */
  public void makeConnection(String queryUrl, String publishUrl) {

    Context context = null;
    ConnectionFactory factory = null;

    /*
     * Define connection configuration properties.
     * To publish, you need both the query URL and the
     * publish URL.
     */
    Properties props = new Properties();
    props.setProperty("javax.xml.registry.queryManagerURL", queryUrl);
    props.setProperty("javax.xml.registry.lifeCycleManagerURL", publishUrl);

    try {
      // Create the connection, passing it the
      // configuration properties
      context = new InitialContext();
      factory = (ConnectionFactory) context.lookup("java:comp/env/eis/JAXR");
      factory.setProperties(props);
      connection = factory.createConnection();
      System.out.println("Created connection to registry");
    } catch (Exception e) {
      e.printStackTrace();
      if (connection != null) {
        try {
          connection.close();
        } catch (JAXRException je) {
        }
      }
    }
  }
  /**
   * Initializes the qpid connection with a jndiName of cow, and a host and port taken from the
   * cow-server.properties file.
   */
  public void init() {
    String connectionFactorylocation =
        "amqp://*****:*****@clientid/test?brokerlist='tcp://" + host + ":" + port + "'";
    String destinationType = "topic";
    String jndiName = "cow";
    String destinationName = "myTopic";

    try {
      properties = new Properties();
      properties.setProperty(
          Context.INITIAL_CONTEXT_FACTORY,
          "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
      properties.setProperty("connectionfactory.amqpConnectionFactory", connectionFactorylocation);
      properties.setProperty(destinationType + "." + jndiName, destinationName);

      context = new InitialContext(properties);
      ConnectionFactory connectionFactory =
          (ConnectionFactory) context.lookup("amqpConnectionFactory");
      Connection connection = connectionFactory.createConnection();
      connection.start();

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      Destination destination = (Destination) context.lookup(jndiName);

      messageProducer = session.createProducer(destination);
      initialized = true;
    } catch (Exception e) {
      log.debug(e.getMessage());
      initialized = false;
    }
  }
  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();
    }
  }
  @Test
  public void testReceiveMessageTimeout() throws JMSException {
    JmsMessageReceiver receiver = new JmsMessageReceiver();
    receiver.setConnectionFactory(connectionFactory);

    receiver.setDestination(destination);

    reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    expect(connectionFactory.createConnection()).andReturn(connection).once();
    expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once();
    expect(session.getTransacted()).andReturn(false).once();
    expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once();

    expect(session.createConsumer(destination, null)).andReturn(messageConsumer).once();

    expect(messageConsumer.receive(5000L)).andReturn(null).once();

    connection.start();
    expectLastCall().once();

    replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    try {
      receiver.receive();
    } catch (ActionTimeoutException e) {
      Assert.assertTrue(
          e.getMessage().startsWith("Action timed out while receiving JMS message on"));
      return;
    }

    Assert.fail(
        "Missing " + CitrusRuntimeException.class + " because of receiveing message timeout");
  }
 private void createAndStartConnection(String userName, String password, String url)
     throws JMSException {
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(userName, password, url);
   connection = (ActiveMQConnection) connectionFactory.createConnection();
   connection.start();
   LOG.info("Connected successfully to {}", url);
 }
Beispiel #13
0
  public static void main(String[] args) throws JMSException {
    AsyncSimpleConsumer asyncConsumer = new AsyncSimpleConsumer();

    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    Connection connection = connectionFactory.createConnection();
    connection.start();

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

    Destination destination = session.createQueue(subject);

    MessageConsumer consumer = session.createConsumer(destination);

    consumer.setMessageListener(asyncConsumer);
    connection.setExceptionListener(asyncConsumer);

    try {
      while (true) {
        if (AsyncSimpleConsumer.catchExit) {
          break;
        }
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println("Sleep interrupted");
    }
    connection.close();
  }
    @Override
    public void run() {
      waitForReady();
      try {
        Thread.sleep(new Random().nextInt(200) + 100);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }

      Connection connection = ConnectionFactory.createConnection(brokerIP);
      session = connection.createSession();

      String topicHierarchy = topicHierarchies[id];
      Subscriber subscriber = session.createHierarchicalTopicSubscriber(topicHierarchy);
      System.out.println("create subscriber: " + topicHierarchy);

      messageReceiver = new TestMessageReceiver();
      subscriber.registerMessageReceiver(messageReceiver);

      while (!messageReceiver.shutdown) {
        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
      done();
    }
Beispiel #15
0
  public static void main(String[] args) throws JMSException {
    // Getting JMS connection from the server
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
    Connection connection = connectionFactory.createConnection();
    connection.start();

    // Creating session for seding messages
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Getting the queue 'JMSBEGINQUEUE'
    Destination destination = session.createQueue(subject);

    // MessageConsumer is used for receiving (consuming) messages
    MessageConsumer consumer = session.createConsumer(destination);

    // Here we receive the message.
    // By default this call is blocking, which means it will wait
    // for a message to arrive on the queue.
    Message message = consumer.receive();

    // There are many types of Message and TextMessage
    // is just one of them. Producer sent us a TextMessage
    // so we must cast to it to get access to its .getText()
    // method.
    if (message instanceof TextMessage) {
      TextMessage textMessage = (TextMessage) message;
      System.out.println("Received message '" + textMessage.getText() + "'");
    }
    connection.close();
  }
Beispiel #16
0
  private void sendTextMessage(String msg) throws Exception {
    try (Connection connection = cf.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer publisher = session.createProducer(queue); ) {
      connection.start();

      TextMessage message = session.createTextMessage(msg);
      publisher.send(message);
    }
  }
  public static void main(String args[]) {
    Connection connection = null;

    try {
      // JNDI lookup of JMS Connection Factory and JMS Destination
      Context context = new InitialContext();
      ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
      Destination destination = (Destination) context.lookup(DESTINATION_NAME);

      connection = factory.createConnection();
      connection.start();

      Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
      MessageConsumer consumer = session.createConsumer(destination);

      LOG.info(
          "Start consuming messages from "
              + destination.toString()
              + " with "
              + MESSAGE_TIMEOUT_MILLISECONDS
              + "ms timeout");

      // Synchronous message consumer
      int i = 1;
      while (true) {
        Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
        if (message != null) {
          if (message instanceof TextMessage) {
            String text = ((TextMessage) message).getText();
            LOG.info("Got " + (i++) + ". message: " + text);
          }
        } else {
          break;
        }
      }

      consumer.close();
      session.close();
    } catch (Throwable t) {
      LOG.error("Error receiving message", t);
    } finally {
      // Cleanup code
      // In general, you should always close producers, consumers,
      // sessions, and connections in reverse order of creation.
      // For this simple example, a JMS connection.close will
      // clean up all other resources.
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOG.error("Error closing connection", e);
        }
      }
    }
  }
 protected synchronized Connection getConnection() {
   if (this.connection == null) {
     try {
       Connection connection = ConnectionFactory.createConnection(getConf());
       setConnection(connection);
     } catch (IOException e) {
       LOG.fatal("Failed to establish connection.", e);
     }
   }
   return connection;
 }
  public static void verifyMobRowCount(
      final HBaseTestingUtility util, final TableName tableName, long expectedRows)
      throws IOException {

    Table table = ConnectionFactory.createConnection(util.getConfiguration()).getTable(tableName);
    try {
      assertEquals(expectedRows, countMobRows(table));
    } finally {
      table.close();
    }
  }
Beispiel #20
0
 @Override
 public void start() {
   try {
     connection = connectionFactory.createConnection();
     Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
     messageConsumer = session.createConsumer(schedulerQueue);
     messageConsumer.setMessageListener(this);
     connection.start();
   } catch (JMSException e) {
     e.printStackTrace();
   }
 }
  public void initialise() throws IOException {
    Configuration conf = HBaseConfiguration.create();
    conf.addResource(new Path(clientConfig));
    conf.addResource(new Path("/etc/hadoop/conf/core-site.xml"));

    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation.loginUserFromKeytab(user, keytabLocation);

    System.out.println(conf.toString());

    connection = ConnectionFactory.createConnection(conf);
  }
Beispiel #22
0
  /** Connects to a named queue. */
  public JMSQueue(ConnectionFactory connectionFactory, Destination queue) throws Exception {
    _connection = connectionFactory.createConnection();

    _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    if (queue == null) _destination = _session.createTemporaryQueue();
    else _destination = queue;

    _consumer = _session.createConsumer(_destination);
    _producer = _session.createProducer(_destination);

    _connection.start();
  }
Beispiel #23
0
 public HBaseUtils(
     String quorum,
     boolean useKerberos,
     String keyTabUsername,
     String kerberosEnv,
     String keyTabFileLocation,
     int regions)
     throws IOException {
   this.regions = regions;
   conf.set("hbase.zookeeper.quorum", quorum);
   if (useKerberos) {
     conf.set("hadoop.security.authentication", "Kerberos");
     conf.set("hbase.security.authentication", "Kerberos");
     conf.set("hbase.master.kerberos.principal", "hbase/_HOST@" + kerberosEnv + ".YOURDOMAIN.COM");
     conf.set(
         "hbase.regionserver.kerberos.principal",
         "hbase/_HOST@" + kerberosEnv + ".YOURDOMAIN.COM");
     conf.set("hbase.client.keyvalue.maxsize", "-1");
     UserGroupInformation.setConfiguration(conf);
     try {
       UserGroupInformation.loginUserFromKeytab(
           keyTabUsername + "@" + kerberosEnv + ".YOURDOMAIN.COM", keyTabFileLocation);
       valid = true;
     } catch (IOException e) {
       e.printStackTrace();
       valid = false;
     }
     kerberosRefresher.scheduleAtFixedRate(
         () -> {
           try {
             UserGroupInformation ugi = UserGroupInformation.getLoginUser();
             if (ugi == null) {
               Logger.error("KERBEROS GOT LOGGED OUT");
               UserGroupInformation.loginUserFromKeytab(
                   keyTabUsername + "@" + kerberosEnv + ".YOURDOMAIN.COM", keyTabFileLocation);
             } else {
               ugi.checkTGTAndReloginFromKeytab();
             }
           } catch (IOException e) {
             e.printStackTrace();
           }
         },
         KERBEROS_EXPIRATION_HOURS,
         KERBEROS_EXPIRATION_HOURS,
         TimeUnit.HOURS);
   } else {
     valid = true;
     conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/hbase-unsecure");
   }
   connection = ConnectionFactory.createConnection(conf);
 }
 public static void main(String[] args) throws JMSException {
   String uri = "failover://tcp://103.224.81.184:61616";
   ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(uri);
   Connection connection = connectionFactory.createConnection();
   Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
   Topic topic = session.createTopic("topic1");
   MessageProducer producer = session.createProducer(topic);
   TextMessage textMessage = session.createTextMessage("HelloWorld4");
   producer.send(textMessage);
   connection.start();
   producer.close();
   session.close();
   connection.close();
 }
Beispiel #25
0
  @SuppressWarnings({"unchecked", "static-access"})
  public static synchronized void initConnectionPool() throws SQLException, ClassNotFoundException {
    ConnectionPool.getConnectionPool().destoryConnectionPool();

    @SuppressWarnings("rawtypes")
    Vector temp = ConnectionPool.getConnectionPool().getConnectionPoolBuffer();
    ConnectionFactory connectionFactory = ConnectionFactory.getDefaultFactory();

    for (int i = 0; i < MAX_CONNECTION; i++) {

      Connection connection = connectionFactory.createConnection("mysql");
      temp.addElement(new ConnectionInfo(connection, System.currentTimeMillis()));
      System.out.println("New Connection Created.." + connection);
    }
  }
Beispiel #26
0
  // TextMessage message;
  // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
  public ActiveMQSender(String broker) {
    try {
      connectionFactory =
          new ActiveMQConnectionFactory(
              ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD, broker);
      // 构造从工厂得到连接对象
      connection = connectionFactory.createConnection();
      // 启动
      connection.start();
      /** ********************************** */
    } catch (Exception e) {
      e.printStackTrace();
    } finally {

    }
  }
  @SuppressWarnings("deprecation")
  @Before
  public void setUp() throws Exception {
    HTableDescriptor desc = new HTableDescriptor(tableName);
    HColumnDescriptor hcd = new HColumnDescriptor(family);
    hcd.setMobEnabled(true);
    hcd.setMobThreshold(3L);
    hcd.setMaxVersions(4);
    desc.addFamily(hcd);

    admin = TEST_UTIL.getHBaseAdmin();
    admin.createTable(desc);
    table =
        ConnectionFactory.createConnection(TEST_UTIL.getConfiguration())
            .getBufferedMutator(TableName.valueOf(tableName));
  }
  protected Connection acceptConnection(ServerSocketChannel listener) {
    SocketChannel channel = null;
    try {
      channel = listener.accept();
      if (channel == null) {
        if (log.isDebugEnabled()) {
          log.debug("Psych! Got ACCEPT_READY, but no connection.");
        }
        return null;
      }
      if (!(channel instanceof SelectableChannel)) {
        try {
          log.warn(
              "Provided with un-selectable socket as result of accept(), can't "
                  + "cope [channel="
                  + channel
                  + "].");
        } catch (Error err) {
          log.warn("Un-selectable channel also couldn't be printed.");
        }
        // stick a fork in the socket
        channel.socket().close();
        return null;
      }
      Connection connection = connFactory.createConnection(channel, System.currentTimeMillis());
      if (connection instanceof AuthingableConnection) {
        ((AuthingableConnection) connection).setAuthenticator(this.getAuthenticator());
        ((AuthingableConnection) connection).beforeAuthing();
      }

      if (manager != null) {
        manager.postRegisterNetEventHandler(connection, SelectionKey.OP_READ);
      } else {
        this.postRegisterNetEventHandler(connection, SelectionKey.OP_READ);
      }
      return connection;
    } catch (Exception e) {
      if (channel != null) {
        try {
          channel.socket().close();
        } catch (IOException ioe) {
          log.warn("Failed closing aborted connection: " + ioe);
        }
      }
      return null;
    }
  }
  public void handleRequest(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    PrintWriter out = res.getWriter();

    ConnectionFactory cf;
    Destination dest;

    try {
      Context initCtx = new InitialContext();
      Context envCtx = (Context) initCtx.lookup("java:comp/env");
      cf = (ConnectionFactory) envCtx.lookup("jms/connectionFactory");
      dest = (Destination) envCtx.lookup(QUEUE_NAME);
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }

    Connection connection = null;
    try {
      connection = cf.createConnection();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer producer = session.createProducer(dest);
      TextMessage message = session.createTextMessage();
      for (int i = 0; i < NUM_MSGS; i++) {
        message.setText("This is message " + (i + 1));
        log.info("Sending message: " + message.getText());
        producer.send(message);
      }
      producer.send(session.createTextMessage());

    } catch (JMSException e) {
      throw new RuntimeException(e);
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
        }
      }
    }

    out.write("<p>Wrote " + NUM_MSGS + " to queue " + QUEUE_NAME + " followed by a blank.</p>");
    out.close();
  }
  @Test
  public void testWithMessageSelectorAndCustomTimeout() throws JMSException {
    JmsMessageReceiver receiver = new JmsMessageReceiver();
    receiver.setConnectionFactory(connectionFactory);

    receiver.setDestination(destination);
    receiver.setReceiveTimeout(10000L);

    Map<String, Object> controlHeaders = new HashMap<String, Object>();
    final Message<String> controlMessage =
        MessageBuilder.withPayload("<TestRequest><Message>Hello World!</Message></TestRequest>")
            .copyHeaders(controlHeaders)
            .build();

    Map<String, String> headers = new HashMap<String, String>();

    reset(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    expect(connectionFactory.createConnection()).andReturn(connection).once();
    expect(connection.createSession(anyBoolean(), anyInt())).andReturn(session).once();
    expect(session.getTransacted()).andReturn(false).once();
    expect(session.getAcknowledgeMode()).andReturn(Session.AUTO_ACKNOWLEDGE).once();

    expect(session.createConsumer(destination, "Operation = 'sayHello'"))
        .andReturn(messageConsumer)
        .once();

    connection.start();
    expectLastCall().once();

    expect(messageConsumer.receive(10000L))
        .andReturn(
            new TextMessageImpl(
                "<TestRequest><Message>Hello World!</Message></TestRequest>", headers))
        .once();

    replay(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);

    Message<?> receivedMessage = receiver.receiveSelected("Operation = 'sayHello'");
    Assert.assertEquals(receivedMessage.getPayload(), controlMessage.getPayload());

    verify(jmsTemplate, connectionFactory, destination, connection, session, messageConsumer);
  }