在Jira中集成Bamboo时获取NULL指针异常

时间:2019-02-06 16:28:54

标签: cucumber

尝试与Bamboo和jira集成时,在以下代码中出现错误。
尝试与Bamboo和jira集成时,在以下代码中出现错误。
尝试与Bamboo和jira集成时,在以下代码中出现错误。
尝试与Bamboo和jira集成时,在以下代码中出现错误。
尝试与Bamboo和jira集成时,在以下代码中出现错误。
 / **      *      * /     包com.ntrs.msf.stepDefinitions;

.crt

import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson;
import static org.junit.Assert.assertNull;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.ntrs.msf.commonFunctions.SolaceComponents;
import com.ntrs.msf.dataProvider.ConfigFileReader;
import com.ntrs.msf.globalVariables.CommonVariables;
import com.ntrs.msf.utility.TestUtility;

import cucumber.api.DataTable;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import net.javacrumbs.jsonunit.core.Option;

/**
 * @author ka102
 *
 */

public class MessageStepDefinition {
    private ConfigFileReader configFileReader = new ConfigFileReader();
    private String solaceEnvConfiguration = configFileReader.getSolaceEnvDetails();
    // private SolaceComponents solaceComponents = new SolaceComponents();
    private String solaceQueueInbound;
    private String solaceQueueOutbound;

    private String messageTemplateFileIn;
    private String messageTemplateIn;
    private String messageIn;

    private String messageTemplateFileOut;
    private String messageTemplateOut;
    private String messageOut;

    private String actualMessageOut;

    @Given("^Read the inbound message template file \"([^\"]*)\"$")
    public void readInboundMessageTemplateFile(String messageTemplateFileIn) throws Throwable {
        this.messageTemplateFileIn = messageTemplateFileIn;
        this.messageIn = this.messageTemplateIn = TestUtility.getStringFromPath("/data/" + messageTemplateFileIn);
    }

    @Given("^Read the outbound message template file \"([^\"]*)\"$")
    public void readOutboundMessageTemplateFile(String messageTemplateFileOut) throws Throwable {
        this.messageTemplateFileOut = messageTemplateFileOut;
        this.messageOut = this.messageTemplateOut = TestUtility.getStringFromPath("/data/" + messageTemplateFileOut);
    }

    @Given("^Use the solace inbound queue as \"([^\"]*)\" and outbound queue as \"([^\"]*)\"$")
    public void useSolaceQueues(String inboundQueue, String outboundQueue) throws Throwable {
        this.solaceQueueInbound = inboundQueue;
        this.solaceQueueOutbound = outboundQueue;
        CommonVariables.solaceOutQueue = outboundQueue;
    }

    @When("^Send message to solace inbound queue$")
    public void sendMessageToSolaceInboundQueue() throws Throwable {
        SolaceComponents solaceComponents = new SolaceComponents();
        solaceComponents.createSolaceConnection(solaceEnvConfiguration);
        solaceComponents.createSolaceProducerSession();
        solaceComponents.createQueueInSolace(solaceQueueInbound);
        // Create the message producer for the created queue
        solaceComponents.createMessageProducer();
        // Create a text message.
        solaceComponents.createAndSendTextMessage(messageIn);
        // Close everything in the order reversed from the opening order
        solaceComponents.closeMessageProducer();
        solaceComponents.closeSession();
        solaceComponents.closeConnection();
    }

