NullpointerException even after preventive check - java

Please help in multithreaded scenario rarely I get NullPointerException in below code
public class CassPerfInterceptor {
private static final Logger log = LoggerFactory
.getLogger(CassPerfInterceptor.class);
private Performance performance;
#Autowired
private QueueServerMbean queueServerMbean;
#Around("target(org.springframework.data.repository.CrudRepository) || execution(public * com.owmessaging.*.dao.*.*Dao.*(..))")
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
try {
Object obj = joinPoint.proceed();
performance = StatsProvider.getCassandraStats(joinPoint.getSignature().getName());
if(performance != null){
// Here I am getting NPE line number 30
performance.add(System.currentTimeMillis()-start, false);
}
return obj;
}catch(DriverException de){
queueServerMbean.sendNotification("CRITICAL", "DB Connectivity Error: "+de.getMessage());
throw de;
}
catch(Exception e){
log.error("Error: ",e);
performance = StatsProvider.getCassandraStats(joinPoint.getSignature().getName());
if(performance != null){
performance.add(System.currentTimeMillis()-start, true);
}
throw e;
}
}
}
Below is the stack trace:
11126 2016-07-04 17:16:58,448[http-nio-8014-exec-16]ERROR CassPerfInterceptor -Error:
11127
java.lang.NullPointerException
11128 at com.owmessaging.qserv.stats.CassPerfInterceptor.invoke(CassPerfInterceptor.java:31)
11129 at sun.reflect.GeneratedMethodAccessor39.invoke(Unknown Source)
11130 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
11131 at java.lang.reflect.Method.invoke(Method.java:497)
11132 at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:621)
11133 at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:610)
11134 at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:68)
11135 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:168)
11136 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
11137 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
11138 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
11139 at com.sun.proxy.$Proxy79.insertMsgInfo(Unknown Source)
11140 at com.owmessaging.qserv.service.impl.QueueServiceImpl.enqueue(QueueServiceImpl.java:151)
Even if I applied preventive check if (performance != null) still I am getting NPE. Is the above check no thread safe. (But note that this is very rare case I got I NPE out of 7000 request.)

Related

Getting a NullPointerException During Initialization of Interface

