primefaces 4.0 p:graphicimage defaultstreamedcontent does not render - jsf

I am using
Primefaces 5.0,
JSF 2.0,
Weblogic 10.3(11g),
J2ee 5.
When i use p:graphicImage to render streamed content from my bean,i notice an ajaxresponse exception in the logs and finally and el exception which is below. Is adding el2.0 an option to solve this, if yes then i am not sure if i can add el2.0 only to my project, as i dont want to add it to the domain files of Weblogic. Please help.
java.lang.NoClassDefFoundError: javax/el/ValueReference
at org.primefaces.el.InterceptingResolver.setValue(InterceptingResolver.java:28)
at com.sun.el.parser.AstValue.setValue(Unknown Source)
at com.sun.el.ValueExpressionImpl.setValue(Unknown Source)
at com.sun.faces.facelets.el.TagValueExpression.setValue(TagValueExpression.java:131)
at org.primefaces.el.ValueExpressionAnalyzer.getExpression(ValueExpressionAnalyzer.java:49)
at org.primefaces.util.DynamicResourceBuilder.build(DynamicResourceBuilder.java:49)
at org.primefaces.component.graphicimage.GraphicImageRenderer.getImageSrc(GraphicImageRenderer.java:74)
at org.primefaces.component.graphicimage.GraphicImageRenderer.encodeEnd(GraphicImageRenderer.java:40)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:884)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:68)
at org.primefaces.component.overlaypanel.OverlayPanelRenderer.encodeMarkup(OverlayPanelRenderer.java:59)
at org.primefaces.component.overlaypanel.OverlayPanelRenderer.encodeEnd(OverlayPanelRenderer.java:37)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:884)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:85)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:68)
Below is my code
<p:graphicImage value="#{lev.viewFile}" width="300" cache="false">
<f:param name="id" value="#{lev.levId}" />
</p:graphicImage>
Below is my bean code which is viewscoped...
public StreamedContent getViewFile() {
try{
File viewfileobj = new File("C:/LEAVEMODULEFOLDER/p1.jpeg");
log.debug("viewfileobj.length() = "+viewfileobj.length());
InputStream stream = new FileInputStream(viewfileobj);
log.debug("stream = "+stream);
this.viewFile = new DefaultStreamedContent(stream,"image/jpeg",Utility.getRandomString());
}catch(Exception e){
log.error("Error in Leave.toString() ::"+e);
log.error(Utility.getStackTrace(e));
}
return viewFile;
}

Changing view scope to session scope should work.

Related

How to create a thumbnail link to OmniFaces graphicImage method

I was wondering if and how it is possible to display an <o:graphicImage> as thumbnail inside a <p:lightbox>. To be more precise, I wanted to achieve something like this:
<p:dataTable id="articles" var="article"
value="#{articleMB.articles}" selectionMode="single"
rowKey="#{articles.id}"
selection="#{articleMB.selectedArticle}">
<p:column>
<p:lightBox styleClass="imagebox" id="lighbox">
<h:outputLink value="#{imageBean.getFirstImage(article, true)}">
<o:graphicImage value="#{imageBean.getFirstImage(article, true)}" dataURI="true" height="80" />
</h:outputLink>
</p:lightBox>
</p:column>
</p:dataTable>
Which isn't working obviously, since there's no proper URL passed to the lightbox.
imageBean.getFirstImage(Article article, boolean thumbnail) returns a byte[] of the image, since the images I want to access are stored on an external source.
Edit: So I've done as BalusC mentioned and it seems to be the proper approach. But now I'm getting the following exception:
Caused by: java.lang.IllegalArgumentException: java.lang.ClassCastException#2eae887c
at sun.reflect.GeneratedMethodAccessor307.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.omnifaces.resourcehandler.GraphicResource.getInputStream(GraphicResource.java:259)
at com.sun.faces.application.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:335)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:655)
... 32 more
This is the method that actually returns the image. It is working fine in every other context:
public byte[] getFirstImage(final Article article, boolean thumbnail)
{
try
{
File dir = new File(getImageFolder(article.getImageFolder(), thumbnail));
File[] files = dir.listFiles(new FilenameFilter()
{
#Override
public boolean accept(File dir, String name)
{
return name.startsWith(String.valueOf(article.getArticleId()));
}
});
Arrays.sort(files);
return Files.readAllBytes(files[0].toPath());
}
catch (Exception e)
{
return new byte[1];
}
}
Edit 2: As mentioned in the comments, I'm facing another weird behaviour. It runs perfectly fine on my local machine but on the server it throws following exception:
Caused by: java.lang.IllegalArgumentException: argument type mismatch
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:606)
at org.omnifaces.resourcehandler.GraphicResource.getInputStream(GraphicResource.java:259)
at com.sun.faces.application.resource.ResourceHandlerImpl.handleResourceRequest(ResourceHandlerImpl.java:335)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at org.primefaces.application.resource.PrimeResourceHandler.handleResourceRequest(PrimeResourceHandler.java:87)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.application.ResourceHandlerWrapper.handleResourceRequest(ResourceHandlerWrapper.java:153)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:655)
... 32 more
For exactly this reason, OmniFaces 2.5 introduced the #{of:graphicImageURL()} EL function. This works only if your ImageBean is annotated with #GraphicImageBean.
import org.omnifaces.cdi.GraphicImageBean;
#GraphicImageBean
public class ImageBean {
// ...
}
<h:outputLink value="#{of:graphicImageURL('imageBean.getFirstImage(article, false)')}">
<o:graphicImage value="#{imageBean.getFirstImage(article, true)}" dataURI="true" height="80" />
</h:outputLink>
See also the #GraphicImageBean showcase.
Update: to be clear, you need a converter for non-standard types such as Article. Why such a converter is needed and how to create it is detailed in Conversion Error setting value for 'null Converter'. If you create a #FacesConverter(forClass=Article.class), then the OmniFaces GraphicImage will automatically pickup it.
In your particular case it's however more efficient to just pass the identifier to the image streamer method right away, this saves an additional conversion step. Provided that your Article object has an id property, here's how:
<h:outputLink value="#{of:graphicImageURL('imageBean.getFirstImage(article.id, false)')}">
<o:graphicImage value="#{imageBean.getFirstImage(article.id, true)}" dataURI="true" height="80" />
</h:outputLink>
public byte[] getFirstImage(Long articleId, boolean thumbnail) {
// ...
}
Namely, JSF already has builtin converters for standard types such as Long and boolean.