    @Then("^Receive message from solace outbound queue$")
    public void receiveMessageFromSolaceOutboundQueue() throws Throwable {
        this.actualMessageOut = null;
        // Latch used for synchronising between Main and listener threads
        final CountDownLatch latch = new CountDownLatch(1);
        SolaceComponents solaceComponents = new SolaceComponents();
        solaceComponents.createSolaceConnection(solaceEnvConfiguration);
        solaceComponents.createSolaceConsumerSession();
        solaceComponents.createQueueInSolace(solaceQueueOutbound);
        // From the session, create a consumer for the destination.
        solaceComponents.createMessageConsumer();
        // Start receiving messages
        solaceComponents.startConnection();
        // Use the anonymous inner class for receiving messages asynchronously

        MessageConsumer messageConsumer = solaceComponents.createMessageConsumer();

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {

                    if (message instanceof TextMessage) {
                        actualMessageOut = ((TextMessage) message).getText();
                        System.out.printf("Json Message received from Queue is: '%s'%n", actualMessageOut);
                    } else {
                        throw new Exception("Message received is of wrong type: " + message.getClass());
                    }
                    message.acknowledge();

                } catch (Exception ex) {
                    System.out.println("Error processing incoming message.");
                    ex.printStackTrace();
                } finally {
                    latch.countDown(); // unblock the main thread
                }
            }
        });

        latch.await(20, TimeUnit.SECONDS);
        // Close everything in the order reversed from the opening order
        solaceComponents.closeMessageConsumer();
        solaceComponents.closeSession();
        solaceComponents.closeConnection();
        if (actualMessageOut == null) {
            System.out.println("No message received in Out queue");
            throw new Exception("No message received in Out queue");
        }
    }

    @Then("^Validate no message is received in the outbound queue for (\\d+) seconds$")
    public void validateNoMessageReceivedFromSolaceOutboundQueue(int timeoutInSecs) throws Throwable {
        this.actualMessageOut = null;
        // Latch used for synchronising between Main and listener threads
        final CountDownLatch latch = new CountDownLatch(1);
        SolaceComponents solaceComponents = new SolaceComponents();
        solaceComponents.createSolaceConnection(solaceEnvConfiguration);
        solaceComponents.createSolaceConsumerSession();
        solaceComponents.createQueueInSolace(solaceQueueOutbound);
        // From the session, create a consumer for the destination.
        solaceComponents.createMessageConsumer();
        // Start receiving messages
        solaceComponents.startConnection();
        // Use the anonymous inner class for receiving messages asynchronously

        MessageConsumer messageConsumer = solaceComponents.createMessageConsumer();

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {

                    if (message instanceof TextMessage) {
                        actualMessageOut = ((TextMessage) message).getText();
                        System.out.printf("Json Message received from Queue is: '%s'%n", actualMessageOut);
                    } else {
                        throw new Exception("Message received is of wrong type: " + message.getClass());
                    }
                    message.acknowledge();

                } catch (Exception ex) {
                    System.out.println("Error processing incoming message.");
                    ex.printStackTrace();
                } finally {
                    latch.countDown(); // unblock the main thread
                }
            }
        });

        latch.await(timeoutInSecs, TimeUnit.SECONDS);
        // Close everything in the order reversed from the opening order
        solaceComponents.closeMessageConsumer();
        solaceComponents.closeSession();
        solaceComponents.closeConnection();
        assertNull(actualMessageOut);
    }

    @Given("^Clear outbound queue$")
    public void clearOutboundQueue() throws Throwable {
        System.out.printf("Clearing the out queue...");
        this.actualMessageOut = null;
        // Latch used for synchronising between Main and listener threads
        final CountDownLatch latch = new CountDownLatch(10000);
        SolaceComponents solaceComponents = new SolaceComponents();
        solaceComponents.createSolaceConnection(solaceEnvConfiguration);
        solaceComponents.createSolaceConsumerSession();
        solaceComponents.createQueueInSolace(solaceQueueOutbound);
        // From the session, create a consumer for the destination.
        solaceComponents.createMessageConsumer();
        // Start receiving messages
        solaceComponents.startConnection();
        // Use the anonymous inner class for receiving messages asynchronously

        MessageConsumer messageConsumer = solaceComponents.createMessageConsumer();

        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        actualMessageOut = ((TextMessage) message).getText();
                        System.out.printf("Json Message received from Queue is: '%s'%n", actualMessageOut);
                    }
                    message.acknowledge();

                } catch (Exception ex) {
                    System.out.println("Error processing incoming message.");
                    ex.printStackTrace();
                } finally {
                    latch.countDown(); // unblock the main thread
                }
            }
        });

        latch.await(3000, TimeUnit.SECONDS);
        // Close everything in the order reversed from the opening order
        solaceComponents.closeMessageConsumer();
        solaceComponents.closeSession();
        solaceComponents.closeConnection();
        System.out.printf("Out queue cleared.");
    }

    @Then("^Validate the actual outbound message with the expected one$")
    public void validateActualMessage() throws Throwable {
        assertThatJson(actualMessageOut).isEqualTo(messageOut);
    }

    @Then("^Validate the actual outbound message with the expected one but ignore these paths$")
    public void validateActualMessage(List<String> pathsToIgnore) throws Throwable {
        assertThatJson(actualMessageOut)
                .withConfiguration(c -> c.whenIgnoringPaths(pathsToIgnore.toArray(new String[0])))
                .isEqualTo(messageOut);
    }

    @Then("^Validate the actual outbound message structure with the expected one$")
    public void validateActualMessageStructure() throws Throwable {
        assertThatJson(actualMessageOut).when(Option.IGNORING_VALUES).isEqualTo(messageOut);
    }

    @Then("^Validate the actual outbound message structure with the expected one but ignore these paths$")
    public void validateActualMessageStructure(List<String> pathsToIgnore) throws Throwable {
        assertThatJson(actualMessageOut).when(Option.IGNORING_VALUES)
                .withConfiguration(c -> c.whenIgnoringPaths(pathsToIgnore.toArray(new String[0])))
                .isEqualTo(messageOut);
    }

    @Then("^Validate the actual outbound message has at least 1 element$")
    public void validateActualMessageOneElement(List<String> fieldsToTest) throws Throwable {
        // Iterate through all fields that need to be tested
        for (String fieldToTest : fieldsToTest) {
            assertThatJson(actualMessageOut).node(fieldToTest).isArray().isNotEmpty();
        }
    }

    @When("^Update following fields in the inbound xml message$")
    public void updateInboundXmlMessage(DataTable fieldsToUpdate) throws Throwable {
        // 1- Build the doc from the inbound XML message
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new StringReader(this.messageIn)));

        // 2 - Iterate through all fields that need to be updated and update them in the
        // doc object
        for (Map<String, String> fieldToUpdate : fieldsToUpdate.asMaps(String.class, String.class)) {
            String fieldName = fieldToUpdate.get("Field");
            String fieldValue = fieldToUpdate.get("Value");

            // 3- Locate the node(s) with xpath
            XPath xpath = XPathFactory.newInstance().newXPath();
            NodeList nodes = (NodeList) xpath.evaluate(fieldName, doc, XPathConstants.NODESET);

            // 4- Make the change on the selected nodes
            for (int i = 0; i < nodes.getLength(); i++) {
                Node selectedNode = nodes.item(i);
                selectedNode.setTextContent(fieldValue);
            }
        }

        // 5- Save the result to a new XML doc once all changes have been made
        StringWriter writer = new StringWriter();
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(new DOMSource(doc), new StreamResult(writer));
        this.messageIn = writer.getBuffer().toString();
    }

    @When("^Update following fields in the expected json message$")
    public void updateExpectedJsonMessage(DataTable fieldsToUpdate) throws Throwable {
        DocumentContext doc = JsonPath.parse(this.messageOut);

        for (Map<String, String> fieldToUpdate : fieldsToUpdate.asMaps(String.class, String.class)) {
            String fieldName = fieldToUpdate.get("Field");
            String fieldValue = fieldToUpdate.get("Value");
            doc.set(fieldName, fieldValue);
        }
        this.messageOut = doc.jsonString();
    }

    public void resetInboundMessage() {
        this.messageIn = this.messageTemplateIn;
    }

    public void resetOutboundMessage() {
        this.messageOut = this.messageTemplateOut;
    }