I write a maven project named "error project". Its aim is to handle exceptions in other projects. It utilizes another maven project "configuration manager". The ultimate aim of configuration manager is to obtain database credentials from some xml files. In this project, it has "IExceptionService", it is proposed that other projects write their exceptions through this interface. This interface's concrete class is assigned at runtime by "DependencyResolver" class. The assignment has been done in "resolve" method as such:
#SuppressWarnings("unchecked")
public static <T> T resolve(Class<T> classType, HashMap<DependencyResolverParameter,String> parameterMap )
{
try {
if(classType == null)
throw new ArgumanBosHatasi("classType is null");
if(parameterMap == null)
throw new ArgumanBosHatasi(HashMap.class.toString());
assert classType != null : "classType == null";
if(classType.equals(IErrorRepository.class))
return (T)getIErrorRepository();
else if(classType.equals(IErrorFile.class))
return (T)getIErrorFile();
else if(classType.equals(ErrorBusinessRule.class))
return (T)getErrorBusinessRule();
else if(classType.equals(IErrorService.class))
{
try {
return (T)getIErrorService(parameterMap);
} catch (UygulamaHatasi applicationException) {
throw applicationException; }
}
else
throw new UnsupportedOperationException("Unknown class type.");
} catch (Exception exception) {
throw exception;
}
}
private static IErrorRepository getIErrorRepository() {
try
{
if(errorDatabase != null)
return errorDatabase;
KonfigurasyonYoneticisi yonetici = new KonfigurasyonYoneticisi();
String sifreKodu = "HATASIFRE";
String schema = yonetici.okuAyar("HATASCHEMA");
String tabloAdi = yonetici.okuAyar("HATATABLOSU");
String veritabaniUrl = yonetici.okuAyar("HATAVERITABANIURL"); //Here is line 92 in DependencyResolver
String kullaniciAdi = yonetici.okuAyar("HATAKULLANICIADI");
if(SozceIsleri.bosMu(sifreKodu))
throw new BasarisizIslemHatasi("sifreKodu boş geliyor.");
if(SozceIsleri.bosMu(schema))
throw new BasarisizIslemHatasi("schema boş geliyor.");
if(SozceIsleri.bosMu(tabloAdi))
throw new BasarisizIslemHatasi("tabloAdi boş geliyor.");
if(SozceIsleri.bosMu(veritabaniUrl))
throw new BasarisizIslemHatasi("veritabaniUrl boş geliyor.");
if(SozceIsleri.bosMu(kullaniciAdi))
throw new BasarisizIslemHatasi("kullaniciAdi boş geliyor.");
assert SozceIsleri.doluMu(sifreKodu) : "SozceIsleri.bosMu(sifreKodu)";
assert SozceIsleri.doluMu(schema) : "SozceIsleri.bosMu(schema)";
assert SozceIsleri.doluMu(tabloAdi) : "SozceIsleri.bosMu(tabloAdi)";
assert SozceIsleri.doluMu(veritabaniUrl) : "SozceIsleri.bosMu(veritabaniUrl)";
assert SozceIsleri.doluMu(kullaniciAdi) : "SozceIsleri.bosMu(kullaniciAdi)";
oracle.jdbc.OracleDriver oracleDriver = new oracle.jdbc.OracleDriver();
lock();
errorDatabase = new HataRepository(oracleDriver, veritabaniUrl,kullaniciAdi,sifreKodu,schema,tabloAdi);
openLock();
if(errorDatabase == null)
throw new BosIsaretciHatasi(MesajIsleri.<IErrorRepository>getirBosGeliyorMesaji(IErrorRepository.class));
return errorDatabase;
} catch (BosIsaretciHatasi | BasarisizIslemHatasi hata) {
throw hata;
}finally {
openLock();
}
}
"DependencyResolverParameter" is an enum and it only has the value "UYGULAMAANAHTAR". (APPLICATION KEY)
I call this method like that:
int applicationKey = 4;
HashMap<DependencyResolverParameter,String> map = new HashMap<DependencyResolverParameter,String>();
map.put(DependencyResolverParameter.APPLICATIONKEY, Integer.toString(applicationKey));
IExceptionService service = DependencyResolver.<IExceptionService>resolve(IExceptionService.class, map);
I define all necessary dependencies within the project. In the code above, the "service" variable is not null as expected and it writes trial error successfully whenever I write it inside a main method as below:
public static void main(String[] args) {
int applicationKey = 4;
HashMap<DependencyResolverParameter,String> map = new HashMap<DependencyResolverParameter,String>();
map.put(DependencyResolverParameter.APPLICATIONKEY, Integer.toString(applicationKey));
IExceptionService servis = DependencyResolver.<IExceptionService>resolve(IExceptionService.class, map);
System.out.println(String.format("is it null? %b", servis == null));
servis.report(new Exception("trial error. Do not care."));
}
However, when I write the code inside JUnit4 test I am getting "NullPointerException" as below:
#Test
public void getHataService_001() {
try
{
int applicationKey= 4;
HashMap<DependencyResolverParameter,String> map = new HashMap<DependencyResolverParameter,String>();
map.put(DependencyResolverParameter.APPLICATIONKEY, Integer.toString(applicationKey));
IExceptionService servis = DependencyResolver.<IExceptionService>resolve(IExceptionService.class, map);
assertNotNull(servis);
} catch (Exception exception) {
fail(exception.getMessage());
}
}
How can I solve that problem? Thanks in advance.
From the stacktrace, I deduce that there is a problem of reading settings from configuration class.
junit dependency :
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
</dependency>
stacktrace:
m:java.lang.NullPointerExceptionlm:nullst:hata.businesslayer.dependencyresolvers.DependencyResolver.resolve(DependencyResolver.java:92)
kisi.core.crosscuttingconcern.exceptionhandling.HataIsleri.getHataService(HataIsleri.java:229)
kisi.core.crosscuttingconcern.exceptionhandling.HataIsleri.raporlaHata(HataIsleri.java:75)
test.hata.HataServisTesti.getHataService_001(HataServisTesti.java:62)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:567)org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
2020/07/09 14:41:34
m:java.lang.NullPointerException
lm:nullst:hata.businesslayer.dependencyresolvers.DependencyResolver.resolve(DependencyResolver.java:92)
test.hata.HataServisTesti.getHataService_001(HataServisTesti.java:56)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:567)
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)2020/07/09 14:41:34
It is because of an apache maven project inside a project. When I remove the apache maven project, it works.

