How to avoid casting to a JAXBElement while making a SOAP webservice call? - spring

I am having a spring boot java application. I am calling a soap web service using spring webservice template . the webservice call always return a JAXBElement. the following is my code snippet.
JAXBElement<ItemResponse> itemResponse = (JAXBElement<ItemResponse> ) getWebServiceTemplate().marshalSendAndReceive(
this.cconfServiceConfiguration.getServices().getLocation(), itemRequest,
new SoapActionCallback(this.cconfServiceConfiguration.getServices().getGetItemAction()));
return itemResponse.getValue();
The marshalSendAndReceive returns a JAXBElement. Is there any way i can rewrite the code so that it will return an Object of ItemResponse so that i can avoid casting.
The following is the ItemResponse class declaration.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "ItemResponse", propOrder = {
"result",
"item"
})
public class ItemResponse {
#XmlElement(required = true)
protected Result result;
protected Item item;
/**
* Gets the value of the result property.
*
* #return
* possible object is
* {#link Result }
*
*/
public Result getResult() {
return result;
}
/**
* Sets the value of the result property.
*
* #param value
* allowed object is
* {#link Result }
*
*/
public void setResult(Result value) {
this.result = value;
}
/**
* Gets the value of the item property.
*
* #return
* possible object is
* {#link Item }
*
*/
public Item getItem() {
return item;
}
/**
* Sets the value of the item property.
*
* #param value
* allowed object is
* {#link Item }
*
*/
public void setItem(Item value) {
this.item = value;
}
}
really appreciate if you can throw some information

Related

How to pass arguments to a mocked class constructor

I have one method (getUsers()) in my class that I would like to mock but I have a constructor in my class. How can I pass values to the constructor when mocking my class?
class MyNotifications {
/**
* Date time.
*
* #var DateTime|mixed|null
*/
public $date;
public function __construct($date = NULL)
{
if (!$date) {
$date = new \DateTime();
}
$this->date = $date;
}
/**
* Get users.
*
* #param int $node_id
* Node id.
*
* #return mixed
* #throws \GuzzleHttp\Exception\GuzzleException
*/
public function getUsers($node_id)
{
// API code goes here.
}
/**
* Get day.
*
* #return false|int|string
*/
public function getDay()
{
return $this->date->format('d');
}
}
class MyNotificationsTest extends TestCase
{
use RefreshMigrations;
public function testOneDay()
{
$mock = $this->getMockBuilder(MyNotifications::class)->onlyMethods([
'getUsers',
])->getMock();
$mock->method('getUsers')->willReturn(['User 1']);
dump($mock->getDay());
dump($mock->getUsers(1));
}
}
For example, I would like to pass the date "2021-12-22" to the constructor so the getDay() method returns 22 instead of the current day.
I haven't used PHPUnit mocks before (usually defaulting to Mockery) but looking at the documentation are you able to call setConstructorArgs(array $args) on the getMockBuilder?
class MyNotificationsTest extends TestCase
{
use RefreshMigrations;
public function testOneDay()
{
$mock = $this->getMockBuilder(MyNotifications::class)
->onlyMethods([
'getUsers',
])
->setConstructorArgs(['2021-03-08'])
->getMock();
$mock->method('getUsers')->willReturn(['User 1']);
dump($mock->getDay());
dump($mock->getUsers(1));
}
}

Synchronous Message send and receive using JMS template and Spring Boot