//Load testing functionality

    @Then("^producer send message to Solace In queue in loop till (\\d+)$")
    public void sendMessageToSolaceInboundQueueInloop(int i) throws Throwable {
        CommonVariables.count=i;
        SolaceComponents solaceComponents = new SolaceComponents();           
        solaceComponents.createSolaceConnection(solaceEnvConfiguration);
        solaceComponents.createSolaceProducerSession();
        solaceComponents.createQueueInSolace(solaceQueueInbound);
        // Create the message producer for the created queue
        solaceComponents.createMessageProducer();
        // Xml Message
        //String xmlMessage = fileReader.readFile(CommonVariables.xmlFileName);
        for(int j=1;j<=i;j++) {
                  // Create a text message.
                  solaceComponents.createAndSendTextMessage(messageIn);
                  Thread.sleep(500);
                  // Close everything in the order reversed from the opening order
                  System.out.println("No of messages sent"+j);
        }
                  solaceComponents.closeMessageProducer();
                  solaceComponents.closeSession();
                  solaceComponents.closeConnection();

    }

}

/**
 *
 */
package com.ntrs.msf.commonFunctions;

import java.util.concurrent.CountDownLatch;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import com.ntrs.msf.dataProvider.ConfigFileReader;
import com.ntrs.msf.globalVariables.CommonVariables;
import com.solacesystems.jms.SolConnectionFactory;
import com.solacesystems.jms.SolJmsUtility;
import com.solacesystems.jms.SupportedProperty;

/**
 * @author sd466 22 Aug 2018 11:31:32
 */
public class SolaceComponents {
    public static Connection connection;
    public static Session session;
    public static Queue queue;
    public static MessageProducer messageProducer;
    public static MessageConsumer messageConsumer;
    ConfigFileReader configFileReader = new ConfigFileReader();
    public GlobalVariables globalVariablesJson = new GlobalVariables();

    // Programmatically create the connection factory using default settings
    public void createSolaceConnection(String systemEnvDetail) throws Exception {
        String[] detail = systemEnvDetail.split("\\|");
        String host = detail[0];
        String vpn = detail[1];
        String userName = detail[2];
        System.out.printf("QueueConsumer is connecting to Solace messaging at %s...%n", host);
        SolConnectionFactory connectionFactory = SolJmsUtility.createConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setVPN(vpn);
        connectionFactory.setUsername(userName);
        // Enables persistent queues or topic endpoints to be created dynamically
        // on the router, used when Session.createQueue() is called below
        connectionFactory.setDynamicDurables(false);
        // Create connection to the Solace router
        connection = connectionFactory.createConnection();

    }

