Primefaces downloadFile java.io.IOException: Stream Closed after second time - primefaces

I have issue with primefaces 5.0 component p:fileDownload , I have following bean store DefaultStreamedContent , and I get the value stored to download it simply :
Bean :
public class EBMail implements Serializable {
private DefaultStreamedContent attachment;
// # here setter and getter too .
}
and from XHTML file :
<p:commandLink ajax="false" value="Download Attachment" rendered="#{mbMail.attachment != null}">
<p:fileDownload value="#{mbMail.attachment}" />
</p:commandLink>
I get mail attachment file for first time, in 2nd time I get the following exception :
WARNING: java.io.IOException: Stream Closed
javax.faces.FacesException: java.io.IOException: Stream Closed
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:87)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.io.IOException: Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:243)
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:77)
... 30 more
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [FacesServlet] in context with path [/faces] threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:648)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:846)
at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:504)
at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:79)
at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:642)
at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:120)
at org.omnifaces.context.OmniPartialViewContext$OmniPartialResponseWriter.startDocument(OmniPartialViewContext.java:270)
at org.primefaces.context.PrimePartialResponseWriter.startDocument(PrimePartialResponseWriter.java:152)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:201)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:126)
at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
I'm running on JFS 2.2.7 , Primefaces 5.0 , I upload file into bean my issue when I download it for 2nd time, even for another object 'mail' .
Any solution, I looked after many solutions around nothing helped me or I've already tested it.

I solved issue finally, I make new class store my data, and action that prepare stream to download from my class object, and when download file I read bytes from my class bytes, like the following:
Class:
public class Attachment implements Serializable {
private String name;
private String type;
private String encoding;
private byte[] data;
// ... Setters and getters ...
public Attachment () {
this.encoding = "UTF-8";
}
}
Bean:
public class MailBean implements Serializable {
// alot of properties
private Attachment attachment;
// setters and getters
}
Managed Bean :
public class MailManagedBean implements Serializable {
private DefaultStreamedContent attachmentToDownload;
private MailBean mail;
// # here setter and getter too .
public void prepare() {
InputStream stream = new ByteArrayInputStream(mail.getAttachment.getData());
attachmentToDownload = new DefaultStreamedContent(stream, mail.getAttachment.getType(), mail.getAttachment.getName(), mail.getAttachment.getEncoding());
}
}
In XHTML file (I added action) :
<p:commandLink ajax="false" value="Download Attachment"
rendered="#{mbMail.mail.attachment != null}" action="#{mbMail.prepare()}">
<p:fileDownload value="#{mbMail.attachmentToDownload}" />
</p:commandLink>

public StreamedContent getExportFile() {
Field field = exportFile.getStream().getClass().getDeclaredField("path");
field.setAccessible(true);
String path = (String)field.get(exportFile.getStream());
InputStream tempStream = new FileInputStream(path);
exportFile = new DefaultStreamedContent(tempStream,exportFile.getContentType(), exportFile.getName());
return exportFile;
}

Related

Primefaces video streaming issues on Chromium, works in Firefox

I'm using Primefaces <p:video> to stream a video. On Firefox everything seems OK, the video loads correctly and I can skip through the video as expected. On Chromium, though, I cannot skip through the video (tried Chrome and Edge).
Servlet:
#ApplicationScoped
#ManagedBean(name="mediaResources")
public class MediaResources extends Resources {
public StreamedContent getMedia() {
try {
InputStream st = Thread.currentThread().getContextClassLoader().getResourceAsStream("video/target5_part_1_libmp3lame_libx265.mp4");
byte[] targetArray = IOUtils.toByteArray(st);
return DefaultStreamedContent.builder()
.contentType(VideoType.MP4.getMediaType())
.stream(() -> new ByteArrayInputStream(targetArray))
.build();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Page:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:video value="#{mediaResources.media}" player="mp4" controls="true" width="800px" />
</h:body>
</html>
When page loads in Chromium, but not in Firefox, I get the following exception:
java.io.IOException: Error in streaming dynamic resource
at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:131)
at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:98)
at org.richfaces.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:655)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at dk.ctu.taparga.filters.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:24)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1139)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:825)
Caused by: org.apache.catalina.connector.ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:410)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:442)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:347)
at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:435)
at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:423)
at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:91)
at org.primefaces.application.resource.StreamedContentHandler.stream(StreamedContentHandler.java:160)
at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:110)
... 26 more
Caused by: java.net.SocketException: Connection reset by peer: socket write error
at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
at org.apache.coyote.http11.InternalOutputBuffer.realWriteBytes(InternalOutputBuffer.java:216)
at org.apache.tomcat.util.buf.ByteChunk.flushBuffer(ByteChunk.java:442)
at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:347)
at org.apache.coyote.http11.InternalOutputBuffer$OutputStreamOutputBuffer.doWrite(InternalOutputBuffer.java:239)
at org.apache.coyote.http11.filters.ChunkedOutputFilter.doWrite(ChunkedOutputFilter.java:119)
at org.apache.coyote.http11.AbstractOutputBuffer.doWrite(AbstractOutputBuffer.java:192)
at org.apache.coyote.Response.doWrite(Response.java:495)
at org.apache.catalina.connector.OutputBuffer.realWriteBytes(OutputBuffer.java:405)
... 33 more
What to do to make my stream work in all browsers? Is it a limitation on which media types can be streamed in the Chromium engine?
Running Primefaces 11 and Java 8