Display p:fileupload image in p:graphicImage preview without saving it

I am using PrimeFaces 5.3 <p:fileUpload> to upload a PNG image and I would like to show a preview of it in <p:graphicImage> before saving in database.
Here's a MCVE:
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{bean.uploadedFile}" mode="simple" />
<p:graphicImage value="#{bean.image}" />
<p:commandButton action="#{bean.preview}" ajax="false" value="Preview" />
</h:form>
private UploadedFile uploadedFile;
public UploadedFile getUploadedFile() {
return uploadedFile;
}
public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}
public void preview() {
// NOOP for now.
}
public StreamedContent getImage() {
if (uploadedFile == null) {
return new DefaultStreamedContent();
} else {
return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFile.getContents()), "image/png");
}
}
No error occurring on the backing bean, and the image won't be load and display at front-end. The client mentions that the image returned a 404 not found error.
Your problem is two-fold. It failed because the uploaded file contents is request scoped and because the image is requested in a different HTTP request. To better understand the inner working, carefully read the answers on following closely related Q&A:
Display dynamic image from database with p:graphicImage and StreamedContent
How to choose the right bean scope?
To solve the first problem, you need to read the uploaded file contents immediately in the action method associated with the form submit. In your specific case, that would look like:
private UploadedFile uploadedFile;
private byte[] fileContents;
public void preview() {
fileContents = uploadedFile.getContents();
}
// ...
To solve the second problem, your best bet is to use the data URI scheme. This makes it possible to render the image directly in the very same response and therefore you can safely use a #ViewScoped bean without facing "context not active" issues or saving the byte[] in session or disk in order to enable serving the image in a different request. Browser support on data URI scheme is currently pretty good. Replace the entire <p:graphicImage> with below:
<ui:fragment rendered="#{not empty bean.uploadedFile}">
<img src="data:image/png;base64,#{bean.imageContentsAsBase64}" />
</ui:fragment>
public String getImageContentsAsBase64() {
return Base64.getEncoder().encodeToString(imageContents);
}
Note: I assume that Java 8 is available to you as java.util.Base64 was only introduced in that version. In case you're using an older Java version, use DatatypeConverter.printBase64Binary(imageContents) instead.
In case you happen to use JSF utility library OmniFaces, you can also just use its <o:graphicImage> component instead which is on contrary to <p:graphicImage> capable of directly referencing a byte[] and InputStream bean property and rendering a data URI.
<o:graphicImage value="#{bean.imageContents}" dataURI="true" rendered="#{not empty bean.imageContents}">

Property 'value' not found on type java.lang.String

I'm working with MVC project with primeface and jboss 5.1 . I had to migrate project to primeface latest version from primeface 3.4. I migrated that to 3.5 and then 4.0 . Now I'm trying to migrate that to primeface 5.0 . Then It gives this error message.
description
The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: /main.xhtml #103,58 itemLabel="#{item.value}": Property 'value' not found on type java.lang.String
javax.faces.webapp.FacesServlet.service(FacesServlet.java:422)
org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:696)
org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:667)
org.apache.jsp.index_jsp._jspService(index_jsp.java:57)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
and part of my main.xhtml is bellow
<p:selectOneMenu id="compType" value="#{authenticateController.userSession.mwtUmUser.companyType}" effect="fold" editable="false" style="width: 180px;">
<f:selectItems
value="#{authenticateController.companyTypeMap}"
var="item"
itemLabel="#{item.value}"
itemValue="#{item.key}"/>
<p:ajax listener="#{authenticateController.setUserCompanyType}" update=":loginFrm:loginGrd"/>
</p:selectOneMenu>
authenticateController
public Map<String, String> getCompanyTypeMap() {
try {
if (null == commonManager) {
commonManager = (CommonManager) SpringUtil.getApplicationContext().getBean("commonManager");
}
companyTypeMap = commonManager.getCompanyTypeMap(null);
} catch (Exception e) {
log.error(e, e);
}
return companyTypeMap;
}
public String getCompanyType() {
return companyType;}
I already tried some similar problems in stack-overflow but still not good result. plz help me out..
Without a code of your authenticateController I could only suppose, that you are trying to use the java.util.Map interface behind the #{authenticateController.companyTypeMap} call. Please read the BalusC answer on how to use maps with selectItems tag.