    public void createSolaceConnectionTHB(String systemEnvDetailthb) throws Exception {
        String[] detail = systemEnvDetailthb.split("\\|");
        String host = detail[0];
        String vpn = detail[1];
        String userName = detail[2];
        System.out.printf("QueueConsumer is connecting to Solace messaging at %s...%n", host);
        SolConnectionFactory connectionFactory = SolJmsUtility.createConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setVPN(vpn);
        connectionFactory.setUsername(userName);
        // Enables persistent queues or topic endpoints to be created dynamically
        // on the router, used when Session.createQueue() is called below
        connectionFactory.setDynamicDurables(false);
        // Create connection to the Solace router
        connection = connectionFactory.createConnection();

    }

    public void createSolaceProducerSession() throws JMSException {
        // Create a non-transacted, auto ACK session.
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }

    public void createSolaceConsumerSession() throws JMSException {
        // Create a non-transacted, auto ACK session.
        session = connection.createSession(false, SupportedProperty.SOL_CLIENT_ACKNOWLEDGE);
    }

    public void createQueueInSolace(String queueName) throws JMSException {
        // Create the queue programmatically and the corresponding router resource
        // will also be created dynamically because DynamicDurables is enabled.
        queue = session.createQueue(queueName);
    }

    public void createMessageProducer() throws JMSException {
        // Create the message producer for the created queue
        messageProducer = session.createProducer(queue);
    }

    public MessageConsumer createMessageConsumer() throws JMSException {
        return messageConsumer = session.createConsumer(queue);
    }

    public void createAndSendTextMessage(String xmlMessage) throws JMSException {
        // Create a text message.
        TextMessage message = session.createTextMessage(xmlMessage);
        // ObjectMessage message = session.createObjectMessage(xmlMessage);

        System.out.printf("Sending message '%s'", xmlMessage);

        // Send the message
        // NOTE: JMS Message Priority is not supported by the Solace Message Bus
        messageProducer.send(queue, message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY,
                Message.DEFAULT_TIME_TO_LIVE);
        System.out.println("Sent successfully. Exiting...");
    }

    public void startConnection() throws JMSException {
        connection.start();
    }

    public void stopConnection() throws JMSException {
        connection.stop();
    }

    public void readMessageFromSolace() throws JMSException {
        final CountDownLatch latch = new CountDownLatch(1);
        messageConsumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        CommonVariables.outputMessageJson = ((TextMessage) message).getText();
                        System.out.printf("Json Message received from Queue is: '%s'%n",
                                CommonVariables.outputMessageJson);
                    }
                    System.out.printf("Message Content:%n%s%n", SolJmsUtility.dumpMessage(message));

                    // String bytesXMLMessage = SolJmsUtility.dumpMessage(message);

                    // ACK the received message manually because of the set
                    // SupportedProperty.SOL_CLIENT_ACKNOWLEDGE above
                    message.acknowledge();

                    latch.countDown(); // unblock the main thread
                } catch (JMSException ex) {
                    System.out.println("Error processing incoming message.");
                    ex.printStackTrace();
                }
            }
        });

    }

    public void closeMessageProducer() throws JMSException {
        messageProducer.close();
    }

    public void closeMessageConsumer() throws JMSException {
        messageConsumer.close();
    }

    public void closeSession() throws JMSException {
        session.close();
    }

    public void closeConnection() throws JMSException {
        connection.close();
    }

}

package com.ntrs.msf.utility;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.parser.ParseException;

/**
 * This class has been designed to provide utility services for running test
 * cases.
 * 
 * @author ad364
 */
public class TestUtility {

    public static final JSONParser parser = new JSONParser(1);

    public static JSONObject getJSONFromPath(String path)
            throws FileNotFoundException, ParseException, UnsupportedEncodingException {

        Object obj = parser.parse(new BufferedReader(
                new InputStreamReader((new TestUtility()).getClass().getResourceAsStream(path), "UTF-8")));
        return (JSONObject) obj;
    }

    public static String getStringFromPath(String path) throws ParseException, IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(TestUtility.class.getResourceAsStream(path)));

        StringBuilder builder = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            builder.append(line);
        }

        return builder.toString();
    }

    /**
     * @param pathParams
     * @param requestValues
     */
    public static void appendPathParam(Map<String, String> pathParams, StringBuilder requestValues, String field) {

        if (StringUtils.isEmpty(pathParams.get(field))) {
            requestValues.append(field).append("=").append(pathParams.get(field)).append("&");
        }
    }

}

0 个答案:

没有答案