servlet connection to remote mysql

I am trying to connect my java servlet program in local in eclipse IDE to my remote SQL database which is created in a web hosting.
AdminLoginServlet-
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import model.Model;
public class Dao
{
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://xyz.com/devadmin_CustomerDatabasev1";
private static String username="USER";
private static String password="Password";
private static Connection con=null;
private static ResultSet rs=null;
public static Connection connect()
{
try
{
Class.forName(driver);
con=DriverManager.getConnection(url,username, password);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
return con;
}
public static ResultSet validate(Model m, String sql)
{
try
{
connect();
PreparedStatement ps=con.prepareStatement("select userid,password from adminlogin where userid='user' and password='password'");
rs=ps.executeQuery();
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
}
I get a 500 error code with the following error on UI-
`HTTP Status 500 -type Exception report message description
The server encountered an internal error that prevented it from fulfilling this request.exception
java.lang.NullPointerException
dao.Dao.validate(Dao.java:40)
controller.AdminLoginServlet.doPost(AdminLoginServlet.java:41)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.47 logs.
Apache Tomcat/7.0.47
`
And following error on Console-
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at dao.Dao.connect(Dao.java:22)
at dao.Dao.validate(Dao.java:39)
at controller.AdminLoginServlet.doPost(AdminLoginServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [AdminLoginServlet] in context with path [/FirstApp] threw exception
java.lang.NullPointerException
at dao.Dao.validate(Dao.java:40)
at controller.AdminLoginServlet.doPost(AdminLoginServlet.java:41)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
I am not sure how to proceed or debug the piece of code.Thanks in advance for any pointer that anyone can provide.
Edit:(26 th feb,2017)
I found the connector for java to mysql was missing from the following link:
http://www.ccs.neu.edu/home/kathleen/classes/cs3200/JDBCtutorial.pdf
But I am not able to add it into build path as an external archive.I am getting following option-
Check the folder structure
Thanks in advance for any pointer that anyone can provide.
The database which you are connecting might not have values and also check the column names or you might have given the wrong name or you might not have included the respective jar file under WebContent folder.Take a keen look at all these.

EJB deployment in Apache TomEE using Hibernate Persistence Provider and MySQL DB

I'm facing a problem in configuration for a project what is build on EJB 3.0 technology. As the server container i'm using Apache TomEE v.7.0 with (with built in OpenEJB module), MySQL database and hibernate as the persistence provider.
Below is my configuration files:
tomee.xml
<?xml version="1.0" encoding="UTF-8"?>
<tomee>
<Resource id="lrsDataSource" type="javax.sql.DataSource">
JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost:3306/lbrentalservice
UserName root
Password 123456
JtaManaged true
</Resource>
</tomee>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="lrs-unit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>lrsDataSource</jta-data-source>
<non-jta-data-source>lrsDataSourceUnmanaged</non-jta-data-source>
<class>edu.drg.entity.Book</class>
<class>edu.drg.entity.Category</class>
<class>edu.drg.entity.Person</class>
<class>edu.drg.entity.RentActivity</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory" />
<property name="hibernate.transaction.manager_lookup_class"
value="org.apache.openejb.hibernate.TransactionManagerLookup"/>
</properties>
</persistence-unit>
</persistence>
Person entity (other entities are similar)
#Entity
#Table (name="person", uniqueConstraints = { #UniqueConstraint(columnNames = "prs_id")})
#NamedQueries({
#NamedQuery(name="findAllPersons", query = "SELECT p FROM Person p")
})
public class Person implements IPerson, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Long personId;
private String personName;
private String personSurname;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="prs_id")
public Long getPersonId() {
return personId;
}
public void setPersonId(Long personId) {
this.personId = personId;
}
#Column(name="name")
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
#Column(name="surname")
public String getPersonSurname() {
return personSurname;
}
public void setPersonSurname(String personSurname) {
this.personSurname = personSurname;
}
#Override
public String toString() {
return "Person [personId=" + personId + ", personName=" + personName
+ ", personSurname=" + personSurname + "]";
}
}
ManagerBean
#Stateless(name="LRSManager")
public class LRSManagerBean implements LRSManager{
#Resource(name="lrsDataSource")
DataSource ds;
#PersistenceContext(unitName="lrs-unit")
private EntityManager entityManager;
#Resource
private SessionContext sessionContext;
private static final Log logger = LogFactory.getLog(LRSManagerBean.class);
#Override
public void addBook (IBook book) {
entityManager.persist(book);
}
#Override
public List<IPerson> getAllPersons() {
System.out.println("Is entityManager not null: "+entityManager!=null);
List<IPerson> allPersons = null;
try {
final Query query = entityManager.createNamedQuery("findAllPersons");
allPersons = query.getResultList();
} catch (PersistenceException e) {
e.printStackTrace();
}
return allPersons;
}
Local interface:
import javax.ejb.Local;
import edu.drg.interfaces.ILRSManager;
#Local
public interface LRSManager extends ILRSManager {
}
I'm trying to access the getAllPersons() method via the Interface manager in a servlet as followss:
#WebServlet("/RetrieveAllPersons")
public class RetrieveAllPersons extends HttpServlet {
private static final long serialVersionUID = 1L;
//private ILRSManager manager = LRSManagerFactory.getInstance().getLRSManager();
#EJB
private LRSManager manager;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Log logger = LogFactory.getLog(this.getClass());
logger.debug("Entering servlet");
List<IPerson> allPersons = manager.getAllPersons();
request.setAttribute("allPersons", allPersons);
logger.debug("Retrieved from persons: "+allPersons);
RequestDispatcher rd = request.getRequestDispatcher("persons.jsp");
rd.forward(request, response);
}
}
However, i have no idea why i'm getting the following exception:
lug 07, 2015 2:12:40 PM org.apache.openejb.core.transaction.EjbTransactionUtil handleSystemException
SEVERE: EjbTransactionUtil.handleSystemException: null
java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)
at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:332)
at org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory.createEntityManager(ReloadableEntityManagerFactory.java:160)
at org.apache.openejb.persistence.JtaEntityManagerRegistry.getEntityManager(JtaEntityManagerRegistry.java:119)
at org.apache.openejb.persistence.JtaEntityManager.getEntityManager(JtaEntityManager.java:96)
at org.apache.openejb.persistence.JtaEntityManager.proxyIfNoTx(JtaEntityManager.java:326)
at org.apache.openejb.persistence.JtaEntityManager.createNamedQuery(JtaEntityManager.java:289)
at edu.drg.ejb.LRSManagerBean.getAllPersons(LRSManagerBean.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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)
at com.sun.proxy.$Proxy76.getAllPersons(Unknown Source)
at edu.drg.servlet.RetrieveAllPersons.doPost(RetrieveAllPersons.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
lug 07, 2015 2:12:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [edu.drg.servlet.RetrieveAllPersons] in context with path [/TestingEJB] threw exception
javax.ejb.EJBException: The bean encountered a non-application exception; nested exception is:
java.lang.NullPointerException
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.convertException(BaseEjbProxyHandler.java:408)
at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:312)
at com.sun.proxy.$Proxy76.getAllPersons(Unknown Source)
at edu.drg.servlet.RetrieveAllPersons.doPost(RetrieveAllPersons.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:76)
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:118)
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1602)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:210)
at org.hibernate.jpa.internal.EntityManagerImpl.<init>(EntityManagerImpl.java:91)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.internalCreateEntityManager(EntityManagerFactoryImpl.java:345)
at org.hibernate.jpa.internal.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:332)
at org.apache.openejb.assembler.classic.ReloadableEntityManagerFactory.createEntityManager(ReloadableEntityManagerFactory.java:160)
at org.apache.openejb.persistence.JtaEntityManagerRegistry.getEntityManager(JtaEntityManagerRegistry.java:119)
at org.apache.openejb.persistence.JtaEntityManager.getEntityManager(JtaEntityManager.java:96)
at org.apache.openejb.persistence.JtaEntityManager.proxyIfNoTx(JtaEntityManager.java:326)
at org.apache.openejb.persistence.JtaEntityManager.createNamedQuery(JtaEntityManager.java:289)
at edu.drg.ejb.LRSManagerBean.getAllPersons(LRSManagerBean.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
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)
... 25 more
It seems something is wrong with TransactionManager, i'm wondering if i still have to map my entities via hibernate.cfg.xml and add this mapping as the reference to persistence.xml. Also i have noticed what when i'm trying to access my method, the entitymanager removes all my records from the table.
I still didn't find anything that could help me on tomee documentation. Any ideas?
Found the solution, may be it could be usefull to someone.
As we are going to use Hibernate Persistence Provider and JTA, the transaction manager also should be the corresponding one, till now i was trying to use implicit, the open ejb transaction manager.
To solove this problem, we should use in persistence.xml, instead of
<property name="hibernate.transaction.manager_lookup_class"
value="org.apache.openejb.hibernate.TransactionManagerLookup"/>
this:
<property
name="transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory"/>
Also be aware of hibernate version you are using, i'm using 4.x, the provider
<provider>org.hibernate.ejb.HibernatePersistence</provider>
is deprecate, use this instead:
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

