primefaces graphicimage from database not loading - java

I am having trouble displaying image from database on a primefaces graphicimage component. I am using primefaces 3.4.2, jsf 2.2, glassfish 3.1.2.2. Following is the simple code I am trying. I went through other posts related to p:graphicimage and incorporated the recommendations, still I gouldnt make this work. What is wrong here?
index.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:form id="f1">
<p:panel style="height: 500px ; width: 800px" visible="true">
<p:graphicImage value="#{treeBean.image}" />
</p:panel>
</h:form>
</h:body>
</html>
TreeBean.java
#Named
#ApplicationScoped
public class TreeBean implements Serializable{
#EJB
private ImageEJB imageEjb;
public StreamedContent getImage() throws IOException{
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
}
else {
Decisiontree dr = imageEjb.getTree();
return new DefaultStreamedContent(new ByteArrayInputStream(dr.getImage()));
}
}
}
This is what I see in the browser console.

Add a MIME type in web.xml like below:-
<mime-mapping>
<extension>xhtml</extension>
<mime-type>image/svg+xml</mime-type>
</mime-mapping>
Change your return statement in your bean as below:-
return new DefaultStreamedContent(new ByteArrayInputStream(dr.getImage()),"image/svg+xml");

Related

JSF Error Message and Info Message is not working from backing bean

I need a bit help here while setting messages to faces context from a backing bean ,
My page design layout is as follows.Also its using a common layout for all the pages.
ContactUs.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:body>
<ui:composition template="#{language.layout}"> //CommonLayout.xhtml //common template
<ui:define name="content">
<div class="input-cont">
<h:form styleClass="login-form">
<h:messages errorClass="error medium" layout="table" />
<p:inputText value="#{customerBean.contactUsDTO.email}"
id="useremail" name="useremail" type="email"
styleClass="input-text" placeholder="Email" />
<p:inputTextarea value="#{customerBean.contactUsDTO.comments}"
name="txtFeedback" id="txtFeedback"
styleClass="input-text comment-area" placeholder="Comments"</p:inputTextarea>
<div class="btn-cont labels-to-inputs">
<h:commandLink action="#{customerBean.contactUs}"
styleClass="next-btn login-btn ord-btn">Submit</h:commandLink>
</div>
</h:form>
CommonLayout.xhtml Is as follows
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
>
<f:view locale="#{language.locale}">
<h:head>
<h:body>
<div class="container">
<ui:insert name="leftNav"> <!-- Left Navigation -->
<ui:include src="commonLeft.xhtml" />
</ui:insert>
<div id="content"> <!-- External Page Contents Starts -->
<ui:insert name="content">
</ui:insert>
</div> <!-- External Page Contents Ends -->
</div>
</h:body>
</f:view>
</html>
And ContactBean.java
This bean is session scoped under facesconfig.xml file
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
public class ContactBean{
public String contactUs() {
String response="success" //Testing purpose
if(!response.equalsIgnoreCase("success")){
{raiseError("Service is temporarily unavailable, Try again later");
}
System.out.println("Response from email is "+response);
}
else if(response.equalsIgnoreCase("success")){
System.out.println("Response from email is "+response);
{raiseInfo("Thanks for gettting in touch with Us, We will contact you soon");
}
}
}
return "ContactUs";
}
public void raiseError(String msgText){
FacesContext fc = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgText, msgText);
fc.addMessage(null, msg);
}//raiseError
public void raiseInfo(String infoMsg){
FacesContext fc = FacesContext.getCurrentInstance();
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, infoMsg, infoMsg);
fc.addMessage(null, msg);
}//raiseError
}
This raiseInfo and rasieError messages are not showing any messages to that contact-form page, after adding those as a new message object into faces context also , Its not showing up. What could be the possibly error happening.
As correctly pointed out by #ArgaPK, you have missed to terminate first string parameter and start the second string parameter in the below call of raiseError inside contactUs method, instead of 2 parameters it is one String and hence the error:
raiseError("Service is temporarily unavailable, Try again later");
It should have been a compile time error.
Find the solution:
you have to add <p:growl> tag in your xhtml form.
<h:form styleClass="login-form">
<p:growl id="growl" life="2000" />
....
<h:commandLink action="#{customerBean.contactUs}"
styleClass="next-btn login-btn ord-btn">Submit</h:commandLink>
</h:form>