NonUniqueObjectException in Confluence with scheduled job

Got a huge problem with quartz Job in Confluence, regarding the page creation.
QUARTZ Job class:
#ComponentImport
private final SpaceManager spaceManager;
#Autowired
private final GeneralConfig config;
#Autowired
private final PageCreator pageCreator;
#ComponentImport
private final PageManager pageManager;
#Autowired
public ReportingPluginJob(GeneralConfig config, SpaceManager spaceManager, PageCreator pageCreator,
PageManager pageManager) {
this.config = config;
this.spaceManager = spaceManager;
this.pageCreator = pageCreator;
this.pageManager = pageManager;
}
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(ReportingPluginJob.class);
#Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
Collection<String> keys = spaceManager.getAllSpaceKeys(SpaceStatus.CURRENT);
String parentPageName = config.getSchedulerWeeklyParentPageName();
for (String key : keys) {
Page parentPage
= pageManager.getPage(key, parentPageName);
if (parentPage != null) {
LOG.debug("Creating weekly report for space " + key);
long pageId = parentPage.getId();
try {
pageCreator.createEazyBiReport(key, pageId);
} catch (ApplicationException e) {
LOG.error("FAILED TO CREATE A REPORT FOR SPACE " + key + " with error: " + System.lineSeparator()
+ e.getMessage());
}
}
}
}
PAGE CREATION class:
Space space = spaceManager.getSpace(spaceKey);
if (page != null) {
page.setTitle(pageTitle);
page.setSpace(space);
page.setVersion(1);
page.addLabelling(new Labelling(label, page.getEntity(), AuthenticatedUserThreadLocal.get()));
page.setCreator(AuthenticatedUserThreadLocal.get());
page.setCreationDate(new Date());
Page parent = pageManager.getPage(parentId);
if (parent != null) {
parent.addChild(page);
}
}
pageManager.saveContentEntity(page, DefaultSaveContext.builder().suppressNotifications(true).build());
attachmentProvider.attachExcelFileToPage(page);
AND Finally the exception which is driving me mad:
org.springframework.dao.DuplicateKeyException: A different object with the same identifier value was already associated with the session : [com.atlassian.confluence.spaces.Space#31653891]; nested exception is org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [com.atlassian.confluence.spaces.Space#31653891]
at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:259)
at org.springframework.orm.hibernate5.HibernateTemplate.doExecute(HibernateTemplate.java:362)
at org.springframework.orm.hibernate5.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:326)
at org.springframework.orm.hibernate5.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:704)
at com.atlassian.confluence.core.persistence.hibernate.HibernateObjectDao.saveRaw(HibernateObjectDao.java:207)
at com.atlassian.confluence.pages.persistence.dao.hibernate.CachingPageDao.saveRaw(CachingPageDao.java:157)
at com.atlassian.confluence.core.DefaultContentEntityManager.saveContentEntity(DefaultContentEntityManager.java:150)
at com.atlassian.confluence.pages.DefaultPageManager.saveContentEntity(DefaultPageManager.java:1388)
at sun.reflect.GeneratedMethodAccessor2132.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at com.atlassian.spring.interceptors.SpringProfilingInterceptor.invoke(SpringProfilingInterceptor.java:16)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at com.atlassian.confluence.util.profiling.ConfluenceMonitoringMethodInterceptor.invoke(ConfluenceMonitoringMethodInterceptor.java:34)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy105.saveContentEntity(Unknown Source)
at sun.reflect.GeneratedMethodAccessor2132.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.atlassian.plugin.util.ContextClassLoaderSettingInvocationHandler.invoke(ContextClassLoaderSettingInvocationHandler.java:26)
at com.sun.proxy.$Proxy253.saveContentEntity(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:302)
at org.eclipse.gemini.blueprint.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:56)
at org.eclipse.gemini.blueprint.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:60)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.eclipse.gemini.blueprint.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:70)
at org.eclipse.gemini.blueprint.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:53)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.eclipse.gemini.blueprint.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:57)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:208)
at com.sun.proxy.$Proxy2863.saveContentEntity(Unknown Source)
at com.censored.atlassian.plugins.service.PageCreator.createEazyBiReport(PageCreator.java:128)
at com.censored.atlassian.plugins.service.ReportingPluginJob.execute(ReportingPluginJob.java:64)
at com.atlassian.confluence.plugin.descriptor.JobModuleDescriptor$DelegatingPluginJob.lambda$execute$0(JobModuleDescriptor.java:113)
at com.atlassian.confluence.impl.vcache.VCacheRequestContextManager.doInRequestContextInternal(VCacheRequestContextManager.java:87)
at com.atlassian.confluence.impl.vcache.VCacheRequestContextManager.doInRequestContext(VCacheRequestContextManager.java:71)
at com.atlassian.confluence.plugin.descriptor.JobModuleDescriptor$DelegatingPluginJob.execute(JobModuleDescriptor.java:112)
at org.quartz.core.JobRunShell.run(JobRunShell.java:223)
at com.atlassian.confluence.schedule.quartz.ConfluenceQuartzThreadPool.lambda$runInThread$0(ConfluenceQuartzThreadPool.java:16)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
According the stack trace, I've got a problem during the page save (saveContentEntity). It seems, the page save needs to update a space associated with the page too.
And here comes the problem. According to the stack trace, this space exists in the Hibernate session already. evict and clear of the actual session does not work.
Any suggestions, how can I handle this exception, or how can I actually remove the space from Hibernate session?
Apparently, this is what's happening in your code:
Within your SpaceManager, your session finds a Session object with ID 1 (assume that) and returns it.
Your method uses this reference to associate with another object, a Page one.
And finally, your PageManager persist this data in the database.
Probably, your problem is problem that:
From step 1 to 2, when the SpaceManager returns the data, your transaction is ended and your returned object becomes detached.
After that, when you call save, you are trying to persist a detached Session, but it already exists in the database. Then you get an exception.
You could try to use the merge method or remove the cascade from this reference in your entity.
(Please provide your entity code so I can improve my answer if there's anything wrong or which don't work for you.)
We ran into the same problem and what solved it for us was to put the code that creates the page (and loads other objects, like the space or the parent page) all into a transaction:
private void createNewPage(String title, String pageInput, Long parentPageId, String spaceKey) {
transactionTemplate.execute(() -> {
Page page = new Page();
page.setTitle(title);
page.setBodyAsString(pageInput);
Space space = spaceManager.getSpace(spaceKey);
page.setSpace(space);
Page parentPage = pageManager.getPage(parentPageId);
if (parentPage != null) {
page.setParentPage(parentPage);
parentPage.addChild(page);
}
pageManager.saveContentEntity(page, DefaultSaveContext.DEFAULT);
return null;
});
}
com.atlassian.sal.api.transaction.TransactionTemplate can be injected with #ComponentImport