Primefaces generating java.lang.NoClassDefFoundError: com/lowagie/text/Document on call method to generate PDF for fileDownload

I need your help in solving the issue of not finding the class com/lowagie/text/Document in iText jar. The Primefaces version is 5.0 and the iText version is 2.1.7. The error is generated when I am adding the method name in the actionListner for calling it in order to generate a PDF file from a method and to make it downloadable on the click of a commandButton.
I trued removing all the JARs and adding them one by one and still the issue is the same. All the JARs are unique and I am using Jdeveloper.
The Bean code is:
public void createPdf1() {
com.lowagie.text.Document doc = new com.lowagie.text.Document(PageSize.A4, 50, 50, 50, 50);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in ;
try {
PdfWriter writer;
writer = PdfWriter.getInstance(doc, out);
doc.open();
PdfPTable table = new PdfPTable(1);
PdfPCell cell = new PdfPCell(new Phrase("First PDF"));
cell.setBorder(Rectangle.NO_BORDER);
cell.setRunDirection(PdfWriter.RUN_DIRECTION_LTR);
table.addCell(cell);
doc.add(table);
in = new ByteArrayInputStream(out.toByteArray());
file = new DefaultStreamedContent(in, "application/pdf", "xxx.pdf");
System.out.println("INSIDE");
} catch (Exception e) {
e.printStackTrace();
}
}
And the jsf code is which I followed the showcase:
<p:commandButton value="Download" ajax="false" onclick="PrimeFaces.monitorDownload(start, stop);" icon="ui-icon-arrowthick-1-s" actionListner="#{pdf.createPdf1}">
<p:fileDownload value="#{pdf.file}" />
</p:commandButton>
On the click of the commandButton, I am getting the error:
javax.faces.el.EvaluationException: java.lang.NoClassDefFoundError:
com/lowagie/text/Document at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
at
com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315) at
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at
oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._invokeApplication(LifecycleImpl.java:973)
at
oracle.adfinternal.view.faces.lifecycle.LifecycleImpl._executePhase(LifecycleImpl.java:354)
at
oracle.adfinternal.view.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:202)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:508)
Caused By: java.lang.ClassNotFoundException: com.lowagie.text.Document
at
weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:297)
at
weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:270)
at
weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:64)
at java.lang.ClassLoader.loadClass(ClassLoader.java:305) at
java.lang.ClassLoader.loadClass(ClassLoader.java:246) at
weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:179)
at
weblogic.utils.classloaders.ChangeAwareClassLoader.loadClass(ChangeAwareClassLoader.java:43)
The iText WAR file is kept under the /lib folder and it has worked fine. The compatible version is iText 2.1.7 please refer to the Dependencies in the guide.

Keep primefaces socket (push) connection after page refresh

I'm using Primefaces fileDownload triggered by a commandButton to allow the user to export his work (as a serialized POJO)... which only exists in a view scope (as long as it has not been exported!)
fileDownload XHTML template:
<p:commandButton value="Save worksheet" icon="ui-icon-disk"
ajax="false" onclick="PrimeFaces.monitorDownload(start, stop)">
<p:fileDownload
value="#{applicationManager.applicationController.saveWorksheet()}" />
</p:commandButton>
saveWorksheet() method
#Override
public StreamedContent saveWorksheet() {
StreamedContent worksheetFile = null;
try {
String worksheetFilename = sessionDirectories + sessionId + "/worksheet.wbc";
System.out.println("saveWorksheet");
FileOutputStream fileOut = new FileOutputStream(worksheetFilename);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(historyList);
out.close();
fileOut.close();
FileInputStream stream = new FileInputStream(worksheetFilename);
worksheetFile = new DefaultStreamedContent(stream, "application/wbc", "worksheet.wbc");
} catch (IOException e) {
e.printStackTrace();
}
return worksheetFile;
}
(historyList is just an ArrayList of history records)
This file downloading feature is working fine. The problem is that I'm using Primefaces push to display the result of the command sent by the user (because I need to display it on every client sharing the same URL fragment). But since fileDownload triggered by a commandButton needs a full page refresh, the socket disconnects on download start.
(note: the socket is connected in the applicationManager bean which is view scoped).
Socket XHTML template:
<p:socket onMessage="handleOutput" channel="/terminalOutput"
widgetVar="subscriber" />
Socket connection:
RequestContext.getCurrentInstance().execute("subscriber.connect('/" + sessionId + "')");
Is there any way to make the socket connection survive a page refresh? is there a way to define the scope of the socket?
Many thanks in advance for your help :)
Regards,
Zim

Resources