sunil gogula
sunil gogula

Reputation: 41

Unable to send Messages to Queues through Java Main Program

I am calling the sendMessage function from Main method and it gives Null Pointer Exception while creating the object Queue (this.queue).

Main method:

public void start()
    {
        AuthorisationServiceImpl authorisationServiceImpl = new AuthorisationServiceImpl();
        try {
            authorisationServiceImpl.fromMain();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws InterruptedException {
        System.out.println("Starting Client Application");
        AbstractApplicationContext context = new FileSystemXmlApplicationContext("resources/applicationContext.xml");
        System.out.println("Spring context loaded.");
        context.registerShutdownHook();
        System.out.println("ShutdownHook registered.");

        MainTestClient mainTestClient = new MainTestClient();
        mainTestClient.start();



    }

And the method that i am calling in another class is

public class AuthorisationServiceImpl {

    @Autowired
    private MessageSender messageSender;


    private MessageReceiver messageReceiver;

    private JmsTemplate jmsTemplate;
    private Queue queue;


    public JmsTemplate getJmsTemplate() {
        return jmsTemplate;
    }



    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }



    public Queue getQueue() {
        return queue;
    }



    public void setQueue(Queue queue) {
        this.queue = queue;
    }



    public MessageReceiver getMessageReceiver() {
        return messageReceiver;
    }



    public void setMessageReceiver(MessageReceiver messageReceiver) {
        this.messageReceiver = messageReceiver;
    }

    private ConfigProperties configProperties;


    public void fromMain() throws InterruptedException {
        System.out.println("Init method called");
        String message = "AAA-MM-CCC";
        long count = new Long("000001").longValue();
        while (true)
        {
            //container.start();
            StringBuffer corelationId = new StringBuffer();

            if (count == 1000000) {
                count = new Long("000001").longValue();
            }

            corelationId.append(message);
            corelationId.append(String.format("%6s", String.valueOf(count)).replace(' ', '0'));
            byte[] myvar = "Message".getBytes();
            System.out.println("Writing message having correlationId: " + corelationId.toString() + " to the queue.");
            sendMessage(corelationId.toString(),myvar);
            count++;
            Thread.sleep(5000);
        }


    }



    /*public boolean sendMessage(String correlationId) throws ServiceException {
        byte[] myvar = "Message".getBytes();
        boolean response = false;
        try {
            MessageSender messageSenderVar = new MessageSender();
            System.out.println("Writing message having correlationId: " + correlationId + " to the queue.");
            // writing message to the request queue. 
            sendMessage(correlationId,myvar);
            //messageReceiver.getMessage();

        }catch(Exception e) {

            throw new ServiceException("Exception:",e);
        }
        return response;
    }
    */
    public void sendMessage(final String correlationId, final byte[] bytes) {
        this.jmsTemplate.send(this.queue, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                BytesMessage bytesMessage = session.createBytesMessage();
                bytesMessage.setJMSCorrelationID(configProperties.getPREFIX_VALUE() + correlationId);

                // message will follow expiration time as configured in properties
                bytesMessage.writeBytes(bytes);
                return bytesMessage;
            }
        });
        System.out.println("Message " + configProperties.getPREFIX_VALUE() + correlationId + " with correlation id: " + configProperties.getPREFIX_VALUE() + correlationId + " written to the queue.");
    }



    public MessageSender getMessageSender() {
        return messageSender;
    }

    public void setMessageSender(MessageSender messageSender) {
        this.messageSender = messageSender;
    }



    public ConfigProperties getConfigProperties() {
        return configProperties;
    }

    public void setConfigProperties(ConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

}

I am getting Null Pointer Exception while calling sendMessage Method. Is there any problem in calling the non static methods from Static Method?

Starting Client Application
Nov 23, 2015 12:49:53 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.FileSystemXmlApplicationContext@5ba28182: startup date [Mon Nov 23 12:49:53 UTC 2015]; root of context hierarchy
Nov 23, 2015 12:49:53 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from file [/app/dev-data/node1/support/tactical_tools/gwatest/client1/resources/applicationContext.xml]
Nov 23, 2015 12:49:54 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from URL [file:resources/config.properties]
Nov 23, 2015 12:49:54 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6b915330: defining beans [propertyConfigurer,configProperties,jndiTemplate,connectionFactory,paymentRequestQueue,paymentResponseQueue,jmsTemplate,messageSender,authorisationResponseHandler,authorisationServiceImpl,jmsContainer]; root of factory hierarchy
Nov 23, 2015 12:49:55 PM org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup start
INFO: Starting beans in phase 2147483647
Spring context loaded.
ShutdownHook registered.
Init method called
Writing message having correlationId: AAA-MM-CCC000001 to the queue.
Exception in thread "main" java.lang.NullPointerException
        at aero.sita.uatp.client.AuthorisationServiceImpl.sendMessage(AuthorisationServiceImpl.java:114)
        at aero.sita.uatp.client.AuthorisationServiceImpl.fromMain(AuthorisationServiceImpl.java:86)
        at aero.sita.uatp.client.MainTestClient.start(MainTestClient.java:15)
        at aero.sita.uatp.client.MainTestClient.main(MainTestClient.java:31)