Need to call StoredProcedure in jave using Hibernate

Just want to call Stored procedure of SQL server from java using Hibernate as ORM.
The stored Procedure has so many result set which I am keeping it in Java as DTO's and each one as list in one DTO to send as JSON payload for Front-end integration.
But I am getting exception saying"org.hibernate.MappingException: Unknown entity: com.test.plans.dto.TemplatesDTO"
public ItemDetailsDTO getItemDetails(int no) {
Session session = getSession();
Connection connection = null;
List<ItemDetailsDTO> resultList = new ArrayList<>();
try {
ResultSet rs = null;
SessionImpl sessionImpl = (SessionImpl) session;
connection = sessionImpl.connection();
Query query = session.createSQLQuery("exec usp_GetItemDetails :no")
.addEntity(TemplatesDTO.class)
.setParameter("no", no);
resultList = query.list();
} catch (Exception e) {
System.out.println("error");
e.printStackTrace();
}
return resultList.get(0);
}
DTO :
import java.util.List;
public class ItemDetailsDTO {
private List<TemplatesDTO> templates;
public List<TemplatesDTO> gettemplates() {
return templates;
}
public void settemplates(List<TemplatesDTO> templates) {
this.templates = templates;
}
}
Please find below complete trace of exception
org.hibernate.MappingException: Unknown entity: com.test.plans.dto.TemplatesDTO
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:783)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.getSQLLoadable(SQLQueryReturnProcessor.java:358)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processRootReturn(SQLQueryReturnProcessor.java:411)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processReturn(SQLQueryReturnProcessor.java:378)
at org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.process(SQLQueryReturnProcessor.java:180)
at org.hibernate.loader.custom.sql.SQLCustomQuery.(SQLCustomQuery.java:71)
at org.hibernate.engine.query.internal.NativeQueryInterpreterStandardImpl.createQueryPlan(NativeQueryInterpreterStandardImpl.java:70)
at org.hibernate.engine.query.spi.QueryPlanCache.getNativeSQLQueryPlan(QueryPlanCache.java:210)
at org.hibernate.internal.AbstractSessionImpl.getNativeSQLQueryPlan(AbstractSessionImpl.java:306)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at nbcu.compass.contingencyplans.dao.impl.ContDAOImpl.getItemDetails(ContingencyDAOImpl.java:503)
at nbcu.compass.contingencyplans.dao.impl.ContDAOImpl$$FastClassBySpringCGLIB$$c2b97106.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
at com.test.plans.dao.impl.ContDAOImpl$$EnhancerBySpringCGLIB$$a1741e1f.getItemDetails()
at com.test.plans.service.impl.ContPlanServiceImpl.getConditionScheduleItemDetails(ContingencyPlanServiceImpl.java:316)
at test.plans.plans.rest.impl.PlanResourceImpl.getItemDetails(PlanResourceImpl.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)