How do I use JPA 2.1's CriteriaBuilder.function with MySQL's "GROUP_CONCAT"? [duplicate]

This question already has answers here:
JPA Criteria API group_concat usage
(3 answers)
Closed 5 years ago.
I’m using JPA 2.1, Hibernate 4.3.6.Final, and MySQL 5.5. I read JPA 2.1 supports invoking native DB functions, but I’m having trouble figuring out how to invoke MySQL's “GROUP_CONCAT.” I have the following code …
final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery criteria = StringUtils.equals(orderByCol, "organization") ? builder.createQuery(Tuple.class) : builder.createQuery(User.class);
final Root<User> user = criteria.from(User.class);
…
final SetJoin<User, Organization> orgsJoin = orderByRoot.join(User_.organizations, JoinType.LEFT);
final Expression groupConcatExpr = builder.function("GROUP_CONCAT", String.class, orgsJoin.get(Organization_.name));
criteria.select(builder.tuple(user, groupConcatExpr))
.groupBy(user);
…
orderByExpr = orgsJoin.get(Organization_.name);
criteria.orderBy(orderByAscending == null || orderByAscending == true ? builder.asc(orderByExpr) : builder.desc(orderByExpr));
but I get the following exception …
java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode
\-[METHOD_CALL] MethodNode: 'function (GROUP_CONCAT)'
+-[METHOD_NAME] IdentNode: 'GROUP_CONCAT' {originalText=GROUP_CONCAT}
\-[EXPR_LIST] SqlNode: 'exprList'
\-[DOT] DotNode: 'organizati2_.NAME' {propertyName=name,dereferenceType=PRIMITIVE,getPropertyPath=name,path=generatedAlias1.name,tableAlias=organizati2_,className=org.mainco.subco.organization.domain.Organization,classAlias=generatedAlias1}
+-[ALIAS_REF] IdentNode: 'organizati2_.id' {alias=generatedAlias1, className=org.mainco.subco.organization.domain.Organization, tableAlias=organizati2_}
\-[IDENT] IdentNode: 'name' {originalText=name}
at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:174)
at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:924)
at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:692)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:568)
at org.hibernate.jpa.criteria.CriteriaQueryImpl$1.buildCompiledQuery(CriteriaQueryImpl.java:336)
at org.hibernate.jpa.criteria.compile.CriteriaCompiler.compile(CriteriaCompiler.java:147)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:736)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
at com.sun.proxy.$Proxy68.createQuery(Unknown Source)
at org.mainco.subco.user.repo.UserDaoImpl.findUsers(UserDaoImpl.java:120)
at org.mainco.subco.user.repo.UserDao2IT.testFindOrderByOrganizationAsc(UserDao2IT.java:624)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
To user GROUP_CONCAT in JPA, below are the steps:
1.) Create a class "GroupConcatFunction" as below:
import java.util.List;
import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
public class GroupConcatFunction implements SQLFunction {
#Override
public boolean hasArguments() {
return true;
}
#Override
public boolean hasParenthesesIfNoArguments() {
return true;
}
#Override
public Type getReturnType(Type firstArgumentType, Mapping mapping)
throws QueryException {
return StandardBasicTypes.STRING;
}
#SuppressWarnings("rawtypes")
#Override
public String render(Type firstArgumentType, List arguments,
SessionFactoryImplementor factory) throws QueryException {
if (arguments.size() != 1) {
throw new QueryException("group_concat should have only one argument");
}
return "group_concat(" + arguments.get(0) + ")";
}
}
2.) We will create a custom dialect which will have the code to register our group_concat function in dialect:
import org.hibernate.dialect.MySQL5Dialect;
public class CustomMySql5Dialect extends MySQL5Dialect {
public CustomMySql5Dialect() {
super();
registerFunction("group_concat", new GroupConcatFunction());
}
}
3.) Replace the dialect definition in persistence.xml with your custom dialect:
<property name="hibernate.dialect" value="<<pkg name>>.CustomMySql5Dialect" />
Now, you will be able to use this in your criteria query.