When i call the sendMessage Normally without Main Method then i am able to connect successfully. And i am using the Spring ApplicationContext to initialize queues as below

<!-- Config property -->
<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>file:resources/config.properties</value>
        </list>
    </property>
    <property name="ignoreUnresolvablePlaceholders" value="true" />
    <property name="order" value="0" />
</bean>

<!-- App config properties -->

<bean id="configProperties" class="aero.sita.uatp.server.utilities.ConfigProperties">
    <property name="properties">
        <props>
                    <prop key="prefix.correlation">${prefix.correlation}</prop>
        </props>
    </property>
</bean>


<!-- jndi Template -->
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">${broker.initialContexFactory}</prop>
            <prop key="java.naming.provider.url">${broker.provide.url}</prop>
        </props>
    </property>
</bean>

<!-- JMS Connection factory -->
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
        <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
        <value>${broker.connectionFactory}</value>
    </property>
</bean>

<!-- Auth (Payment) Request queue -->
<bean id="paymentRequestQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
        <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
        <value>${payment.request}</value>
    </property>
</bean>

<!-- Auth (Payment) Response queue -->
<bean id="paymentResponseQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate">
        <ref bean="jndiTemplate" />
    </property>
    <property name="jndiName">
        <value>${payment.response}</value>
    </property>
</bean>

<!-- JMS Template -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="explicitQosEnabled" value="true" />
    <property name="timeToLive" value="${payment.request.expiration}" />
    <property name="receiveTimeout" value="${payment.response.receive.timeout}" />
</bean>

<bean id="messageSender" class="aero.sita.uatp.server.MessageSender">
    <property name="jmsTemplate" ref="jmsTemplate" />
    <property name="queue" ref="paymentResponseQueue" />
    <property name="configProperties" ref="configProperties" />
</bean>

<bean id="authorisationServiceImpl" class="aero.sita.uatp.server.AuthorisationServiceImpl">
    <property name="messageSender" ref="messageSender" />
    <property name="configProperties" ref="configProperties" />
</bean>


<bean id="authorisationResponseHandler" class="aero.sita.uatp.server.AuthorisationResponseHandler">
    <property name="configProperties" ref="configProperties" />
    <property name="messageSender" ref="messageSender" />
</bean>



<!-- and this is the message listener container -->

<bean id="jmsContainer" class="org.springframework.jms.listener.SimpleMessageListenerContainer">
    <property name="autoStartup" value="TRUE" />
    <property name="connectionFactory" ref="connectionFactory" />
    <property name="destination" ref="paymentRequestQueue" />
    <property name="messageListener" ref="authorisationResponseHandler" />

</bean>

Upvotes: 0

Views: 896

Answers (1)

Zilvinas
Zilvinas

Reputation: 5578

You are getting a NullPointerException when trying to invoke this.jmsTemplate.send(...) method, because your jmsTemplate variable is NULL, or never initialized. One more thing is that you are not using the spring bean authorisationServiceImpl, but you are instantiating the class manually.

First you need to set the jmsTemplate in your bean:

<bean id="authorisationServiceImpl" class="aero.sita.uatp.server.AuthorisationServiceImpl">
    <property name="jmsTemplate" ref="jmsTemplate" />
    <property name="messageSender" ref="messageSender" />
    <property name="configProperties" ref="configProperties" />
</bean>

Second you should not instantiate the class:

AuthorisationServiceImpl authorisationServiceImpl = new AuthorisationServiceImpl();
try {
    authorisationServiceImpl.fromMain();
} 

But get it from application context, that you have just created

AuthorisationServiceImpl authorisationServiceImpl = context.getBean("authorisationServiceImpl", AuthorisationServiceImpl.class );

Upvotes: 3

Related Questions