I'm Adding 3 Categories using Post Request and for every Category, 3 respective Courses are added to the same. Finally I need to get an array of Categories containing list of courses.
But while performing Test Driven Development using Mockito, I', recieving a null Pointer Exception with status code 400.
Kindly help me in the same.
Test.java
#RunWith(value = MockitoJUnitRunner.class)
#WebMvcTest(Controller.class)
class Test {
#Autowired
MockMvc mvc;
#MockBean
service s;
#MockBean
Controller cont;
#MockBean
StatusResultMatchers sr;
#org.junit.jupiter.api.Test
void catTest() throws Exception {
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
Course[] c= {c1,c2,c3};
List<Course> cl=new ArrayList<Course>();
cl.add(c1);
cl.add(c2);
cl.add(c3);
Category ca=new Category(7415,"java","very gud", cl);
when(s.getAllContents()).thenReturn(cl);
mvc.perform(get("/getcourse")).andExpect(sr.is2xxSuccessful()).andReturn();
}
}
Controller.java
#RestController
public class Controller {
#Autowired
private service cs;
#RequestMapping(value="/addcat", method=RequestMethod.POST)
public void addcat(#RequestBody Category[] categ) throws Exception{
for(int i=0;i<3;i++)
cs.cat[i]=categ[i];
}
#RequestMapping(value="/addcour", method=RequestMethod.POST)
public void addcour(#RequestBody Course[] cour) {
for(Category c:cs.cat) {
cs.co=null;
for(int i=0;i<3;i++) {
if(cour[i].getCategoryId()==c.getCategoryId()) {
cs.co.add(cour[i]);
c.setCourseList(cs.co);
}
}
}
}
#RequestMapping(value="/getcat", method=RequestMethod.GET)
public #ResponseBody Category[] getcat(){
return cs.getAllCategories();
}
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(#RequestBody Map<Category,List<Course> > cour){
return cs.getAllContents();
}
}
Service.java
#Service
public class service {
public List<Course> co=new ArrayList<Course>();
public Category[] cat=new Category[3];
public List<Course> getAllContents() {
return co;
}
public Category[] getAllCategories() {
return cat;
}
}
Test Output
MockHttpServletRequest:
HTTP Method = GET
Request URI = /getcourse
Parameters = {}
Headers = []
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.example.demo.controller.Controller$MockitoMock$138133307
Method = com.example.demo.controller.Controller$MockitoMock$138133307#getcourse(Map)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
2020-06-03 17:38:59.573 INFO 26360 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
I have updated my code. Now, NullPOinterException is not there. But I'm getting an empty list "ActualCourse".
Please find d code below:
Test.java
#RunWith(value = MockitoJUnitRunner.class)
#WebMvcTest(Controller.class)
class Test {
#Autowired
MockMvc mvc;
#MockBean
service testService;
#MockBean
Controller targetController;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#org.junit.jupiter.api.Test
void catTest() throws Exception {
// Mock Data
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
List<Course> expectedCourse=new ArrayList<Course>();
expectedCourse.add(c1);
expectedCourse.add(c2);
expectedCourse.add(c3);
Category expectedCategory=new Category(7415,"java","very gud", expectedCourse);
when(testService.addcour()).thenReturn(expectedCourse);
List<Course> actualCourse = targetController.addcour();
assertEquals(expectedCourse,actualCourse);
}
Controller.java
#RestController
public class Controller {
#Autowired
private service cs;
#RequestMapping(value="/addcat", method=RequestMethod.POST)
public List<Category> addcat(#RequestBody Category[] categ) throws Exception{
return cs.addcat(categ);
}
#RequestMapping(value="/addcour", method=RequestMethod.POST)
public List<Course> addcour() {
return cs.addcour();
}
#RequestMapping(value="/getcat", method=RequestMethod.GET)
public #ResponseBody List<Category> getcat(){
return cs.getAllCategories();
}
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(){
return cs.getAllCourses();
}
}
Service.java
#Service
public class service {
public List<Category> cat=new ArrayList<Category>();
public List<Course> c=new ArrayList<Course>();
List<Course> empty=new ArrayList<Course>();
List<Category> category=new ArrayList<Category>();
public List<Category> addcat(Category[] categ) {
int flagcat=0,flagcourse=0;
Category c1=new Category(7415,"Technology","Java",empty);
Category c2=new Category(2,"Technology","Java",empty);
Category c3=new Category(7314,"Technology","Java",empty);
Category c4=new Category(4,"Technology","Java",empty);
Category c5=new Category(8415,"Technology","Java",empty);
Category c6=new Category(6,"Technology","Java",empty);
category=Arrays.asList(c1,c2,c3,c4,c5,c6);
Iterator icat=category.iterator();
Iterator icourse=c.iterator();
Object ncourse=new Object();
Object ncat=new Object();
while(icat.hasNext()) {
List<Course> co=new ArrayList<Course>();
flagcat++;
flagcourse=0;
ncat=icat.next();
while(icourse.hasNext()) {
ncourse=icourse.next();
if(((Category) ncourse).getCategoryId()==((Category) ncat).getCategoryId()) {
flagcourse++;
co.add((Course) ncourse);
if(flagcourse==3) {
((Category) ncat).setCourseList(co);
break;
}
}
}
cat.add((Category) icat);
if(flagcat==3) {
break;
}
}
return cat;
}
public List<Course> addcour() {
Course c1=new Course(1,"Technology",100,50,7415);
Course c2=new Course(2,"Technology",100,50,7415);
Course c3=new Course(3,"Technology",100,50,7415);
Course c4=new Course(4,"Technology",100,50,7314);
Course c5=new Course(5,"Technology",100,50,7314);
Course c6=new Course(6,"Technology",100,50,7314);
Course c7=new Course(7,"Technology",100,50,8415);
Course c8=new Course(8,"Technology",100,50,8415);
Course c9=new Course(9,"Technology",100,50,8415);
Course c10=new Course(10,"Technology",100,50,8415);
List<Course> c=Arrays.asList(c1,c2,c3,c4,c5,c6,c7,c8,c9,c10);
return c;
}
public List<Course> getAllCourses() {
return c;
}
public List<Category> getAllCategories() {
return cat;
}
}
Output
org.opentest4j.AssertionFailedError: expected: <[com.example.demo.Course#6ecc02bb, com.example.demo.Course#31973858, com.example.demo.Course#65514add]> but was: <[]>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
at com.example.demo.test.Test.catTest(Test.java:75)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
It seems you have some design issues in your code. In your controller, the getcourse method is receiving a request body Map<Category,List<Course> > cour, but the HTTP method is a GET, you're not supposed to send data in a GET method (check this answer and this for more context).
On the other side, your getcourse is not using the cour parameter, so refactor this method as:
#RequestMapping(value="/getcourse", method=RequestMethod.GET)
public #ResponseBody List<Course> getcourse(){
return cs.getAllContents();
}
Let me know if it works.
DetailFragment.java
public void sendPost() {
mAPIService.savePost("O3", 2, "ssfu", "jhsgdhf", 20, "mystring", 1, "UnoiaTech", "hdbjhsdhfjsd").enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if (response.isSuccessful()) {
Toast.makeText(getActivity(), "Submited" + response.body(), Toast.LENGTH_SHORT).show();
Log.i(TAG, "post submitted to API." + response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Toast.makeText(getActivity(), "Error To Post API in DetailFragment", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to submit post to API.");
}
});
}
PlanFragment.java
next_plan_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detailFragment.sendPost();
}
});
ApiUtils.java
public class ApiUtils {
private ApiUtils() {}
public static final String BASE_URL = "http://192.168.100.14:8080";
public static APIService getAPIService() {
return RetrofitClient.getClient(BASE_URL).create(APIService.class);
}
}
RetroClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
ApiService.java
public interface APIService {
#POST("/deals/deal")
#FormUrlEncoded
Call<Post> savePost(#Field("bookingType") String bookingType,
#Field("dealPrice") int dealPrice,
#Field("description") String description,
#Field("keyword") String keyword,
#Field("originalPrice") int originalPrice,
#Field("plan") String plan,
#Field("shopId") int shopId,
#Field("shopName") String shopName,
#Field("title") String title);
}
Showing error
FATAL EXCEPTION: main
Process: googlemap.arun.com.mywork2, PID: 20969
java.lang.NullPointerException: Attempt to invoke interface method
'retrofit2.Call
googlemap.arun.com.mywork2.data.remote.APIService.savePost(java.lang.String,
int, java.lang.String, java.lang.String, int, java.lang.String, int,
java.lang.String, java.lang.String)' on a null object reference
at
googlemap.arun.com.mywork2.DetailFragment.sendPost(DetailFragment.java:104)
at
googlemap.arun.com.mywork2.PlanFragment$5.onClick(PlanFragment.java:85)
at android.view.View.performClick(View.java:5272)
at android.view.View$PerformClick.run(View.java:21528)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5857)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1026)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:887)
I hade a strange happening today with my Firebase project.
Suddenly the
AddressChatMessage chatMessage = snapshot.getValue(AddressChatMessage.class);
parsed everything ok for the AddressChatMessage except for one int.
Took me 2 hour until i tried this, setting the field to public
public int type;
Note I use this code for weeks without problem and today Android studio made some core updated to 2.3.2 and maybe that trigger this strange event.
Here´s the AddressChatMessage.java nothing strange except that the public int type cannot be private, if it is, it will be zero, that too is strange, usually Firebase give out a logcat warning when pojo parsing fails. I have 10 other modell classes like this with plenty of int´s
#IgnoreExtraProperties
public class AddressChatMessage {
// [START Firebase keys inside AddressChatMessage ]
#Exclude
public static final String TYPE = "type";
#Exclude
public static final String SENDER_ID = "senderId";
#Exclude
public static final String MESSAGE = "message";
#Exclude
public static final String FILENAME = "fileName";
#Exclude
public static final String DOWNLOAD_URI = "downloadUri";
#Exclude
public static final String TIME = "time";
// [STOP Firebase keys inside AddressChatMessage ]
public int type;
private String senderId;
private String message;
private String fileName;
private String downloadUri;
#Exclude
private long time;
#Exclude
private String messageId;
public AddressChatMessage() {
}
public AddressChatMessage(int type, String senderUid) {
this.senderId = senderUid;
this.type = type;
}
public AddressChatMessage(int type, String senderUid, String message) {
this.type = type;
this.senderId = senderUid;
this.message = message;
}
private int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getSenderId() {
return senderId;
}
public void setSenderId(String senderId) {
this.senderId = senderId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getDownloadUri() {
return downloadUri;
}
public void setDownloadUri(String downloadUri) {
this.downloadUri = downloadUri;
}
public long getTime() {
return time;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
#Exclude
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put(TYPE, type);
result.put(SENDER_ID, senderId);
result.put(MESSAGE, message);
result.put(FILENAME, fileName);
result.put(DOWNLOAD_URI, downloadUri);
result.put(TIME, time);
return result;
}
#Exclude
public boolean isTypeNormal() {
return getType() == ChatAdapter.MessageType.NORMAL.ordinal();
}
#Exclude
public boolean isTypeImage() {
return getType() == ChatAdapter.MessageType.IMAGE.ordinal();
}
}
When cleaning the code using Lint. Lint suggested changes like "This can be private instead of public" - I accidentally set the getType() to private access.
I get the below exception when trying to run an EJB application using TopLink on WebLogic application server.
java.lang.IllegalArgumentException: NamedQuery of name: TblPkgFeature.getFeaturesData not found:
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.getDatabaseQuery(EJBQueryImpl.java:422)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EJBQueryImpl.setParameterInternal(EJBQueryImpl.java:657)
at oracle.toplink.essentials.internal.ejb.cmp3.EJBQueryImpl.setParameter(EJBQueryImpl.java:202)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.persistence.InterceptingInvocationHandlerImpl.invoke(InterceptingInvocationHandlerImpl.java:29)
at $Proxy110.setParameter(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailServiceImpl.getPackageData(PartDetailServiceImpl.java:170)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.__WL_invoke(Unknown Source)
at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:34)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl.getPackageData(Unknown Source)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.ServerRequest.sendReceive(ServerRequest.java:202)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:463)
at weblogic.rmi.cluster.ClusterableRemoteRef.invoke(ClusterableRemoteRef.java:274)
at com.siliconexpert.avago.service.impl.PartDetailService_888km8_PartDetailServiceRemoteImpl_12120_WLStub.getPackageData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:84)
at $Proxy111.getPackageData(Unknown Source)
at com.siliconexpert.avago.server.rmi.client.PartDetailServiceRmiClient.getPackageData(PartDetailServiceRmiClient.java:108)
at com.siliconexpert.avago.gui.server.services.PartDetailRemoteServiceImpl.getPackageData(PartDetailRemoteServiceImpl.java:121)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:569)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:751)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:844)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:280)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:254)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:136)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:341)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:25)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at com.siliconexpert.avago.gui.server.services.MainFilter.doFilter(MainFilter.java:47)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:79)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3367)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3333)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2220)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2146)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2124)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1564)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:254)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:295)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:254)
The above exception is thrown on the below line:
List<TblPkgFeature> list =
em.createNamedQuery("TblPkgFeature.getFeaturesData").setParameter("pkgTypeId", GetFeaturesData.PACKAGE.getCode()).setParameter("type", "package").getResultList();
Also when I changed this method em.createNamedQuery("TblPkgFeature.getFeaturesData") by the method
em.createQuery("select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder")
it worked successfully and the exception wasn't thrown.
By the way both queries are the same, but the difference is that I placed the query in the method parameter of the "createQuery()" method.
The below is the entity bean that contains the NamedQuery:
package com.siliconexpert.avago.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
* The persistent class for the TBL_PKG_FEATURES database table.
*
*/
#NamedQueries
({
#NamedQuery(name="TblPkgFeature.getFeaturesData", query="select new com.siliconexpert.avago.model.TblPkgFeature(p.fetId, p.fetName, p.fetDisplayName, o.fetDefention, p.unit) " +
" from TblPkgFeature p left outer join p.tblOthersFetDef o where (lower(o.type) =:type or o.type is null )" +
" and p.display=1 and p.pkgTypeId =:pkgTypeId order by p.cmDisplayOrder ") //and p.fetId<>39
})
#Entity
#Table(name = "TBL_PKG_FEATURES")
public class TblPkgFeature implements Serializable
{
private static final long serialVersionUID = -8604710446605212000L;
#Id
#Column(name = "FET_ID")
private long fetId;
#Column(name = "CM_DISPLAY_ORDER")
private long cmDisplayOrder;
#Column(name = "DATA_LENGHT")
private long dataLenght;
#Column(name = "DATA_TYPE")
private String dataType;
private long display;
#Column(name = "FET_DISPLAY_NAME")
private String fetDisplayName;
#Column(name = "FET_HEADER_ORDER")
private long fetHeaderOrder;
#Column(name = "FET_NAME")
private String fetName;
#Column(name = "OLD_NAME")
private String oldName;
#Column(name = "PKG_TYPE_ID")
private long pkgTypeId;
#Column(name = "QUALITY_AV")
private long qualityAv;
#Column(name = "TBL_NAME")
private String tblName;
private String unit;
#OneToOne
#JoinColumn(name="FET_NAME", referencedColumnName="FET_NAME", updatable=false, insertable=false)
private TblOthersFetDef tblOthersFetDef;
#Transient
private String fetDefinition;
public TblPkgFeature()
{
}
public TblPkgFeature(long fetId, String fetDisplayName)
{
super();
this.fetId = fetId;
this.fetDisplayName = fetDisplayName;
}
public TblOthersFetDef getTblOthersFetDef()
{
return tblOthersFetDef;
}
public void setTblOthersFetDef(TblOthersFetDef tblOthersFetDef)
{
this.tblOthersFetDef = tblOthersFetDef;
}
public TblPkgFeature(long fetId, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName);
this.fetDefinition = fetDefinition;
this.unit = unit;
}
public TblPkgFeature(long fetId, String fetName, String fetDisplayName, String fetDefinition, String unit)
{
this(fetId, fetDisplayName, fetDefinition, unit);
this.fetName = fetName;
}
public String getFetDefinition()
{
return fetDefinition;
}
public void setFetDefinition(String fetDefinition)
{
this.fetDefinition = fetDefinition;
}
public long getFetId()
{
return this.fetId;
}
public void setFetId(long fetId)
{
this.fetId = fetId;
}
public long getCmDisplayOrder()
{
return this.cmDisplayOrder;
}
public void setCmDisplayOrder(long cmDisplayOrder)
{
this.cmDisplayOrder = cmDisplayOrder;
}
public long getDataLenght()
{
return this.dataLenght;
}
public void setDataLenght(long dataLenght)
{
this.dataLenght = dataLenght;
}
public String getDataType()
{
return this.dataType;
}
public void setDataType(String dataType)
{
this.dataType = dataType;
}
public long getDisplay()
{
return this.display;
}
public void setDisplay(long display)
{
this.display = display;
}
public String getFetDisplayName()
{
return this.fetDisplayName;
}
public void setFetDisplayName(String fetDisplayName)
{
this.fetDisplayName = fetDisplayName;
}
public long getFetHeaderOrder()
{
return this.fetHeaderOrder;
}
public void setFetHeaderOrder(long fetHeaderOrder)
{
this.fetHeaderOrder = fetHeaderOrder;
}
public String getFetName()
{
return this.fetName;
}
public void setFetName(String fetName)
{
this.fetName = fetName;
}
public String getOldName()
{
return this.oldName;
}
public void setOldName(String oldName)
{
this.oldName = oldName;
}
public long getPkgTypeId()
{
return this.pkgTypeId;
}
public void setPkgTypeId(long pkgTypeId)
{
this.pkgTypeId = pkgTypeId;
}
public long getQualityAv()
{
return this.qualityAv;
}
public void setQualityAv(long qualityAv)
{
this.qualityAv = qualityAv;
}
public String getTblName()
{
return this.tblName;
}
public void setTblName(String tblName)
{
this.tblName = tblName;
}
public String getUnit()
{
return this.unit;
}
public void setUnit(String unit)
{
this.unit = unit;
}
}
Please help.
Thanks.
I'm trying to persist a record that has a mapped #Persistent InputStream field.
the context is: JDK 1.8, LiferayPortal on Tomee 1.7.1 (OpenJPA 2.4-patch). Sorry about the stacktrace polluted by the Liferay one.
#Entity
#Table(name = "file_entries")
public class FileEntry implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(length = 120)
private String createdBy;
#Temporal(TemporalType.TIMESTAMP)
private Date created;
#Column(length = 120)
private String modifiedBy;
#Temporal(TemporalType.TIMESTAMP)
private Date modified;
#Column(length = 200)
private String title;
#Column(length = 2000)
private String description;
#Column(length = 240)
private String filename;
#Column(length = 60)
private String extension;
#Column(length = 20)
private String version;
#Column(length = 240)
private String contentType;
#Persistent(fetch = FetchType.LAZY)
private InputStream content;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public Date getModified() {
return modified;
}
public void setModified(Date modified) {
this.modified = modified;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public InputStream getContent() {
return content;
}
public void setContent(InputStream content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
And when persisting:
logo = new FileEntry();
logo.setContent(new FileInputStream("some_local_file"));
entityService.persist(logo);
I get the following exception.
<openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: The transaction has been rolled back. See the nested exceptions for details on the errors that occurred.
at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2370)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2207)
at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2105)
at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:1876)
at org.apache.openjpa.kernel.DelegatingBroker.flush(DelegatingBroker.java:1045)
at org.apache.openjpa.persistence.EntityManagerImpl.flush(EntityManagerImpl.java:663)
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:483)
at org.zeroturnaround.jrebel.integration.openjpa.EntityManagerFactoryWrapper$ReloadingMethodHandler.invoke(EntityManagerFactoryWrapper.java:135)
at com.sun.proxy.$Proxy619.flush(Unknown Source)
at org.apache.openejb.persistence.JtaEntityManager.flush(JtaEntityManager.java:202)
at com.computas.generic.service.SimpleEntityService.persist(SimpleEntityService.java:37)
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:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.monitoring.StatsInterceptor.record(StatsInterceptor.java:181)
at org.apache.openejb.monitoring.StatsInterceptor.invoke(StatsInterceptor.java:100)
at sun.reflect.GeneratedMethodAccessor585.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext$Invocation.invoke(ReflectionInvocationContext.java:192)
at org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed(ReflectionInvocationContext.java:173)
at org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85)
at org.apache.openejb.core.stateless.StatelessContainer._invoke(StatelessContainer.java:227)
at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:194)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:308)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:303)
at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:308)
... 171 more
Caused by: <openjpa-2.4.0-nonfinal-1598334-r422266:1599166 fatal general error> org.apache.openjpa.persistence.PersistenceException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4998)
at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4958)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:134)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:108)
at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:60)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:185)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:96)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:77)
at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:732)
at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
... 204 more
Caused by: java.sql.SQLException: can't call setAutoCommit when the connection is JtaManaged
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.forbiddenCall(ManagedConnection.java:185)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invokeUnderTransaction(ManagedConnection.java:162)
at org.apache.openejb.resource.jdbc.managed.local.ManagedConnection.invoke(ManagedConnection.java:93)
at com.sun.proxy.$Proxy618.setAutoCommit(Unknown Source)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.ConfiguringConnectionDecorator$ConfiguringConnection.setAutoCommit(ConfiguringConnectionDecorator.java:117)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.lib.jdbc.DelegatingConnection.setAutoCommit(DelegatingConnection.java:167)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertPostgresBlob(PostgresDictionary.java:627)
at org.apache.openjpa.jdbc.sql.PostgresDictionary.insertBlobForStreamingLoad(PostgresDictionary.java:614)
at org.apache.openjpa.jdbc.meta.strats.LobFieldStrategy.insert(LobFieldStrategy.java:100)
at org.apache.openjpa.jdbc.meta.FieldMapping.insert(FieldMapping.java:623)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.insert(AbstractUpdateManager.java:238)
at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.populateRowManager(AbstractUpdateManager.java:165)
... 208 more
The persistence unit declaration is:
<persistence-unit name="uefiscdi" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>uefiscdiDS</jta-data-source>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
<property name="openjpa.jdbc.DBDictionary" value="postgres" />
<property name="openjpa.Log" value="DefaultLevel=INFO, Tool=INFO" />
</properties>
</persistence-unit>
The Datasource declaration is:
<Resource id="uefiscdiDS" type="DataSource">
JdbcDriver org.postgresql.Driver
JdbcUrl jdbc:postgresql://localhost:5432/db_name
UserName user_name
Password user_password
JtaManaged true
DefaultAutoCommit false
</Resource>
I tried with DefaultAutoCommit true / false / not declared ... same exception.
Just a shot in the dark, but have you tried calling em.persist(...) rather than em.merge(..)?
If that doesn't work it might be helpful if you posted the full stack trace somewhere. I'm afraid you might have snipped off the important parts.