PrimeFaces component doesn't update as desired (nested buttons generated)

I have commandButton component on my JSF page:
<p:commandButton id="period"
value="#{myBean.isMonthly == false ? 'Yearly' : 'Monthly'}"
action="#{myBean.doSomeOtherStuff()}"
update="period myDataTable">
</p:commandButton>
I'm trying to update a dataTable upon a click on the button above.
When I click it, the dataTable is updated as desired whereas the commandButton behaves weirdly, resulting in a display like:
Can someone help me understand the causes of such a weird situation and also tell a solution if possible?
NOTES:
JSF implementation and version: Mojarra (javax.faces-2.1.11.jar)
View technology: Facelets (XHTML)
Copy'n'paste'n'runnable example! (SSCCE) listed below:
FilterBean.java:
package com.turkcell.mdealer.bean.impl;
import org.springframework.stereotype.Component;
#Component
public class FilterBean {
private boolean monthly = true;
public String applyPeriod(String caller) {
monthly = !monthly;
return caller;
}
public boolean isMonthly() {
return monthly;
}
public void setMonthly(boolean monthly) {
this.monthly = monthly;
}
}
sample.xhtml:
<f:view xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:turkcell="http://turkcell.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui" xmlns:o="http://omnifaces.org/ui"
xmlns:of="http://omnifaces.org/functions"
xmlns:pm="http://primefaces.org/mobile" contentType="text/html"
renderKitId="PRIMEFACES_MOBILE">
<pm:page title="Bayi Raporlari">
<pm:view id="FaturasizAktivasyon" swatch="c">
<p:outputPanel id="FaturasizPanel">
<h:form id="FaturasizForm">
<pm:content>
<p:commandButton id="period"
value="#{filterBean.monthly == false ? 'Yearly' : 'Monthly'}"
action="#{filterBean.applyPeriod('sample')}" update="period">
</p:commandButton>
</pm:content>
</h:form>
</p:outputPanel>
</pm:view>
</pm:page>
</f:view>
General view of libraries:
I don't know the reason of the weird behaviour
However, you can use two conditionally rendered button to achieve the same effect:
<p:panelGroup>
<p:commandButton value="Monthly"
action="#{myBean.doSomeOtherStuff()}"
update="myDataTable #parent" rendered="#{myBean.isMonthly}" />
<p:commandButton value="Yearly"
action="#{myBean.doSomeOtherStuff()}"
update="myDataTable #parent" rendered="#{not myBean.isMonthly}" />
</p:panelGroup>

Primefaces photoCam component not rendering

I am using primefaces photoCam component exactly as explained in
https://www.primefaces.org/showcase/ui/multimedia/photoCam.xhtml . unfortunately, unlike in the showcase my photoCam example, mine does not render. I have tried it on Firefox and Chrome the code is as follows:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
And the bean
#ManagedBean
#ViewScoped
public class PhotoCamBean {
private List<String> photos = new ArrayList<String>();
private String getRandomImageName() {
int i = (int) (Math.random() * 10000000);
return String.valueOf(i);
}
public List<String> getPhotos() {
return photos;
}
public void oncapture(CaptureEvent captureEvent) {
String photo = getRandomImageName();
this.photos.add(0,photo);
byte[] data = captureEvent.getData();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "photocam" + File.separator + photo + ".png";
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(new File(newFileName));
imageOutput.write(data, 0, data.length);
imageOutput.close();
}
catch(Exception e) {
throw new FacesException("Error in writing captured image.");
}
}
}
The primefaces showcase photoCam renders a canvas with an adobe flash confirmation window but mine doesn't, what am i missing here?
Adding the meta tag in the head section of the page solves the problem as shown:
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</h:head>
<h:form>
<h:panelGrid columns="3">
<p:photoCam widgetVar="pc" listener="#{photoCamBean.oncapture}" update="photos"/>
<p:commandButton type="button" value="Capture" onclick="pc.capture()"/>
<p:imageSwitch effect="zoom" id="photos">
<ui:repeat value="#{photoCamBean.photos}" var="photo">
<p:graphicImage value="/photocam/#{photo}.png" />
</ui:repeat>
</p:imageSwitch>
</h:panelGrid>
</h:form>
</ui:composition>
I was able to view the canvas with an adobe flash confirmation window simply by adding the meta tag. Thank you all for your contribution.