I am after sending/receiving call to JMS queue synchronously using JMS Template and Spring boot. I went through official spring doc for JMS template but of no help.
I am not too sure about calling receive() method specifically or it will automatically receive message once send() is invoked. Since this is synchronous call I only need to receive message that I've sent (with the correlation Id).
Any help in this regard would be appreciated. Please let me know if you need any further info.
Update!!
Below is my spring boot code.
JMSSConfig.java
#Configuration
#EnableJms
public class JMSConfig {
#Bean
public JmsListenerContainerFactory<?> myFactory(ConnectionFactory connectionFactory, DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
// This provides all boot's default to this factory, including the message converter
configurer.configure(factory, connectionFactory);
// You could still override some of Boot's default if necessary.
return factory;
}
#Bean
public MarshallingMessageConverter createMarshallingMessageConverter(final Jaxb2Marshaller jaxb2Marshaller) {
System.out.println("executing createMarshallingMessageConverter");
return new MarshallingMessageConverter(jaxb2Marshaller);
}
#Bean
public Jaxb2Marshaller createJaxb2Marshaller(#Value("${context.path}") final String contextPath, #Value("${schema.location}") final String schemaLocaation) {
System.out.println("executing Jaxb2Marshaller");
Resource schemaResource = new ClassPathResource(schemaLocaation);
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPath(contextPath);
jaxb2Marshaller.setSchema(schemaResource);
Map<String, Object> properties = new HashMap<>();
properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxb2Marshaller.setMarshallerProperties(properties);
return jaxb2Marshaller;
}
}
Sender and receiver code
#Component
public class Receiver {
#Autowired
JmsTemplate jmsTemplate;
#JmsListener(destination = "mailbox", containerFactory="myFactory")
public void receiveMessage(CacheMsgType submitEventType) {
System.out.println("Received <" + submitEventType + ">");
}
public void send(CacheMsgType submitEventType) {
jmsTemplate.convertAndSend("mailbox", submitEventType);
System.out.println("Successfully sent a message.");
}
}
JAXB Generated classes
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "SubmitEventType", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", propOrder = {
"eventType",
"clientApplication",
"clientReferenceID",
"systemDate",
"transactionAcceptTime",
"bsb",
"accountNumber",
"productcode",
"accttypecode",
"trancode",
"meid",
"baiCode",
"baiDecs",
"tranamount",
"amountonhold",
"recordedlimit",
"currentbalance",
"availablebalance",
"description",
"reference",
"payer"
})
public class SubmitEventType {
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String eventType;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String clientApplication;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String clientReferenceID;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String systemDate;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String transactionAcceptTime;
#XmlElement(name = "BSB", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String bsb;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String accountNumber;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String productcode;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String accttypecode;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String trancode;
#XmlElement(name = "MEID", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String meid;
#XmlElement(name = "BAICode", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String baiCode;
#XmlElement(name = "BAIDecs", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String baiDecs;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String tranamount;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String amountonhold;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String recordedlimit;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String currentbalance;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String availablebalance;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String description;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String reference;
#XmlElement(namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected String payer;
/**
* Gets the value of the eventType property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getEventType() {
return eventType;
}
/**
* Sets the value of the eventType property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setEventType(String value) {
this.eventType = value;
}
/**
* Gets the value of the clientApplication property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getClientApplication() {
return clientApplication;
}
/**
* Sets the value of the clientApplication property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setClientApplication(String value) {
this.clientApplication = value;
}
/**
* Gets the value of the clientReferenceID property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getClientReferenceID() {
return clientReferenceID;
}
/**
* Sets the value of the clientReferenceID property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setClientReferenceID(String value) {
this.clientReferenceID = value;
}
/**
* Gets the value of the systemDate property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getSystemDate() {
return systemDate;
}
/**
* Sets the value of the systemDate property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setSystemDate(String value) {
this.systemDate = value;
}
/**
* Gets the value of the transactionAcceptTime property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getTransactionAcceptTime() {
return transactionAcceptTime;
}
/**
* Sets the value of the transactionAcceptTime property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setTransactionAcceptTime(String value) {
this.transactionAcceptTime = value;
}
/**
* Gets the value of the bsb property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getBSB() {
return bsb;
}
/**
* Sets the value of the bsb property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setBSB(String value) {
this.bsb = value;
}
/**
* Gets the value of the accountNumber property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getAccountNumber() {
return accountNumber;
}
/**
* Sets the value of the accountNumber property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setAccountNumber(String value) {
this.accountNumber = value;
}
/**
* Gets the value of the productcode property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getProductcode() {
return productcode;
}
/**
* Sets the value of the productcode property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setProductcode(String value) {
this.productcode = value;
}
/**
* Gets the value of the accttypecode property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getAccttypecode() {
return accttypecode;
}
/**
* Sets the value of the accttypecode property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setAccttypecode(String value) {
this.accttypecode = value;
}
/**
* Gets the value of the trancode property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getTrancode() {
return trancode;
}
/**
* Sets the value of the trancode property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setTrancode(String value) {
this.trancode = value;
}
/**
* Gets the value of the meid property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getMEID() {
return meid;
}
/**
* Sets the value of the meid property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setMEID(String value) {
this.meid = value;
}
/**
* Gets the value of the baiCode property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getBAICode() {
return baiCode;
}
/**
* Sets the value of the baiCode property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setBAICode(String value) {
this.baiCode = value;
}
/**
* Gets the value of the baiDecs property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getBAIDecs() {
return baiDecs;
}
/**
* Sets the value of the baiDecs property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setBAIDecs(String value) {
this.baiDecs = value;
}
/**
* Gets the value of the tranamount property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getTranamount() {
return tranamount;
}
/**
* Sets the value of the tranamount property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setTranamount(String value) {
this.tranamount = value;
}
/**
* Gets the value of the amountonhold property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getAmountonhold() {
return amountonhold;
}
/**
* Sets the value of the amountonhold property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setAmountonhold(String value) {
this.amountonhold = value;
}
/**
* Gets the value of the recordedlimit property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getRecordedlimit() {
return recordedlimit;
}
/**
* Sets the value of the recordedlimit property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setRecordedlimit(String value) {
this.recordedlimit = value;
}
/**
* Gets the value of the currentbalance property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getCurrentbalance() {
return currentbalance;
}
/**
* Sets the value of the currentbalance property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setCurrentbalance(String value) {
this.currentbalance = value;
}
/**
* Gets the value of the availablebalance property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getAvailablebalance() {
return availablebalance;
}
/**
* Sets the value of the availablebalance property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setAvailablebalance(String value) {
this.availablebalance = value;
}
/**
* Gets the value of the description property.
*
* #return
* possible object is
* {#link String }
*
*/
public String getDescription() {
return description;
}
/**
* Sets the value of the description property.
*
* #param value
* allowed object is
* {#link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
public String getReference() {
return reference;
}
public void setReference(String value) {
this.reference = value;
}
public String getPayer() {
return payer;
}
public void setPayer(String value) {
this.payer = value;
}
}
CashMsgType.java
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "CacheMsg", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "CacheMsgType", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", propOrder = {
"submitEvent"
})
public class CacheMsgType {
#XmlElement(name = "SubmitEvent", namespace = "nabgroup.com/nab/schema/PaymentsExecution/SubmitPaymentEvent", required = true)
protected List<SubmitEventType> submitEvent;
public List<SubmitEventType> getSubmitEvent() {
if (submitEvent == null) {
submitEvent = new ArrayList<SubmitEventType>();
}
return this.submitEvent;
}
}
It seems sending on to mailbox queue is working but receiving gives error
Exception
2018-05-05 10:44:53.280 WARN 4120 --- [enerContainer-1] o.s.j.l.DefaultMessageListenerContainer : Execution of JMS message listener failed, and no ErrorHandler has been set.
org.springframework.jms.listener.adapter.ListenerExecutionFailedException: Listener method could not be invoked with incoming message
Endpoint handler details:
Method [public void com.nab.services.mq.Receiver.receiveMessage(com.nab.services.dto.CacheMsgType)]
Bean [com.nab.services.mq.Receiver#134bfc8]
; nested exception is org.springframework.messaging.converter.MessageConversionException: Cannot convert from [javax.xml.bind.JAXBElement] to [com.nab.services.dto.CacheMsgType] for org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener$MessagingMessageConverterAdapter$LazyResolutionMessage#3621aa, failedMessage=org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener$MessagingMessageConverterAdapter$LazyResolutionMessage#3621aa
at org.springframework.jms.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:118) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:77) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:736) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:696) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:674) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:318) [spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:257) [spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1189) [spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1179) [spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:1076) [spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_162]
Caused by: org.springframework.messaging.converter.MessageConversionException: Cannot convert from [javax.xml.bind.JAXBElement] to [com.nab.services.dto.CacheMsgType] for org.springframework.jms.listener.adapter.AbstractAdaptableMessageListener$MessagingMessageConverterAdapter$LazyResolutionMessage#3621aa
at org.springframework.messaging.handler.annotation.support.PayloadArgumentResolver.resolveArgument(PayloadArgumentResolver.java:144) ~[spring-messaging-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:116) ~[spring-messaging-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:137) ~[spring-messaging-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.messaging.handler.invocation.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:109) ~[spring-messaging-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.jms.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:114) ~[spring-jms-5.0.5.RELEASE.jar:5.0.5.RELEASE]
... 10 common frames omitted
This might be implementation specific, but once the message is sent, you should be able to read the message id from the message itself.

Calling stored function in hibernate

I have tried multiple ways to call stored function in hibernate---
1) Via Session.doWork callback method
session.doWork(new Work() {
#Override
public void execute(Connection conn)
throws SQLException {
CallableStatement stmt = conn.prepareCall("{? = call test(?)}");
stmt.registerOutParameter(1, Types.INTEGER);
stmt.setString(2, "callIndex");
stmt.execute();
eventVal = stmt.getInt(1);
}
});
This works fine but cannot return any thing from here, so doesn't solve my purpose.
2) Via Native query
StringBuilder query = new StringBuilder();
query.append("Select test() from dual");
SQLQuery sqlQuery = session.createSQLQuery(query.toString());
List resultList = sqlQuery.list();
events = new ArrayList<Events>();
Object result = null;
if (events != null && !events.isEmpty()) {
for (int i = 0; i < events.size(); i++) {
result = resultList.get(i);
}
}
This doesn't work and gives me some No Dialect mapping for JDBC type -10, not sure of the reason.
3) Via named query
My entity class is ---
#NamedNativeQueries({
#NamedNativeQuery(name = "testCall",
query = "? = call test()",
hints = {#QueryHint(name = "org.hibernate.callable", value = "true" )},
resultClass = Events.class
)
})
#Entity
#Table(name = "EVENTS")
public class Events implements Serializable {
private static final long serialVersionUID = -24850323296832289L;
/** The id. */
#Id
#Column(name = "EVENT_SID")
private Integer eventId;
/** The processed status. */
#Column(name = "EVENT_STATUS")
private String eventStatus;
/** The event type. */
#Column(name = "EVENT_TYPE_NAME")
private String eventType;
/** The live event. */
#Column(name = "IS_LIVE_EVENT")
private Integer liveEvent;
/** The event message. */
#Lob
#Column(name = "EVENT_MESSAGE")
private String eventMessage;
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public String getEventStatus() {
return eventStatus;
}
public void setEventStatus(String eventStatus) {
this.eventStatus = eventStatus;
}
/**
* Gets the event type.
*
* #return the event type
*/
public String getEventType() {
return eventType;
}
/**
* Sets the event type.
*
* #param eventType
* the new event type
*/
public void setEventType(String eventType) {
this.eventType = eventType;
}
/**
* Gets the live event.
*
* #return the live event
*/
public Integer getLiveEvent() {
return liveEvent;
}
/**
* Sets the live event.
*
* #param liveEvent
* the new live event
*/
public void setLiveEvent(Integer liveEvent) {
this.liveEvent = liveEvent;
}
/**
* Gets the event message.
*
* #return the event message
*/
public String getEventMessage() {
return eventMessage;
}
/**
* Sets the event message.
*
* #param eventMessage
* the new event message
*/
public void setEventMessage(String eventMessage) {
this.eventMessage = eventMessage;
}
}
The DAO through which I am making call have method ---
public Integer callSqlBlock(){
int event = 0;
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
List<Events> events = null;
events = session.getNamedQuery("testCall").list();
return events.get(0).getEventId();
}
stored function on the DB end ---
create or replace
function test return SYS_REFCURSOR
as
p_order_recordset SYS_REFCURSOR;
begin
open p_order_recordset FOR SELECT EVENT_SID,EVENT_STATUS,EVENT_TYPE_NAME,IS_LIVE_EVENT FROM events;
return p_order_recordset;
end ;
execution of stored function via named query is giving me invalid column index
Please let me know where I am going wrong on this, and if possible please provide some example also

