Dynamic Graphic Image - jsf

I am trying to have dynamic graphic image from database.
I found a few according questions here in SO but somehow it does not work.
Page:
<p:dataList styleClass="routeDatalist" value="#{searchRoutesBean.foundRoutes}" var="uiRoute">
<p:outputLabel value="USERID #{uiRoute.owner.id}"/>
<h:graphicImage value="#{photoStreamer.streamedContent}" styleClass="userProfileImage">
<f:param name="userId" value="#{uiRoute.owner.id}" />
</h:graphicImage>
<p:/dataList>
I get my list of objects from backing bean
#SessionScoped
#ManagedBean
public class SearchRoutesBean{
private List<UIRoute> foundRoutes;
...
}
I created a backing bean which should take the userimage bytearray and create a streamed content
#ManagedBean(name = "photoStreamer")
#ApplicationScoped
public class PhotoStreamer implements Serializable {
#Autowired
UserService userService;
private StreamedContent streamedContent;
public StreamedContent getStreamedContent() {
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
String userId = externalContext.getRequestParameterMap().get("userId");
if (StringUtils.isNotBlank(userId)) {
User user;
try {
user = userService.getUserById(Long.valueOf(userId));
byte[] image = user.getProfileJpegImage();
if (image != null && image.length > 0) {
return new DefaultStreamedContent(new ByteArrayInputStream(
image), "image/jpeg");
} else {
BufferedImage bufferedImg = new BufferedImage(250, 350,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufferedImg.createGraphics();
g2.drawString("User has no ProfilImage", 50, 175);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedImg, "png", os);
return new DefaultStreamedContent(new ByteArrayInputStream(
os.toByteArray()), "image/png");
}
} catch (NumberFormatException | UserServiceException | IOException e) {
throw new IllegalStateException(e);
}
}
return null;
}
}
I dont know why but the given parameter userId is always null.
Does someone know what could be the problem?
BR

What about
<p:dataList styleClass="routeDatalist" value="#{searchRoutesBean.foundRoutes}" var="uiRoute">
<p:outputLabel value="USERID #{uiRoute.owner.id}"/>
<h:graphicImage value="#{photoStreamer.streamedContent(uiRoute.owner.id)}" styleClass="userProfileImage"/>
<p:/dataList>
+
public StreamedContent getStreamedContent(String userId) {
if (StringUtils.isNotBlank(userId)) {
User user;
try {
...
}

The problem was that dataList need to be wrapped into h:form.
Thx to Makky who send me this tutorial
http://www.youtube.com/watch?v=imiBwk_xqaE

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 ?

p:graphicImage with viewscoped

page:
<p:graphicImage value="#{testController.QR}" />
testController bean:
private StreamedContent QR;
private ByteArrayOutputStream rawQR;
public StreamedContent getQR() {
if (rawQR != null) {
rawQR = QRCode.from("test").to(ImageType.PNG).stream();
ByteArrayInputStream is = new ByteArrayInputStream(rawQR.toByteArray());
QR = new DefaultStreamedContent(is, "image/png");
return QR;
} else {
return null;
}
}
I'm trying to display a QR image on the page.
with SessionScoped the above code works, but with ViewScoped it displays a broken image icon, i need my bean to be ViewScoped. What am i missing here?
QR Reference: http://viralpatel.net/blogs/create-qr-codes-java-servlet-qr-code-java/

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');"/>

show UploadedFile content from Primeface's p:fileUpload in same form without refresh

I'm trying to implement an ImageUpload and show the uploaded Image immediately on same page using DynamicImage. My Problem is, I can't force the p:graphicImage content be refreshed and show the uploaded image after uploading it.
#ManagedBean(name = "myformbean")
#Controller
#ViewScoped
#Data
public class MyFormBean implements Serializable {
private StreamedContent listImage = null;
public StreamedContent getListImage() {
if (listImage == null) {
try {
listImage = new DefaultStreamedContent(new FileInputStream("E:/t.jpg"), "image/png"); // load a dummy image
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return listImage;
}
public void handleFileUpload(FileUploadEvent event) {
final UploadedFile uploadedFile = event.getFile();
listImage = new DefaultStreamedContent(new ByteArrayInputStream(uploadedFile.getContents()), "image/png");
}
}
And in .xhtml file:
<p:graphicImage value="#{myformbean.listImage}" />
if your upload does the work
all you need to do is to set id to <p:graphicImage like this
<p:graphicImage id="refreshMe" value="#{myformbean.listImage}" />
and in your <p:fileUpload set the update attribute to point to the image
like this
<p:fileUpload auto="true" ... update="refreshMe" ....

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