p:graphicImage with viewscoped - jsf

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/

Related

Handle file download request in JSF 2.1 + PrimeFaces 5.1

I have a web application in JSF 2.1 + PrimeFaces 5.1 that has a datatable where I list records from a database. Each row can be expanded to show some details, and there I have a button to download a XML file that has its contents saved in the DB.
<p:dataTable id="event_queue_table_id" var="event" value="#{eventQueueBean.eventQueue}" rowKey="#{event.id}">
...
<p:rowExpansion>
...
<p:commandButton ajax="false" icon="ui-icon-arrowthick-1-s" actionListener="#{eventQueueBean.downloadXml(event.id)}">
<p:fileDownload value="#{fileBean.file}"/>
</p:commandButton>
</p:rowExpansion>
</p:dataTable>
I want to fetch the XML contents from the DB, create the file and prompt the user to open/save it. The bean that controls this datatable looks like this:
#ManagedBean
#ViewScoped
public class EventQueueBean implements Serializable {
#ManagedProperty(value="#{fileBean}")
private FileBean fileBean;
public void downloadXml(BigDecimal eventId) {
try {
logger.entry(eventId);
DtoGetXmlEvent dtoGetXmlEvent = null;
if (eventId != null) {
dtoGetXmlEvent = eventQueueService.getXmlEvent(eventId);
String xml = dtoGetXmlEvent.getXml();
if (xml == null) {
// show error message stating that file does not exist
} else {
this.fileBean.download(xml, eventId + ".xml", "application/xml");
}
}
logger.exit();
} catch (...)
}
}
}
And my FileBean is:
#ManagedBean
#ViewScoped
public class FileBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(FileBean.class);
private StreamedContent file;
public FileBean() {
logger.entry();
}
public void download(String content, String fileName, String contentType) {
logger.entry(fileName, contentType);
InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
file = new DefaultStreamedContent(stream, contentType, fileName);
logger.exit();
}
public StreamedContent getFile() {
return file;
}
public void setFile(StreamedContent file) {
this.file = file;
}
When I try to download an empty XML (the DB retrieves NULL content), the open/save file prompt does not show, but if I try to refresh the page I get the "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier.". How can I avoid this?

Dynamic Graphic Image

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

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