Hibernate issue java.lang.Boolean cannot be cast to java.lang.String Using JDK 1.7

I am facing issue with Hibernate.
Using Hibernate 3.2.6 and JDK 1.7.0_21
Is this issue coming due to JDK compatibility with Hibernate version?
This issue is random. I still unable to find steps to reproduce.
2014-07-14 06:09:10,661 [DEBUG] EventExpenseAreaService.getEventSummary:654 - Revenue Value (Hari) --> 1166.15
2014-07-14 06:09:18,665 [ERROR] EventSetupService.getEventById:1451 - java.lang.Boolean cannot be cast to java.lang.String
java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.String
at org.hibernate.type.StringType.toString(StringType.java:44)
at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:93)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:140)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:107)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2002)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2376)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2312)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2612)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:96)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at com.sibisoft.northstar.events.service.EventSetupService.getEventById(EventSetupService.java:1441)
at com.sibisoft.northstar.events.struts.EventAction.load(EventAction.java:1037)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
Code getEventById
public EventDTO getEventById(Integer eventId,boolean logActivity, Session session)throws Exception {
EventDTO event = null;
Transaction transaction = null;
try {
if (session == null) {
session = HibernateSessionFactory.getSession();
if(logActivity){
transaction = session.beginTransaction();
}
}
event = (EventDTO) super.getByPrimaryKey(EventDTO.class, eventId,session);
if(transaction!=null){
transaction.commit();
}
} catch (HibernateException e) {
LOGGER.error(e.getMessage(), e);
if(transaction!=null){
transaction.rollback();
}
throw e;
}catch (Exception e) {
LOGGER.error(e.getMessage(), e);
if(transaction!=null){
transaction.rollback();
}
throw e;
}
return event;
}
Method : getByPrimaryKey
protected BaseEventDTO getByPrimaryKey(Class clazz, Integer pk,Session session) throws Exception{
BaseEventDTO dto = null;
Transaction tx = null;
try {
if (session == null) {
session = HibernateSessionFactory.getSession();
}
dto = (BaseEventDTO) session.get(clazz, pk);
return dto;
}
catch(Exception e){
LOGGER.error(e);
if (tx !=null) {
tx.rollback();
}
throw e;
}
}
JDK 7 have changed Class.getDeclaredMethods() so the order is not guaranteed. [click here]
You might have a property in Object mapping that have getter method String getProperty() as well as Boolean isPropery() that is causing problem intermittently.
Hibernate 3 BasicPropertyAccessor.getterMethod(...) some time finds getProperty() and some time isProperty() due to unspecified ordering in JDK 7 by getDeclaredMethods(). which confuses hibernate and it invokes Boolean Type method for String type property.
You need to rename one method to get expected results.
Similar question on Hibernate Forum: https://forum.hibernate.org/viewtopic.php?p=2474641