Composite component listeners only working after page reload

I have a web page which is including a sub-page that changes according to the element I choose in the primefaces dock menu (ui:include). Some sub pages include a custom composite component I implemented. The first page the web app shows has all his listeners working correctly. When I change sub-page via the dock menu, VideoStatusTable's listeners (composite component's listeners) won't work until I refresh the page in the browser (with F5) OR if I select the page again in the dock menu.
Here is the main page holding the dock menu.
<h:body style="width:100%;height:100%;position:relative;">
<h:panelGroup id="contentPanelGroup">
<ui:include src="#{Template.currentView.view}" />
</h:panelGroup>
<div id="header-wrapper">
<h:form id="headerForm" styleClass="titleSize" style="position:relative;height:100%;width:100%;">
</h:form>
</div>
<div id="footer-wrapper">
<h:form id="footerForm">
<h:graphicImage name="ctec.png" library="images" style="position:absolute;left:30px;bottom:10px;"/>
<p:dock>
<p:menuitem value="#{msgs.ViewEnum_TRANSFER}" icon="#{resource['images:hard-drive-download.png']}" action="#{Template.setWindow( 0 )}" update=":contentPanelGroup :headerForm :msgsArea" />
<p:menuitem value="#{msgs.ViewEnum_STATUS}" icon="#{resource['images:gears.png']}" action="#{Template.setWindow( 1 )}" update=":contentPanelGroup :headerForm :msgsArea"/>
<p:menuitem value="#{msgs.ViewEnum_ORGANIZATION}" icon="#{resource['images:folder.png']}" action="#{Template.setWindow( 2 )}" update=":contentPanelGroup :headerForm :msgsArea" />
<p:menuitem value="#{msgs.ViewEnum_VALIDATION}" icon="#{resource['images:chart-bar.png']}" action="#{Template.setWindow( 3 )}" update=":contentPanelGroup :headerForm :msgsArea" />
<p:menuitem value="#{msgs.ViewEnum_REPORT}" icon="#{resource['images:documents.png']}" action="#{Template.setWindow( 4 )}" update=":contentPanelGroup :headerForm :msgsArea" />
</p:dock>
</h:form>
</div>
<p:growl id="msgsArea" life="5000"/>
<ui:debug/>
</h:body>
TemplateBean looks like this:
#Named(value="Template") // CDI
#SessionScoped // CDI
public class TemplateBean implements Serializable {
private static final long serialVersionUID = -8230221469543897876L;
private Integer window = 2;
// Some getters ...
// Get Window
public Integer getWindow() {
return window;
}
public void setWindow( Integer window ) {
this.window = window;
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage( FacesMessage.SEVERITY_INFO, getCurrentViewTitle(), getCurrentViewTitle() )
);
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage( FacesMessage.SEVERITY_ERROR, getCurrentViewTitle(), getCurrentViewTitle() )
);
}
}
ViewEnum (which is used for choosing which view is shown):
public enum ViewEnum {
TRANSFER ( "hard-drive-download.png", "/private/VideoTransfer.xhtml" ),
STATUS ( "gears.png", "/private/ProcessStatus.xhtml" ),
ORGANIZATION ( "folder.png", "/private/DataOrganization.xhtml" ),
VALIDATION ( "chart-bar.png", "/private/ProcessValidation.xhtml" ),
REPORT ( "documents.png", "/private/ReportGeneration.xhtml" ),
;
private String iconFileName;
private String view;
private StreamedContent icon = null;
private ViewEnum( String iconFileName, String view ) {
this.iconFileName = iconFileName;
this.view = view;
}
public String getIconFileName() {
return this.iconFileName;
}
public String getTranslationKey() {
return "ViewEnum_" + this.toString();
}
public StreamedContent getIcon() {
// irrelevant code ...
}
public String getView() {
return this.view;
}
}
The custom component:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:cmpnt="http://java.sun.com/jsf/composite/component">
<composite:interface componentType="videoStatusTableComponent">
<composite:attribute name="value" required="true"/>
<composite:attribute name="selection" required="true"/>
<composite:attribute name="selectionListener" required="true" method-signature="void listener(org.primefaces.event.SelectEvent)"/>
<composite:attribute name="selectionUpdate" required="false" default="#this"/>
<composite:attribute name="refreshListener" required="true" method-signature="void action()"/>
</composite:interface>
<composite:implementation>
<p:dataTable id="cmpntVideoList" var="video" value="#{cc.attrs.value}" rowKey="#{video.key}" style="clear:both;"
selection="#{cc.attrs.selection}" selectionMode="single" emptyMessage="#{cc.attrs.emptyValueListMsg}">
<p:ajax event="rowSelect" listener="${cc.selectionListener}" process="#this" update="${cc.attrs.selectionUpdate}"/>
<composite:insertFacet name="header"/>
<p:column headerText="Test">
#{video.humanReadableVideoId}
</p:column>
<f:facet name="footer">
<h:commandLink action="${cc.attrs.refreshListener}" style="float:right;">
<h:graphicImage library="images" name="button-rotate-cw_16.png"/>
<f:ajax render="cmpntVideoList" execute="#this"/>
</h:commandLink>
</f:facet>
</p:dataTable>
</composite:implementation>
</html>
#FacesComponent( "videoStatusTableComponent" )
public class VideoStatusTableComponent extends UINamingContainer {
public void selectionListener( org.primefaces.event.SelectEvent event ) {
FacesContext context = FacesContext.getCurrentInstance();
MethodExpression ajaxEventListener = (MethodExpression) getAttributes().get( "selectionListener" );
ajaxEventListener.invoke( context.getELContext(), new Object[] { event } );
}
}
The first sub-page (and its Bean), which includes the component:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:cmpnt="http://java.sun.com/jsf/composite/component">
<ui:composition>
<h:form id="contentForm">
<cmpnt:videoStatusTable id="transferingVideoList"
value="#{videoTransfer.tableModel}"
selection="#{videoTransfer.selectedTableReadyNotCompletelyTranferedVideo}"
selectionListener="${videoTransfer.onVideoSelection}"
selectionUpdate=":msgsArea"
refreshListener="${processStatus.refreshUncompletedVideos}"
>
</cmpnt:videoStatusTable>
</h:form>
</ui:composition>
</html>
#Named( value="videoTransfer" ) // CDI
#SessionScoped // CDI
public class VideoTransferBean implements Serializable {
private static final long serialVersionUID = -9019701853654362317L;
private VideoStatus selectedTableReadyNotCompletelyTranferedVideo;
private VideoStatusTableModel tableModel;
private List<Video> currentlyTranferingVideos = null;
// Other irrelevant code...
public VideoStatusTableModel getTableModel() {
return tableModel;
}
public void setSelectedTableReadyNotCompletelyTranferedVideo(VideoStatus selectedTableReadyNotCompletelyTranferedVideo) {
this.selectedTableReadyNotCompletelyTranferedVideo = selectedTableReadyNotCompletelyTranferedVideo;
}
public VideoStatus getSelectedTableReadyNotCompletelyTranferedVideo() {
return selectedTableReadyNotCompletelyTranferedVideo;
}
public void onVideoSelection( SelectEvent event ) {
FacesMessage msg = new FacesMessage( "Video Selected: " + ((VideoStatus) event.getObject()).getHumanReadableVideoId() );
FacesContext.getCurrentInstance().addMessage( null, msg );
}
}
Another sub-page that includes the same component (here the listeners don't work until I reload the page (via the dock or if I hit F5)):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:cmpnt="http://java.sun.com/jsf/composite/component"
>
<ui:composition>
<h:form id="contentForm">
<cmpnt:videoStatusTable
id="orphanVideoList"
value="#{DataOrganization.videoTableModel}"
selection="#{DataOrganization.selectedVideo}"
selectionListener="#{DataOrganization.onOrphanVideoSelection}"
selectionUpdate=":msgsArea"
refreshListener="#{DataOrganization.refreshOrphanVideos}"
/>
</h:form>
</ui:composition>
</html>
#Named(value="DataOrganization") // CDI
#SessionScoped // CDI
public class DataOrganizationBean implements Serializable, MonitoredBean {
private static final long serialVersionUID = 1686055743669628317L;
// Constants and variables
#EJB
private DataOrganizationEJB controller;
private Integer companyEntityID = null;
private VideoStatusTableModel videoTableModel;
private VideoStatus selectedVideo;
public void refreshOrphanVideos() {
setOrphanVideos(controller.getOrphanVideos(getCompanyEntityID()));
}
public void onOrphanVideoSelection(org.primefaces.event.SelectEvent event) {
this.setSelectedVideo(((VideoStatus) event.getObject()));
}
public VideoStatusTableModel getVideoTableModel() {
return videoTableModel;
}
public VideoStatus getSelectedVideo() {
return selectedVideo;
}
public void setSelectedVideo(VideoStatus selectedVideo) {
this.selectedVideo = selectedVideo;
}
}
Does anyone have a clue on how to avoid reloading the web page to get the component's listeners to work?
In web XML I have set the STATE_SAVING_METHOD to client.
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
N.B.:
I use JSF 2.0, Glassfish 3.1.2.2, Primefaces 3.4.
Thanks!
**** UPDATED ****
I found out the problem really comes from the components. If I use the exact same code without the use of components everything works fine.
Did anyone encountered this problem?
This looks very similar to some behaviors I have noticed and this issue found at: http://java.net/jira/browse/JAVASERVERFACES-2050
I had the same issue but you really should avoid doing this! You should do less generic components. It worked for me.

CommandButton inside dynamically rendered panelGroup fails to execute actionlistener

I have a very simple xhtml file where a panelGroup containing a commandButton is added to the page on clicking toggle button but this dynamically added commandButton fails to execute its actionlistener on being clicked.
Complete code below:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h:panelGroup id="checkDyna">
<h:panelGroup rendered="#{listRetriever.booleanStatus}" >
<h:form>
<p:commandButton value="check" process="#all" actionListener="#{listRetriever.xx()}"/>
</h:form>
</h:panelGroup>
</h:panelGroup>
<h:form>
<p:commandButton value="Toggle" actionListener="#{listRetriever.toggleBooleanStatus()}" update=":checkDyna"/>
</h:form>
</h:body>
</html>
Bean
#ManagedBean(name = "listRetriever")
#RequestScoped
public class ListRetriever implements Serializable {
private boolean booleanStatus;
public void toggleBooleanStatus(){
if (!booleanStatus)
booleanStatus=true;
}
public void xx(){
System.out.println("Invoked***");
}
public boolean isBooleanStatus() {
return booleanStatus;
}
public void setBooleanStatus(boolean booleanStatus) {
this.booleanStatus = booleanStatus;
}
}
On removing rendered="#{listRetriever.booleanStatus}" actionlistener is successfully invoked.
On making the bean ViewScoped too the problem is eliminated but I dont want to make it wider than RequestScoped.
I had this p:commandButton within a conditionally rendered panel whose conditional expression for rendering was evaluating to false while I was trying to execute the actionlistener. This was the cause of actionlistener not getting executed.

Categories

Resources