NPE at TreeTableRenderer.encodeEnd

This is my TreeTable definition on xhtml page:
<p:treeTable var="r" value="#{mybean.tree}">
I can see in catalina.out file that every day this happens a few times:
12-Jan-2015 10:13:00.119 SEVERE [ajp-apr-8009-exec-211] com.sun.faces.application.view.FaceletViewHandlingStrategy.handleRenderException Error Rendering View[/my_page.xhtml]
java.lang.NullPointerException
at org.primefaces.component.treetable.TreeTableRenderer.encodeEnd(TreeTableRenderer.java:127)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at org.primefaces.component.api.UITree.visitTree(UITree.java:648)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:430)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.ajp.AbstractAjpProcessor.process(AbstractAjpProcessor.java:831)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.tomcat.util.net.AprEndpoint$SocketWithOptionsProcessor.run(AprEndpoint.java:2344)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
12-Jan-2015 10:13:00.120 SEVERE [ajp-apr-8009-exec-211] com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError java.lang.NullPointerException
at org.primefaces.component.treetable.TreeTableRenderer.encodeEnd(TreeTableRenderer.java:127)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:919)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1863)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:582)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at org.primefaces.component.api.UITree.visitTree(UITree.java:648)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIForm.visitTree(UIForm.java:371)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:403)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:322)
at org.primefaces.context.PrimePartialViewContext.processPartial(PrimePartialViewContext.java:60)
at javax.faces.component.UIViewRoot.encodeChildren(UIViewRoot.java:1004)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:430)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:133)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.ajp.AbstractAjpProcessor.process(AbstractAjpProcessor.java:831)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.tomcat.util.net.AprEndpoint$SocketWithOptionsProcessor.run(AprEndpoint.java:2344)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I haven't gottten any user complaints and am not sure yet what the user is doing when this happens. I was assuming she is just opening the page but because of handlePartialResponseError I guess it could be also expanding/collapsing.
Does the error indicate that my object is null in one entry of the tree? In my code I have made sure no nulls are added so this should not be the case.
mybean is a #SessionScoped #ManagedBean (used to be #ViewScoped but now the tree is cached for each user).
My setup is:
Tomcat 8.0.15
Mojarra 2.2.8
Primefaces 5.1
RHEL 7.0
I don't think thats a good solution. The code should look more like this:
public TreeNode getRoot() {
checkSession();
if (root == null) {
root = new DefaultTreeNode(data, null);
}
return root;
}
To ensure that it's the same object (right scope of bean assumed)
Michael
As #BalusC wrote in his comment this exception occurs when backend tree is changed while UI tree is building.
When p:treeTable builds it calls getTree() method really many times, at least once for each category. If one of these calls receives a TreeNode object which does not equal the others this exception will be thrown.
In my code I made sure getTree() will always return the same TreeNode object if it was last called by the same user less than 10ms ago. That fixed it.
Better solution would be a fix in PrimeFaces that would make p:treeTable request TreeNode object only once.
Call following JS function onstart of <p:ajax event="select" onstart="func()" />.
function func(){
var originalVal = $('<YOUR_TREETABLE_ID>_selection').val();
var arr = originalVal.split(',');
$('<YOUR_TREETABLE_ID>_selection').val(arr[arr.length-1]);
}