ibi.telnet.api.TnDriverException: Connection is closed

I'm trying to connect to a mainframe via java using iway telnet, this is the connection code:
public static Session conexion(String nodo,int port) throws TnDriverException {
TnDriver driver = new TnDriver();
driver.setHost(nodo);
driver.setPort(port);
driver.setEmulation(Terminal.TN_3270);
driver.setTraceOn(false);
driver.setExtendedAttributes(true);
driver.setLanguage("Cp037");
driver.setTimerTimeout(25);
driver.setTimerOn(true);
session = driver.getSession();
logger.info("CONNECTED TO MAINFRAME.");
return session;
}
During the process of connecting to the mainframe I'm getting the next exception in the first screen:
ibi.telnet.api.TnDriverException: Connection is closed...
at ibi.telnet.api.Session.waitFor(Session.java:453)
at ibi.telnet.api.Session.waitFor(Session.java:393)
at ibi.telnet.api.Session.waitFor(Session.java:312)
at
tn3270.GestionPantallas.identificaPantalla(GestionPantallas.java:73)
at
tn3270.CertificacionSindo.getTransaccion(CertificacionSindo.java:67)
at
ws.Pensiones.obtenerCertificacion(Pensiones.java:41)
at sun.reflect.GeneratedMethodAccessor486.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at weblogic.wsee.component.pojo.JavaClassComponent.invoke(JavaClassComponent.java:99)
at weblogic.wsee.ws.dispatch.server.ComponentHandler.handleRequest(ComponentHandler.java:64)
at weblogic.wsee.handler.HandlerIterator.handleRequest(HandlerIterator.java:137)
at weblogic.wsee.ws.dispatch.server.ServerDispatcher.dispatch(ServerDispatcher.java:109)
at weblogic.wsee.ws.WsSkel.invoke(WsSkel.java:80)
at weblogic.wsee.server.servlet.SoapProcessor.handlePost(SoapProcessor.java:66)
at weblogic.wsee.server.servlet.SoapProcessor.process(SoapProcessor.java:44)
at weblogic.wsee.server.servlet.BaseWSServlet$AuthorizedInvoke.run(BaseWSServlet.java:257)
at weblogic.wsee.server.servlet.BaseWSServlet.service(BaseWSServlet.java:156)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3395)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(Unknown Source)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2140)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2046)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)
And this is the method identificaPantalla in the class GestionPantallas, where the conexion method is.
public static int identificaPantalla(ScreenDesc[] pantallas) throws TnDriverException {
int result = -1;
try {
result = session.waitFor(pantallas);
}
catch(TnDriverException e) {
throw e;
}
return result;
}
Any idea about this issue?

Categories