Primefaces p:graphicImage dynamicContent failed to load 404 - primefaces

Displaying p:graphicImage dynamic content keeps me busy already quite a few days now. Can anyone help me please, I would appreciate that very much.
I have a straigtforward approach of p:graphicImage as StreamedContent of imgage.jpg loaded into a list (TreeMap).
This is my xhtml snippet:
<p:dataView var="id"
value="#{fotoViewer.imagesViewTree.entrySet()}"
gridIcon="pi pi-th-large" listIcon="pi pi-bars">
<p:dataViewListItem>
<h:panelGrid columns="2" style="width:100%" columnClasses="">
<p:graphicImage value="#{id.value.streamedImage}"
style="max-width: 30vw; max-height: 53vh;" cache="false"
stream="true" styleClass="w3-round-xlarge" />
<p:outputPanel>
<h:panelGrid columns="2" cellpadding="5">
<h:outputText value="Id:" />
<h:outputText value="#{id.key}" style="font-weight: bold" />
<h:outputText value="naam:" />
<h:outputText value="#{id.value.naam}" style="font-weight: bold" />
</h:panelGrid>
</p:outputPanel>
</h:panelGrid>
</p:dataViewListItem>
</p:dataView>
I can see the dynamicContents sitting in my browser which looks fine as far as can judge, here it is:
(img id="cac010:j_id_11:0:j_id_14" src="/cJsfComponents1/faces/javax.faces.resource/dynamiccontent.properties?ln=primefaces&v=8.0&pfdrid=8ca67d0788631c82cdee936b119abf8e&pfdrt=sc&pfdrid_c=false&uid=6d617a80-1fe2-4b5f-80b8-b7868dac9f10" alt="" class="w3-round-xlarge" style="max-width: 30vw; max-height: 53vh;")
I don't understand why the server does not deliver the contentStream. It responds with an http-status-code-404.
Thx in advance for any help!