Jedis and JOhm Error

I am using Redis installed on Windows via chocolatey and setup jedis and JOhm in java project. The Redis server is live Redis version 2.6 When I want to save a Java object like the one in the post I got an error message.
java.lang.NoSuchMethodError: redis.clients.jedis.Jedis.sadd(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Long;
at redis.clients.johm.Nest.sadd(Nest.java:168)
at redis.clients.johm.JOhm.save(JOhm.java:220)
at redis.clients.johm.JOhm.save(JOhm.java:146)
This is my java object:
/**
*
*/
package com.smsgh.unitysmpp.MessageProcessor;
import java.io.Serializable;
import org.joda.time.DateTime;
import redis.clients.johm.Attribute;
import redis.clients.johm.Id;
import redis.clients.johm.Model;
/**
* #author Arsene Tochemey GANDOTE This class holds the Messages that needs a
* Delivery Receipt
*/
#Model
public class StoredShortMessage implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6185862961624213864L;
#Id
private Integer id;
// session Id
#Attribute
private Long smppSessionId;
// Message Id
#Attribute
private String messageId;
// ESME Account Number#
#Attribute
private Long accountNumber;
// ESME Account Id
#Attribute
private String accountId;
// ESME API Pub Key
#Attribute
private String apiPublicKey;
// Message state
#Attribute
private String messageState;
// Network Error
#Attribute
private String networkErrorCode;
// First 20 Characters of the message
#Attribute
private String mesgFirstLines;
// esme TCP/IP connection
#Attribute
private String ip;
// message submitted datetime
#Attribute
private DateTime submitDate;
// final state date
#Attribute
private DateTime doneDate;
// source address
#Attribute
private byte srcTon;
#Attribute
private byte srcNpi;
#Attribute
private String srcAddr;
// destination address
#Attribute
private byte destTon;
#Attribute
private byte destNpi;
#Attribute
private String destAddr;
// delivery state
#Attribute
private char dlrState;
/**
*
*/
public StoredShortMessage() {
}
/**
* #return the smppSessionId
*/
public Long getSmppSessionId() {
return smppSessionId;
}
/**
* #param smppSessionId
* the smppSessionId to set
*/
public void setSmppSessionId(Long smppSessionId) {
this.smppSessionId = smppSessionId;
}
/**
* #return the messageId
*/
public String getMessageId() {
return messageId;
}
/**
* #param messageId
* the messageId to set
*/
public void setMessageId(String messageId) {
this.messageId = messageId;
}
/**
* #return the accountNumber
*/
public Long getAccountNumber() {
return accountNumber;
}
/**
* #param accountNumber
* the accountNumber to set
*/
public void setAccountNumber(Long accountNumber) {
this.accountNumber = accountNumber;
}
/**
* #return the accountId
*/
public String getAccountId() {
return accountId;
}
/**
* #param accountId
* the accountId to set
*/
public void setAccountId(String accountId) {
this.accountId = accountId;
}
/**
* #return the apiPublicKey
*/
public String getApiPublicKey() {
return apiPublicKey;
}
/**
* #param apiPublicKey
* the apiPublicKey to set
*/
public void setApiPublicKey(String apiPublicKey) {
this.apiPublicKey = apiPublicKey;
}
/**
* #return the messageState
*/
public String getMessageState() {
return messageState;
}
/**
* #param messageState
* the messageState to set
*/
public void setMessageState(String messageState) {
this.messageState = messageState;
}
/**
* #return the networkErrorCode
*/
public String getNetworkErrorCode() {
return networkErrorCode;
}
/**
* #param networkErrorCode
* the networkErrorCode to set
*/
public void setNetworkErrorCode(String networkErrorCode) {
this.networkErrorCode = networkErrorCode;
}
/**
* #return the mesgFirstLines
*/
public String getMesgFirstLines() {
return mesgFirstLines;
}
/**
* #param mesgFirstLines
* the mesgFirstLines to set
*/
public void setMesgFirstLines(String mesgFirstLines) {
this.mesgFirstLines = mesgFirstLines;
}
/**
* #return the ip
*/
public String getIp() {
return ip;
}
/**
* #param ip
* the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* #return the submitDate
*/
public DateTime getSubmitDate() {
return submitDate;
}
/**
* #param submitDate
* the submitDate to set
*/
public void setSubmitDate(DateTime submitDate) {
this.submitDate = submitDate;
}
/**
* #return the doneDate
*/
public DateTime getDoneDate() {
return doneDate;
}
/**
* #param doneDate
* the doneDate to set
*/
public void setDoneDate(DateTime doneDate) {
this.doneDate = doneDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
/**
* #return the srcTon
*/
public byte getSrcTon() {
return srcTon;
}
/**
* #param srcTon
* the srcTon to set
*/
public void setSrcTon(byte srcTon) {
this.srcTon = srcTon;
}
/**
* #return the srcNpi
*/
public byte getSrcNpi() {
return srcNpi;
}
/**
* #param srcNpi
* the srcNpi to set
*/
public void setSrcNpi(byte srcNpi) {
this.srcNpi = srcNpi;
}
/**
* #return the srcAddr
*/
public String getSrcAddr() {
return srcAddr;
}
/**
* #param srcAddr
* the srcAddr to set
*/
public void setSrcAddr(String srcAddr) {
this.srcAddr = srcAddr;
}
/**
* #return the destTon
*/
public byte getDestTon() {
return destTon;
}
/**
* #param destTon
* the destTon to set
*/
public void setDestTon(byte destTon) {
this.destTon = destTon;
}
/**
* #return the destNpi
*/
public byte getDestNpi() {
return destNpi;
}
/**
* #param destNpi
* the destNpi to set
*/
public void setDestNpi(byte destNpi) {
this.destNpi = destNpi;
}
/**
* #return the destAddr
*/
public String getDestAddr() {
return destAddr;
}
/**
* #param destAddr
* the destAddr to set
*/
public void setDestAddr(String destAddr) {
this.destAddr = destAddr;
}
/**
* #return the dlrState
*/
public char getDlrState() {
return dlrState;
}
/**
* #param dlrState
* the dlrState to set
*/
public void setDlrState(char dlrState) {
this.dlrState = dlrState;
}
}
Can someone tell me what can be the error? Thanks
To solve I have to download the source code and use it. I think there is a bug in the jar file I downloaded.
Download Project Source from
https://github.com/xetorthio/johm
Edit pom.xml
change Jedis version from 1.5.1 to 2.4.2 or latest
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.4.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
Compile project and build jar , use this new jar in your project

java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()

For some reason I get the following exception when using Spring Batch in combination with Hibernate 4.
java.lang.NoSuchMethodError: org.hibernate.SessionFactory.openSession()Lorg/hibernate/classic/Session;
at org.springframework.batch.item.database.HibernateItemReaderHelper.createQuery(HibernateItemReaderHelper.java:152)
at org.springframework.batch.item.database.HibernateItemReaderHelper.getForwardOnlyCursor(HibernateItemReaderHelper.java:122)
at ....
I upgraded to the latest Spring batch 2.1.8.RELEASE and Spring 3.1.1.RELEASE which supposed to work with Hibernate 4. I looked into the source and it seems that the helper class is using the new version of the session factory that is used in Hibernate 4:
package org.springframework.batch.item.database;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.springframework.batch.item.database.orm.HibernateQueryProvider;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Internal shared state helper for hibernate readers managing sessions and
* queries.
*
* #author Dave Syer
*
*/
public class HibernateItemReaderHelper<T> implements InitializingBean {
private SessionFactory sessionFactory;
private String queryString = "";
private String queryName = "";
private HibernateQueryProvider queryProvider;
private boolean useStatelessSession = true;
private StatelessSession statelessSession;
private Session statefulSession;
/**
* #param queryName name of a hibernate named query
*/
public void setQueryName(String queryName) {
this.queryName = queryName;
}
/**
* #param queryString HQL query string
*/
public void setQueryString(String queryString) {
this.queryString = queryString;
}
/**
* #param queryProvider Hibernate query provider
*/
public void setQueryProvider(HibernateQueryProvider queryProvider) {
this.queryProvider = queryProvider;
}
/**
* Can be set only in uninitialized state.
*
* #param useStatelessSession <code>true</code> to use
* {#link StatelessSession} <code>false</code> to use standard hibernate
* {#link Session}
*/
public void setUseStatelessSession(boolean useStatelessSession) {
Assert.state(statefulSession == null && statelessSession == null,
"The useStatelessSession flag can only be set before a session is initialized.");
this.useStatelessSession = useStatelessSession;
}
/**
* #param sessionFactory hibernate session factory
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void afterPropertiesSet() throws Exception {
Assert.state(sessionFactory != null, "A SessionFactory must be provided");
if (queryProvider == null) {
Assert.notNull(sessionFactory, "session factory must be set");
Assert.state(StringUtils.hasText(queryString) ^ StringUtils.hasText(queryName),
"queryString or queryName must be set");
}
// making sure that the appropriate (Hibernate) query provider is set
else {
Assert.state(queryProvider != null, "Hibernate query provider must be set");
}
}
/**
* Get a cursor over all of the results, with the forward-only flag set.
*
* #param fetchSize the fetch size to use retrieving the results
* #param parameterValues the parameter values to use (or null if none).
*
* #return a forward-only {#link ScrollableResults}
*/
public ScrollableResults getForwardOnlyCursor(int fetchSize, Map<String, Object> parameterValues) {
Query query = createQuery();
if (parameterValues != null) {
query.setProperties(parameterValues);
}
return query.setFetchSize(fetchSize).scroll(ScrollMode.FORWARD_ONLY);
}
/**
* Open appropriate type of hibernate session and create the query.
*/
public Query createQuery() {
if (useStatelessSession) {
if (statelessSession == null) {
statelessSession = sessionFactory.openStatelessSession();
}
if (queryProvider != null) {
queryProvider.setStatelessSession(statelessSession);
}
else {
if (StringUtils.hasText(queryName)) {
return statelessSession.getNamedQuery(queryName);
}
else {
return statelessSession.createQuery(queryString);
}
}
}
else {
if (statefulSession == null) {
statefulSession = sessionFactory.openSession();
}
if (queryProvider != null) {
queryProvider.setSession(statefulSession);
}
else {
if (StringUtils.hasText(queryName)) {
return statefulSession.getNamedQuery(queryName);
}
else {
return statefulSession.createQuery(queryString);
}
}
}
// If queryProvider is set use it to create a query
return queryProvider.createQuery();
}
/**
* Scroll through the results up to the item specified.
*
* #param cursor the results to scroll over
*/
public void jumpToItem(ScrollableResults cursor, int itemIndex, int flushInterval) {
for (int i = 0; i < itemIndex; i++) {
cursor.next();
if (i % flushInterval == 0 && !useStatelessSession) {
statefulSession.clear(); // Clears in-memory cache
}
}
}
/**
* Close the open session (stateful or otherwise).
*/
public void close() {
if (statelessSession != null) {
statelessSession.close();
statelessSession = null;
}
if (statefulSession != null) {
statefulSession.close();
statefulSession = null;
}
}
/**
* Read a page of data, clearing the existing session (if necessary) first,
* and creating a new session before executing the query.
*
* #param page the page to read (starting at 0)
* #param pageSize the size of the page or maximum number of items to read
* #param fetchSize the fetch size to use
* #param parameterValues the parameter values to use (if any, otherwise
* null)
* #return a collection of items
*/
public Collection<? extends T> readPage(int page, int pageSize, int fetchSize, Map<String, Object> parameterValues) {
clear();
Query query = createQuery();
if (parameterValues != null) {
query.setProperties(parameterValues);
}
#SuppressWarnings("unchecked")
List<T> result = query.setFetchSize(fetchSize).setFirstResult(page * pageSize).setMaxResults(pageSize).list();
return result;
}
/**
* Clear the session if stateful.
*/
public void clear() {
if (statefulSession != null) {
statefulSession.clear();
}
}
}
So the question is why is it still trying to use an older version even though the newest is used. Does anybody have an idea why this still could be happening?
We finally got it to work by compiling Spring batch against Hibernate 4. It seems Spring batch is not compatible with Hibernate 4.
This is what's in my WAR:
activation-1.1.jar
amqp-client-2.7.1.jar
antlr-2.7.7.jar
aopalliance-1.0.jar
aspectjrt-1.5.0.jar
aspectjweaver-1.5.2.jar
aspectjweaver-1.6.9.jar
avalon-framework-4.1.3.jar
billing-commons-1.9.0-SNAPSHOT.jar
billing-core-1.9.0-SNAPSHOT.jar
cglib-nodep-2.2.2.jar
classpath.txt
commons-batch-2.0.0-SNAPSHOT.jar
commons-beanutils-1.7.0.jar
commons-cli-1.1.jar
commons-codec-1.2.jar
commons-customer-experience-1.3.0.jar
commons-domain-1.0.0.jar
commons-email-1.1.jar
commons-email-1.9.1-SNAPSHOT.jar
commons-hibernate-3.0.0-SNAPSHOT.jar
commons-http-1.2.1.jar
commons-httpclient-3.1.jar
commons-httpclient-contrib-3.1.jar
commons-io-1.3.1.jar
commons-lang-2.1.jar
commons-logging-1.1.jar
commons-logging-1.2.0.jar
commons-monitoring-1.0.0.jar
commons-property-3.3.0.jar
commons-rabbitmq-1.1.1.jar
commons-spring-agent-2.5.0-SNAPSHOT.jar
commons-util-1.6.1.jar
customer-inventory-commons-1.4.0.jar
customer-inventory-core-1.4.0.jar
cxf-api-2.3.2.jar
cxf-common-schemas-2.3.2.jar
cxf-common-utilities-2.3.2.jar
cxf-rt-bindings-xml-2.3.2.jar
cxf-rt-core-2.3.2.jar
cxf-rt-frontend-jaxrs-2.3.2.jar
cxf-rt-transports-common-2.3.2.jar
cxf-rt-transports-http-2.3.2.jar
dom4j-1.6.1.jar
generic-monitoring-console-api-1.1.0.jar
geronimo-javamail_1.4_spec-1.7.1.jar
hibernate-commons-annotations-4.0.1.Final.jar
hibernate-core-4.1.4.Final.jar
hibernate-entitymanager-4.1.4.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
hibernate-validator-4.3.0.Final.jar
javassist-3.15.0-GA.jar
jaxb-impl-2.1.13.jar
jboss-logging-3.1.0.GA.jar
jboss-transaction-api_1.1_spec-1.0.0.Final.jar
jettison-1.1.jar
jms-1.1.jar
jsr250-api-1.0.jar
jsr311-api-1.1.1.jar
log4j-1.2.15.jar
logkit-1.0.1.jar
mail-1.4.jar
neethi-2.0.4.jar
orchestration-api-1.7.0-20120820.120350-6.jar
quartz-1.5.2.jar
simplestuff-0.9.jar
singleview-api-commons-1.1.0.jar
singleview-api-core-1.1.0.jar
slf4j-api-1.5.6.jar
slf4j-simple-1.5.6.jar
spring-aop-3.1.1.RELEASE.jar
spring-asm-3.1.1.RELEASE.jar
spring-aspects-3.1.1.RELEASE.jar
spring-batch-core-2.1.8.RELEASE.jar
spring-batch-infrastructure-2.1.8.RELEASE.jar
spring-beans-3.1.1.RELEASE.jar
spring-context-3.1.1.RELEASE.jar
spring-context-support-3.1.1.RELEASE.jar
spring-core-3.1.1.RELEASE.jar
spring-expression-3.1.1.RELEASE.jar
spring-jdbc-3.1.1.RELEASE.jar
spring-orm-3.1.1.RELEASE.jar
spring-tx-3.1.1.RELEASE.jar
spring-web-3.1.1.RELEASE.jar
spring-webmvc-3.1.1.RELEASE.jar
stax2-api-3.0.2.jar
validation-api-1.0.0.GA.jar
woodstox-core-asl-4.0.8.jar
wsdl4j-1.6.2.jar
XmlSchema-1.4.7.jar
xpp3_min-1.1.4c.jar
xstream-1.3.1.jar

Resources