rendered attribute not working with request parameter - jsf

I am using JSF2.2 with primefaces 5.0. I have a xhtml file where there are two file Uploads where one should always be visible while other should be visible only when request parameter, named signmethod, is JAVAME.
<h:panelGrid>
<h:panelGroup>
<h:outputLabel for="selected_signmethod" value="Selected Signethod : "/>
<h:outputText id="selected_signmethod" value="#{param.signmethod}" />
</h:panelGroup>
<h:panelGroup>
<b>Select file(s) to upload:</b>
</h:panelGroup>
</h:panelGrid>
<h:form id="uploadForm" enctype="multipart/form-data">
<p:message for="file_upload"/>
<p:fileUpload id="file_upload" allowTypes="#{fileUploadView.allowedTypes}" label="Select file" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" update="growl" multiple="true" fileLimit="5"/>
<p:message for="javame_upload"/>
<h:panelGroup rendered="#{param.signmethod == 'JAVAME'}" >
<b>Select corresponding jar file(s) to upload:</b>
<p:fileUpload id="javame_upload" allowTypes="" label="Select Jar file for javame" fileUploadListener="#{fileUploadView.handleFileUpload}"
mode="advanced" dragDropSupport="false" multiple="true" fileLimit="5"/>
</h:panelGroup>
<p:commandButton ajax="false" id="signProceed" value="Proceed" action="#{fileUploadView.submit}"/>
</h:form>
But this seems to be not happening. Second upload component is not getting rendered at all. I am also printing value of param.signmethod so that to be sure that right value is getting into param.signmethod, which is correct. So whats stopping this component to get rendered.
Managed Bean code :
#ManagedBean
#ViewScoped
public class FileUploadView implements Serializable {
#ManagedProperty(value = "#{signBundleBean}")
private SignBundleBean signBundleBean;
static String uploadDirRoot = InitialisationHelper.getUploadDirRoot();
transient Map<String, Object> sessionMap;
ArrayList<Signing> signings;
String username;
SignMethod signMethod;
public FileUploadView() {
System.out.println("NEW FileUploadView created.");
}
#PostConstruct
public void init() {
System.out.println("#POstConstruct FileuploadView");
System.out.println("signMethod : " + signMethod);
sessionMap = FacesContext.getCurrentInstance().getExternalContext().getSessionMap();
signings = signBundleBean.getSignings();
username = (String) sessionMap.get("username");
}
public void handleFileUpload(FileUploadEvent e) {
String signId = "" + DatabaseHelper.genrateSigningId();
FacesContext ctx = FacesContext.getCurrentInstance();
UploadedFile uploadedFile = e.getFile();
String filename = uploadedFile.getFileName();
if (signId.equals("-1")) {
FacesMessage fm = new FacesMessage();
fm.setDetail("Database Connection not working. Please try later.");
fm.setSummary("DBConnection_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
//ctx.addMessage(null, fm);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
if (username == null) {
FacesMessage fm = new FacesMessage();
fm.setDetail("You are not in session to upload.");
fm.setSummary("Session_Error");
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
ctx.addMessage("uploadForm:file_upload", fm);
return;
}
Signing sg;
sg = new Signing(signId, username, filename, signMethod, false);
signings.add(sg);
System.out.println("Signing added : " + sg);
signBundleBean.setMaxParameters(SignParametersInitialisation.getNumberOfParameters(signMethod));
try {
InputStream is = uploadedFile.getInputstream();
OutputStream os = new FileOutputStream(sg.getUploadfile());
byte[] bytes = new byte[1024];
int read = 0;
while ((read = is.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
sg.setUploaded(true);
is.close();
os.close();
} catch (IOException ex) {
signings.remove(sg);
Logger.getLogger(FileUploadView.class.getName()).log(Level.SEVERE, null, ex);
}
FacesMessage fm = new FacesMessage();
fm.setDetail(filename);
fm.setSummary("FileUploaded");
fm.setSeverity(FacesMessage.SEVERITY_INFO);
//ctx.addMessage(null, fm);
ctx.addMessage(null, fm);
System.out.println(sg + " File uploaded to " + sg.getUploadfile());
}
}

Related

Display list of images using p:graphicImage in p:dataGrid after uploading image through p:fileUpload

i am uploading multiple images through p:fileUpload and showing uploaded images in datagrid but after upload the blank panel is created inside datagrid
<p:panelGrid columns="1" layout="grid" style="width: 1000px">
<p:outputLabel value="Upload Images"></p:outputLabel>
<p:fileUpload mode="advanced" multiple="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/" dragDropSupport="true"
update="messages,updimgsfields,carouselcomp" sizeLimit="100000"
fileUploadListener="#{drawingattachmnt.handleFileUpload}"></p:fileUpload>
<!-- <p:graphicImage id="gimPhoto" value="#{fileuploadSection.image}" /> -->
</p:panelGrid>
<p:fieldset id="updimgsfields" legend="Uploaded Images">
<p:dataGrid id="updimgsdatagrid" var="upldimg"
value="#{drawingattachmnt.uploadedimages}" columns="4">
<p:panel id="drawingattachmntpnl" header="#{upldimg.displayId}"
style="text-align:center">
<h:panelGrid columns="1" cellpadding="5"
style="width: 100%; height: 200px;">
<p:graphicImage value="#{upldimg.imgcontent}" cache="false"
stream="true">
<f:param id="imgId" name="photo_id" value="#{upldimg.id}" />
</p:graphicImage>
</h:panelGrid>
</p:panel>
<p:draggable for="drawingattachmntpnl" revert="true"
handle=".ui-panel-titlebar" stack=".ui-panel" />
</p:dataGrid>
</p:fieldset>
// file upload function inside bean
public void handleFileUpload(final FileUploadEvent event) throws IOException {
if (event.getFile().getContents() != null) {
final ByteArrayOutputStream byteArrOutputStream = new ByteArrayOutputStream();
BufferedImage uploadedImage = null;
byte[] imageBytes = null;
try {
final String imageType = event.getFile().getContentType() != null
|| event.getFile().getContentType().split("/") != null ? event.getFile().getContentType()
.split("/")[1] : "jpeg";
uploadedImage = ImageIO.read(event.getFile().getInputstream());
ImageIO.write(uploadedImage, imageType, byteArrOutputStream);
imageBytes = byteArrOutputStream.toByteArray();
updimg.setImgcontent(new DefaultStreamedContent(new ByteArrayInputStream(imageBytes), imageType));
updimg.setId(UUID.randomUUID().toString().substring(0, 8));
updimg.setDisplayId("FIG: ");
uploadedimages.add(updimg);
} catch (final IOException io) {
} finally {
try {
byteArrOutputStream.close();
// imageInputStream.close();
} catch (final IOException e1) {
e1.printStackTrace();
}
uploadedImage.flush();
}
final FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("Successful", "File uploaded Successfully "));
}
// List POJO
import org.primefaces.model.StreamedContent;
public class UploadImage {
public String displayId;
public String id;
public StreamedContent imgcontent;
public UploadImage() {
}
public UploadImage(final String id, final String displayId, final StreamedContent imgcontent) {
this.id = id;
this.displayId = displayId;
this.imgcontent = imgcontent;
}
#Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UploadImage other = (UploadImage) obj;
if (this.id == null ? other.id != null : !this.id.equals(other.id)) {
return false;
}
return true;
}
public String getDisplayId() {
return displayId;
}
public String getId() {
return id;
}
public StreamedContent getImgcontent() {
return imgcontent;
}
#Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
public void setDisplayId(final String displayId) {
this.displayId = displayId;
}
public void setId(final String id) {
this.id = id;
}
public void setImgcontent(final StreamedContent imgcontent) {
this.imgcontent = imgcontent;
}
}
I need to show images in datagrid dynamically, but i am getting blank image panel inside datagrid. what should be done ?

JSF Primefaces pass parameter to fileupload

JSF 2.2 - Primefaces 4.0 - JBoss Wildfly
Hi, I am trying to pass a parameter value to the file upload handler.
I tried a few suggestions I found, but can't get it to work.
I stepped a few steps back
I need the #{fileUploadController.newItemId} in the controller
When going to the file update page it is done with i.e. this URL
/fileUpload.jsf?newItemId=10
I tried what it mentioned in
How to send parameter to fileUploadListener in PrimeFaces fileUpload
and
Passing value to the backing bean with PrimeFaces file upload
fileUpload.xhtml
<f:metadata>
<f:viewParam name="newItemId"
value="#{fileUploadController.newItemId}" />
<f:viewAction action="#{fileUploadController.loadData()}" />
</f:metadata>
<h:form id="item" enctype="multipart/form-data">
<p:messages id="messages" />
<p:panelGrid styleClass="panelGridCenter">
<p:row>
<p:column>
<p:fileUpload
fileUploadListener="#{fileUploadController.handleFileUpload}"
validator="#{fileUploadController.validateFile}" mode="advanced"
dragDropSupport="false" update="messages" sizeLimit="1000000"
fileLimit="100" allowTypes="/(\.|\/)(gif|jpe?g|png)$/">
</p:fileUpload>
</p:column>
</p:row>
</p:panelGrid>
</h:form>
FileUploadController.java
public void handleFileUpload(FileUploadEvent event) {
try {
// Need item id here :)
UploadedFile file = event.getFile();
InputStream inputStream = file.getInputstream();
FileOutputStream outputStream = new FileOutputStream(file.getFileName());
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (true) {
bytesRead = inputStream.read(buffer);
if (bytesRead > 0) {
outputStream.write(buffer, 0, bytesRead);
} else {
break;
}
}
outputStream.close();
inputStream.close();
Long imageId = serviceSLSB.saveImage(itemId, file, buffer);
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded and saved with id." + imageId);
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (Exception e) {
String errorMessage = getRootErrorMessage(e);
FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Saving unsuccessful");
facesContext.addMessage(null, m);
}
}
public void loadData() {
if (newItemId == null) {
String message = "Bad request. Please use a link from within the system.";
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
return;
} else {
String message = "Your are adding images to item with id : " + newItemId;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
return;
}
}
I just found that my controller was only request scoped, after changing it to
#ViewScoped
#Named
public class FileUploadController implements Serializable
I of cause still have the item id, and can now add images to that item.
Thanks for the comments guys

p:fileupload won't invoke listener at first browse?

I find it really weird I don't know why but when I first select an image it won't invoke the upload listener but at the second select it work perfectly.
View code :
<h:form enctype="multipart/form-data;charset='UTF-8'">
<p:fileUpload id="clientProfile" auto="true" sizeLimit="2097152" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" fileUploadListener="#{clientController.uploadListener}" mode="advanced" multiple="true" label="browse" update="imagePreview" invalidFileMessage="Invalid image" invalidSizeMessage="too large size"/>
<p:outputPanel id="imagePreview">
<ui:repeat value="#{clientController.listImages}" var="imageId">
<div style="float:left;margin-right:10px; margin-bottom: 5px;">
<p:graphicImage value="#{clientController.previewImage}" height="135" width="135" styleClass="images">
<f:param name="imageId" value="#{imageId}"/>
</p:graphicImage>
</div>
</ui:repeat>
</p:outputPanel>
</h:form>
Bean code :
private Map<UUID, UploadedFile> uploadedFiles = new HashMap<UUID, UploadedFile>();//used for preview
private List<String> listImages = new ArrayList<String>(); //list of id from map which is UUID
private List<UploadedFile> clientProfile = new ArrayList<UploadedFile>();
public void uploadListener(FileUploadEvent event) {
clientProfile.add(event.getFile());
final UUID uuid = UUID.randomUUID();
uploadedFiles.put(uuid, event.getFile());
listImages.add(uuid.toString());
System.out.println(listImages.size());
System.out.println(clientProfile.size());
}
public List<String> getListImages() {
return listImages;
}
public StreamedContent getPreviewImage() {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
StreamedContent image = null;
String imageId = JsfUtil.getRequestParameter("imageId");
System.out.println(imageId);
if (imageId != null) {
UUID imageIndex = UUID.fromString(imageId);
return new DefaultStreamedContent(new ByteArrayInputStream(uploadedFiles.get(imageIndex).getContents()));
}
}
return null;
}

primefaces reload galleria

reference: http://www.primefaces.org/showcase/ui/galleria.jsf
my page:
<p:galleria id="merchant-gallery" value="#{testController.imageIds}" var="item" autoPlay="false" >
<p:graphicImage width="300" value="#{imageStreamer.image}" >
<f:param name="id" value="#{item}" />
</p:graphicImage>
</p:galleria>
i tried enclosing <p:galleria> in a form and added a <p:remoteCommand name="updateme" update="#form"/> but after calling updateme it simply just make the galleria blank.
*Update
testController bean:
public List<Integer> getImageIds() {
int aId = (Integer) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user_id");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("TEST2PU");
EntityManager em = emf.createEntityManager();
TypedQuery<Merchant> tp = em.createQuery("SELECT a FROM Account a WHERE a.id = :id", Account.class);
tp.setParameter("id", aId);
current = tp.getSingleResult();
Collection rawPhotoCollection = current.getPhotoCollection();
imageIds = new ArrayList<Integer>(rawPhotoCollection);
List<Photo> photoList = new ArrayList<Photo>(rawPhotoCollection);
for (int i = 0; i < photoList.size(); i++) {
int imageId = photoList.get(i).getId();
imageIds.set(i, imageId);
}
return imageIds;
}
imageStreamer bean:
#EJB
private test.controller.photo.PhotoFacade ejbFacade;
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
Map<String, String> param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String id = param.get("id");
Photo image = ejbFacade.find(Integer.valueOf(id));
return new DefaultStreamedContent(new ByteArrayInputStream(image.getImage()));
}
}
I reworked your example and have the same issue. It is not related to your upload or remotecommand. I think it is a bug in primefaces. See http://code.google.com/p/primefaces/issues/detail?id=4840 for similar issue.
When I do the command
PrimeFaces.cw('Galleria','widget_companydetail_merchant-gallery',{id:'companydetail:merchant-gallery',transitionInterval:0,panelWidth:640,panelHeight:480,custom:false},'galleria');
in firebug console, the galleria reappears.
So when changing the remotecommand and adding the javascript to oncomplete it works.
<p:remoteCommand name="updateme" update="#form" oncomplete="PrimeFaces.cw('Galleria','widget_companydetail_merchant-gallery',{id:'companydetail:merchant-gallery',transitionInterval:0,panelWidth:640,panelHeight:480,custom:false},'galleria');"/>

Navigation to call action for bean class

I am using JSF 2.0 and PrimeFaces 3.0. I have uploaded the images and have to crop the image. The images are uploaded and successfully displayed in the upload pages.
When I select the images and click the crop button the corresponding crop bean is not called. If I don't select the image and click the crop button the corresponding crop bean class is called but a NullPointerException occurred. What is the problem?
The Facelet view is:
<h:form>
<p:panel header="FILE UPLOAD WITH CROPPER" style="width:900px; margin: 0 auto; margin-top:0px">
<p:fileUpload fileUploadListener="#{photoUploadAction.handleImageUpload}"
mode="advanced"
update="getImageId,messages" auto="false"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>
<p:growl id="messages" showDetail="true"/>
<p:growl id="uploadMessages" showSummary="true" showDetail="true"/>
<h:panelGrid columns="2" >
<p:imageCropper value="#{photoUploadAction.croppedImage}" id="getImageId"
image="images/#{photoUploadVO.imageName}"/>
</h:panelGrid>
<p:commandButton value="Crop" update="getImageId" action="#{imageCropperBean.crop}" />
</p:panel>
</h:form>
BACKING BEAN for ImageCropper:
#ManagedBean(name="imageCrop")
#RequestScoped
public class ImageCropperBean {
private CroppedImage croppedImage;
private String newFileName;
private String imageName;
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
System.out.println("TEH IMAGE NAME ===="+imageName);
this.imageName = imageName;
}
public String getNewFileName() {
return newFileName;
}
public void setNewFileName(String newFileName) {
System.out.println("AAAAAAAAAAAAAA"+this.newFileName);
this.newFileName = newFileName;
}
public CroppedImage getCroppedImage() {
return croppedImage;
}
public void setCroppedImage(CroppedImage croppedImage) {
System.out.println("cRRRRRRRRRRRRR"+croppedImage);
this.croppedImage = croppedImage;
}
public ImageCropperBean(){
}
public String crop() {
System.out.println("WELCOMEMMMMMMMMMMMMMM");
FacesContext context = FacesContext.getCurrentInstance();
ImageCropperBean imageCropperBean = (ImageCropperBean) context.getApplication().evaluateExpressionGet(context, "#{imageCropperBean}", ImageCropperBean.class);
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
newFileName = servletContext.getRealPath("") + File.separator + "cropImage" + File.separator+ "croppedImage.jpg";
System.out.println("FILE NAME NAME NAME NAME "+newFileName);
String file = new File(newFileName).getName();
System.out.println("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"+file);
imageCropperBean.setImageName(file);
File fileFolder = new File("e:/Mecherie_project/image_web/WebContent/cropImages",file);
System.out.println("FILE ANE"+file);
// String target=null;
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(fileFolder);
System.out.println("HHHHHHHHHH=="+imageOutput);
imageOutput.write(croppedImage.getBytes(), 0, croppedImage.getBytes().length);
imageOutput.close();
FacesMessage msg = new FacesMessage("Succesful", file
+ " is cropped.");
FacesContext.getCurrentInstance().addMessage(null, msg);
} catch (FileNotFoundException e) {
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not Cropped!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
// System.out.println("ghfhgfghgh"+target);
return "success";
}
}

Resources