Found the solution given over 8 years ago which is exactly where I was looking for. And.... it works great!
How to use <p:graphicImage> with DefaultStreamedContent in an ui:repeat?
How to use <p:graphicImage> with DefaultStreamedContent in an ui:repeat?
Since I'm using PrimeFaces V8.0 there is some different implementation regarding how to get the StreamedContent of the image. Here's my ImageStreamer method that does it:
public StreamedContent getStreamedContentOfImage(ByteArrayInputStream bais) {
StreamedContent graphicImage = null;
graphicImage = DefaultStreamedContent.builder().contentType("image/png").stream(() -> {
try {
return bais;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}).build();
return graphicImage;
}
Maybe it helps someone in future!?

#tandraschko: thx for your quick reply. The link you included was several days ago also my startingpoint. I must say helas, that it is a very bad example! The code doesn't work and is incomplete. The link How to use <p:graphicImage> with DefaultStreamedContent in an ui:repeat? put me on the right track. I've got it all working now very well and I am getting more and more enthousiastic about PrimeFaces! It's a pitty that not all of the documentation is accurate, actual and clear setup, with all levels of users in mind!. Thx anyway!

Related

Combine Drag&Drop and Reorder in a p:dataTable

I need to combine Drag and Drop and Reorder on a DataTable row. I know that there are ways to do this on different columns (like one column for the reorder, the other one for Drag and Drop), but I need to do it on one Element.
I tried different ways, but nothing worked. The Problem is, that once the reordering is triggered, I can't drop it in the area. It always returns to the end of the table.
Getting the mouse position wouldn't work, because i need to make it responsive and usable for mobile devices.
HTML:
<p:fieldset id="availableCarsField" legend="Available Cars">
<p:dataTable id="availableCars"
var="car"
widgetVar="widgetVarAvailableCars"
draggableRows="true"
value="#{dndCarsView.cars}">
<p:column id="dragColumn"style="width:20px;">
<h:outputText id="test" value="#{car.id}"/>
<p:draggable helper="clone" revert="true"/>
</p:column>
</p:dataTable>
</p:fieldset>
<!-- ........................... DROP ...........................-->
<p:fieldset id="selectedCars" legend="Selected Cars">
<p:outputPanel id="dropArea">
<h:outputText value="!!!Drop here!!!"
rendered="#{empty dndCarsView.droppedCars}"
style="font-size:24px;"/>
<p:dataTable id="selectedCarsTable"
var="car"
value="#{dndCarsView.droppedCars}"
rendered="#{not empty dndCarsView.droppedCars}">
<p:column headerText="Id">
<h:outputText value="#{car.id}"/>
</p:column>
</p:dataTable>
</p:outputPanel>
</p:fieldset>
<p:droppable for="selectedCars"
tolerance="touch"
activeStyleClass="ui-state-highlight"
onDrop="handleDrop"
datasource="availableCars">
<p:ajax listener="#{dndCarsView.onCarDrop}"
process="#form"
update="dropArea availableCars"/>
</p:droppable>
JS:
function handleDrop(event, ui) {
var droppedCar = ui.draggable;
droppedCar.fadeOut('fast');
}
Bean (in case it's required):
public class DNDCarsView implements Serializable {
private List<Car> cars;
private List<Car> droppedCars;
#PostConstruct
public void init() {
cars = createCars(9);
droppedCars = new ArrayList<>();
}
public List<Car> createCars(int size) {
List<Car> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
list.add(new Car("" + i, "Brand" + i, i * 2000, "Color" + i));
}
return list;
}
public void onCarDrop(DragDropEvent ddEvent) {
Object car = ddEvent.getData();
droppedCars.add((Car) car);
cars.remove(car);
}
public void onReorder(ReorderEvent event) {
Car car = cars.get(event.getFromIndex());
cars.add(event.getToIndex(), car);
cars.remove(event.getFromIndex());
}
//Getter & Setter
}
Is there anyway to combine these two and get this running?
Thanks in advance
Edit:
I want to reorder the rows inside the DataTable and also be able to drop the dragged row into the fieldset.
Primefaces 6.2.12
JSF 2.2
Edit 2:
After month of trying I haven't found a good solution for my problem. Just thought, that I might share this here, if someone else deals with this problem.
I seems like there is no way to realize Drag&Drop in combination with columnreorder on one element (in my case p:column). The problem is, that always the reorderevent is triggered when dragged. When dropped into the droparea, the dragId of the dragged element is null (because we started with the reorder-event but ended with the event for drag and drop)
Due to the fact that I wasn't allowed to change anything which wasn't my class I didn't manage to fix this. I ended up to separate the actions onto two elementes. So I made a drag handle where the user can drag the element into the droparea and realized the reorder on the column.
If I was blind and someone knows an answer to this feel free to write. Maybe it might help someone. At least it would be interesting whether there is a way to do so

progressbar-primefaces3.5 with two different managed beans

Hi I have a xhtml (html1), which has a save button. The click of this renders method1 of Managedbean1. This method1, inturn called method2 of ManagedBean2 and on success, brings up html1. Is there a way to have a progressbar in html1 and see though both the managedbean actions and display till html2 comes up. So far, all the examples i see have one ui and one managedbean.
#mareckmareck - Thanks for your reply. This is what I am trying to do. - Please see the code excerpts.
regbudget.xhtml
<div id="actionButtonBarNew">
<p:panel styleClass="buttonPanelNew" >
<p:commandButton id="saveBudget" value="Save Budget" type="button" onclick="pbAjax.start();startButton1.disable();" widgetVar="startButton1" />
<p:progressBar widgetVar="pbAjax" value="#{regbudgetMgmtMB.handleBudgetEvent}" ajax="true" labelTemplate="{value}%">
<p:ajax event="complete" listener="#{progressBean.onComplete}"
update="growl" oncomplete="startButton1.enable()" render="#form" update="messages,fcotcol" /> />
</p:progressBar>
</p:panel>
</div>
=======================
RegbudgetBean (//regbudgetMgmtMB)
------------------------------
public void handleBudgetEvent(AjaxBehaviorEvent evt){
// more codee--- code here --
try {
HourAllocationManagedBean hbean = getCurrentInstanceOfHourAlloc();
hbean.calculateHourAlloc();
}
===============================
HourAllocationManagedBean
public void calculateHourAlloc() {
if(logger.isDebugEnabled()){
logger.debug("HourAllocationManagedBean: calculateHourAlloc");
}
//more code here---
try{
FacesContext.getCurrentInstance().getExternalContext().redirect("/pages/budget/hourAlloc.xhtml");
}
====================================================
As you can see, i am in regbudget.xhtml, call handleBudgetEvent in RegbudgetBean , which inturn calls calculateHourAlloc in HourAllocationManagedBean and displays hourAlloc.xhtml. My requirement is to have the progressbar in regbudget.xhtml to show progress till the houralloc.xhtml is displayed. Could you please let me know if you have any suggestions. Thanks.

Update the page with command bouton primefaces

I want to get the value of the input Textarea and show it in the same page by clicking on the command button "compiler "
however i don't get any result ! and the contnet is only shown when I update with the browser updater
Sh How do I upate the page and the managed beans to show the content of a primefaces textarea in the same page
this is the code:
<p:layoutUnit position="west" size="520" header="Code à executer" resizable="true" >
<h:form id="moncode">
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="guest.xhtml" styleClass="myButtonClass" />
</h:form>
</p:layoutUnit>
<p:layoutUnit position="east" size="550" header="Resultat d'execution" resizable="true" >
<h:outputText value="#{fichier.code}" />
</p:layoutUnit>
<p:layoutUnit position="south" >
my application is about compiling a given code: I write a code and then I executed with the button "compiler" so a file will be created however the file is always created with "null" and I think because the var "code" is not yet set in the managed bean that why I want to update the page so the managed bean ill be set here is compile:
`
private String code;
private String error;
public String getCode() {
return code;
}
public String getError() {
return error;
}
public void setCode(String code) {
this.code = code;
}
public void compile() throws IOException {
File file = new File("C:\\Users\\Rad1\\test.c");
PrintWriter ecrivain;
ecrivain = new PrintWriter(new BufferedWriter (new FileWriter(file)));
ecrivain.println(code);
ecrivain.close();
`
There are two ways to achieve what you want: either by using a synchronous submit of a form with a subsequesnt postback, or by sending an AJAX request to partially update necessary parts of the page.
Synchronous submit
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="#{fichier.action}" styleClass="myButtonClass" ajax="false" />
<h:outputText id="upd" value="#{fichier.code}" />
with action method
public String action() {
//do business job
return null;
}
This way a fields will be refreshed by making a postback. Don't forget that the bean Fichier must be view scoped. Note the ajax="false" attribute of <p:commandButton>.
AJAX call
<p:inputTextarea id="mycode" value="#{fichier.code}" rows="17" cols="50" />
<p:commandButton value="compiler" id="btn3" action="#{fichier.action}" styleClass="myButtonClass" update="upd" />
<h:outputText id="upd" value="#{fichier.code}" />
with the same action method
public String action() {
//do business job
return null;
}
This way only the contents of <h:outputText> will be updated after AJAX call is finished. Don't forget that the bean Fichier should also be view scoped. Note that id attribute of <h:outputText> must be specified.
Actually, you don't call the action itself. Your action forwards to a certain page. There is no race condition or syncronization problems in a JSF action betwwen setting the properties and the action itself. I recommend you to read JSF life cycles tutorial by BalusC Aplly request values phase run before the action.
Try to call action on command Button.
<p:commandButton value="compiler" id="btn3" action="#{fichier.compile}" update="outputCode" styleClass="myButtonClass" />
Add an id attribute to your output panel and specify it in the action button.
<p:layoutUnit id="outputCode" position="east" size="550" header="Resultat d'execution" resizable="true" >
<h:outputText value="#{fichier.code}" />
</p:layoutUnit>
P.S. It is also good to read this BalusC answer for better understanding of actions, Ajax/non Ajax request etc.

CommandLink within PrimeFaces Mobile DataList is not referencing the correct element after being filtered

I'm working on a PrimFaces mobile employee directory app and have hit a road block. Its a simple app which consists of two screens (employee filter/list + employee detail).
I was able to load a datalist without issues. Clicking on the commandlink properly loads the employee detail. I then was able to implement a custom employee filter which was somewhat painful, but I got that working. The filter works by repopulating the employee datalist's model with the filtered results.
The issue is, after I use the filter to repopulate/filter the datalist, clicking on an employee (commandlink) does not pass the correct employee ID back to the model. Instead, the employee ID that was there before the filter was performed is passed. It's like the JSF model is not matching the DOM.
I'm using:
TomEE (MyFaces 2.1.7)
PrimeFaces Mobile 0.9.3
PrimeFaces 3.3
Both of my backing models are #ViewScoped
<pm:view id="peopleDirView" onload="">
<pm:header title="People Directory" fixed="true">
</pm:header>
<pm:content>
<h:form id="form">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<p:inputText id="searchCriteria" value="#{peopleDirectoryBean.criteria}" type="search"
onkeyup="delay(function() {filterResults();}, 500);" />
</fieldset>
</div>
<p:dataList id="peopleDataList" value="#{peopleDirectoryBean.people}" var="person" rowIndexVar="rowIndex">
<p:column>
<p:commandLink action="#{peopleDirectoryDetailBean.loadPersonDetail(person.employeeId)}" update=":personDetailView">
<img src="/phonedir/people/image/#{person.employeeId}?width=75&height=100" width="90" height="100"
onerror="missingImage(this);" id="per-search-picture" />
<h1>#{person.nameLast}, #{person.nameFirst}</h1>
<p>#{person.deptName}</p>
<p>#{person.jobTitle}</p>
</p:commandLink>
</p:column>
</p:dataList>
<p:remoteCommand name="filterResults" update="peopleDataList" action="#{peopleDirectoryBean.peopleSearch}" />
</h:form>
</pm:content>
<pm:footer fixed="true">
<pm:navBar>
<p:button value="People" icon="home" href="#peopleDirView?reverse=true" styleClass="ui-btn-active" />
<p:button value="Locations" icon="info" href="#locationsView?reverse=true" />
<p:button value="Conference" icon="search" href="#conferenceRoomsView?reverse=true" />
</pm:navBar>
</pm:footer>
<script>
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
function missingImage(image) {
image.onerror = "";
image.src = "missing-person.jpg";
return true;
}
</script>
</pm:view>
Okay, looks like the mistake was on my part.
In my backing bean, I was using javax.inject.Named (#Named) because I was trying to make use of my container's ability to do CDI. Once I changed it to javax.faces.bean.ManagedBean (#ManagedBean ) the problem went away. The TomEE docs state that it supports #Named so I'm not sure what the deal is.

java.awt.HeadlessException when calling JOptionPane.showMessageDialog in backing bean action method

I'm trying the following:
labelconfig.xhtml:
<h:form id="ok">
<h:commandButton value="click">
<f:ajax event="click" listener="#{canvasController.oeps}" />
</h:commandButton>
</h:form>
And I'm trying to get it here:
CanvasController.java
#ManagedBean(name = "canvasController")
#SessionScoped
public class CanvasController
public void oeps(AjaxBehaviorEvent event) {
JOptionPane.showMessageDialog(null, "SUCCES3");
}
}
But when I click the button, I get:
serverError: class java.awt.HeadlessException
How is this caused and how can I solve it?
You are trying to call Swing from server application without any desktop GUI. Instead of JOptionPane use logger or FacesContext.addMessage to get feedback. If for some reason you do want to control Swing app through JSF make sure DISPLAY etc are set but then I suggest rephrasing your question.