Как создать сеанс Hermes вручную в проекте Java при импорте проекта SOAP, который подключается к JMS MQ

Я создал проект SoapUI, который соединяется с очередью сообщений и отправляет в нее сообщение JMS. Для соединения с MQ я использовал инструмент HERMES, который предоставляет SoapUI. В настоящее время я использую Hermes v1.14.

Я создал требуемый сеанс и соответствующие очереди в конце Hermes и отправил сообщение JMS после выполнения шагов, как показано здесь: https://www.soapui.org/documentation/jms/config.html, https://www.soapui.org/jms/working-with-jms-messages.html

Это все отлично работает.

Сейчас я пытаюсь включить этот проект SOAPUI в проект Java, в котором я предоставлю проект XML и запустим все необходимые тестовые случаи. Я не могу создать сеанс и очереди HERMES и т. Д. С помощью кода Java. Ниже приведены некоторые фрагменты кода из класса. Я на правильном пути? Нужна помощь, чтобы настроить это.

TestRunner runner = null;
SoapUI.setSoapUICore(new StandaloneSoapUICore(true));
WsdlProject project = new WsdlProject("C:\\My Directory\\CustomerTest-soapui-project.xml");
List<TestSuite> suiteList = project.getTestSuiteList();

String defaultHermesJMSPath= HermesUtils.defaultHermesJMSPath();
System.out.println("defaultHermesJMSPath- "+defaultHermesJMSPath);

String soapUiHome = System.getProperty("soapui.home");
System.out.println("soapUiHome - "+soapUiHome);

//System.setProperty("soapui.home", "C:\\Program Files\\SmartBear\\SoapUI-5.2.1\\bin");

TestRunner runner = project.getTestSuiteByName("Private Individual").getTestCaseByName(
"TEST CASE CONTAINING GROOVY SCRIPT TEST STEPTHAT CONNECTS TO HERMES").run
(new PropertiesMap(), false);

Выход:

defaultHermesJMSPath - null
soapuiHome - null

PS Для этого я включил несколько JAR-файлов:

Любая помощь будет оценена.

1 ответ

Решение

Основной проблемой для этого вопроса было создание SOAP-проекта, который в конечном итоге был бы независим от графического интерфейса HERMES для настройки сеанса, очередей и т. Д. В итоге я создал объекты для MQQueueConnectionFactory, QueueConnection, QueueSession, MQQueue, MQQueueSender, JMSTextMessage на моем шаге теста GROOVY и отправил сообщение JMS в очередь. Таким образом, не было необходимости открывать интерфейс Hermes и настраивать его там. Ниже приведен пример кода, которому можно следовать.

  def stringBuilder=context.expand('${CustomerXmlsAndCdbs#MasterXmlPrivateIndividual}');
  MQQueueConnectionFactory cf = new MQQueueConnectionFactory()
  cf.setHostName(context.expand('${#Project#HostName}'));
  cf.setPort(Integer.parseInt(context.expand('${#Project#Port}')))
  cf.setQueueManager(context.expand('${#Project#QueueManager}'))
  cf.setTransportType(Integer.parseInt(context.expand('${#Project#TransportType}')))
  QueueConnection queueConn = cf.createQueueConnection("retapp","retapp")
  QueueSession queueSession = queueConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE)

  MQQueue queue = (MQQueue) queueSession.createQueue(context.expand('${#Project#QueueName}').toString())

  MQQueueSender sender = (MQQueueSender) queueSession.createSender(queue)
  JMSTextMessage message = (JMSTextMessage) queueSession.createTextMessage(stringBuilder.toString())
  sender.send(message)
  sender.close()
  queueSession.close()
  queueConn.close()

Следующие зависимости должны уже существовать в папке SoapUI Lib (\ SoapUI-5.2.1 \ lib) и Hermes Lib (\ SoapUI-5.2.1 \ hermesJMS \ lib):

com.ibm.dhbcore.jar, com.ibm.mq.jar, com.ibm.mq.pcf.jar, com.ibm.mqjms.jar, connector.jar, javax.transaction.jar

Это просто, вы должны создать временные очереди для получения ответа.

    import javax.jms.*;
    import java.util.Enumeration;

    public class JMSExample5 {

protected static final String SERVICE_QUEUE = "QUEUE_NAME_THAT_IS_CREDTED_IN_SERVER_FOR_ACCEPTING";
static String serverUrl = "tcp://10.xxx.xxx.xxx:xxxxx";
static String userName = "UR_UserID";
static String password = "UR_Pass";

public static void sendTopicMessage(String topicName, String messageStr) {

    Connection connection = null;
    Session session = null;
    MessageProducer msgProducer = null;
    Destination destination = null;

    try {
        TextMessage msg;
        System.out.println("Publishing to destination '" + topicName
                + "'\n");
        ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(serverUrl);
        connection = factory.createConnection(userName, password);
        connection.start();
        session = connection
                .createSession(false,javax.jms.Session.AUTO_ACKNOWLEDGE);
        TemporaryQueue tempQueue = session.createTemporaryQueue();

        TextMessage message_t = session.createTextMessage(messageStr);
        //This step is compulsory to get the reply from JMS server
        message_t.setJMSReplyTo(tempQueue);
        MessageProducer producer = session.createProducer(session.createQueue(SERVICE_QUEUE));
        producer.send(message_t);

        System.out.println("INFO::  The producer has sent the message"+message_t);
        Destination dest = tempQueue;

        MessageConsumer consumer = session.createConsumer(dest);
        Message replyMsg = consumer.receive();
        TextMessage tm = (TextMessage) replyMsg;
        System.out.println("INFO The response is "+ replyMsg);
        consumer.close();
        producer.close();
        session.close();
        connection.close();

    } catch (JMSException e) {
         System.out.println("Error :: there was exception"+e);
        e.printStackTrace();
    }
}

/*-----------------------------------------------------------------------
 * main
 *----------------------------------------------------------------------*/
public static void main(String[] args) {
    JMSExample5.sendTopicMessage(SERVICE_QUEUE,
            "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n" +
                    "<MYServices>\n" +
                    " <header>\n" +
                    "  <Version>1.0</Version>\n" +
                    "  <SrvType>OML</SrvType>\n" +
                    "  <SrvName>REQ_BALANCE_ENQUIRY</SrvName>\n" +
                    "  <SrcApp>BNK</SrcApp>\n" +
                    "  <OrgId>BLA</OrgId>\n" +
                    " </header>\n" +
                    " <body>\n" +
                    "  <srv_req>\n" +
                    "   <req_credit_card_balance_enquiry>\n" +
                    "    <card_no>12345678</card_no>\n" +
                    "   </req_credit_card_balance_enquiry>\n" +
                    "  </srv_req>\n" +
                    " </body>\n" +
                    "</MYServices>\n");
}

}

Другие вопросы по тегам