Unable to load the image dynamically in jsf - java

I am working on some project, and i need to implement the image upload and view the image functionality,
but i am facing some problem here.
I am unable to display the image, can you please help me.
I am using p:fileload from primefaces, And i am storing all the images in bin folder of jboss server(E:\jboss-as-7.1.1.Final\bin\BrandImages\logo.gif).
And storing that path in MYSQL DB, till now it is working fine. But when i am trying to display the image by calling getBrandDetails(), it is unable to display. Can you please tell me how can i solve this problem???
In web.xml
In web.xml i added filter and mime...
Xhtml
<h:form enctype="multipart/form-data">
<h:panelGrid id="brandDetails_Panel" columns="2" columnClasses="plabel, pvalue" styleClass="ui-panelgrid">
<h:outputLabel for="brand_img_url" value="Brand Image" />
<p:fileUpload id="brand_img_url" fileUploadListener="#{brandBean.handleFileUpload}"
mode="advanced" sizeLimit="100000" allowTypes="/(\.\/)(gif|jpe?g|png)$/"/>
<h:outputLabel value="" />
<p:graphicImage value="#{brandBean.brand_image}" alt="The image could not be found."/>
</h:panelGrid>
<f:facet name="footer" >
<center>
<p:commandButton id="add" value="Add" disabled="#{brandBean.disable_addBut}" actionListener="#{brandBean.addBrandDetails}"/>
<p:commandButton id="view" value="View" disabled="#{brandBean.disable_viewBut}" action="#{brandBean.getBrandDetails}"/>
</center>
</f:facet>
</h:form>
In addBrandDetails(), handleFileUpload() as
public void handleFileUpload(FileUploadEvent event)
{
String t1=".\\BrandImages\\"+event.getFile().getFileName();
System.out.println("The final path is :"+t1);
try{
File f =new File(t1);
FileOutputStream fileOutputStream = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int bulk;
InputStream inputStream = event.getFile().getInputstream();
while (true) {
bulk = inputStream.read(buffer);
if (bulk < 0) {
break;
}
fileOutputStream.write(buffer, 0, bulk);
fileOutputStream.flush();
}
fileOutputStream.close();
inputStream.close();
}catch(Exception e)
{
System.out.println("Exception :"+e);
}
this.brand_image=t1;
}
In getBrandDetails(), i am setting as "this.setBrand_image(b.getBrand_img_url());"
When i am pringting it is printing path E:\jboss-as-7.1.1.Final\bin\BrandImages\logo.gif
but it is unable to display the image.
Please help me out....

First of all, your bean must have the scope as session. A good way is making just a bean for getting requested images.
Second, your varible "brand_image" need to be a object of DefaultStreamedContent. Because you are using primefaces.
brand_image = new DefaultStreamedContent(input, "image/jpeg");

Related

How to import file in a directory using jsf

Hi all I'm new to Java development, and I'm really confused about this.
im doing an web app and my problem is how to import file and put it in i directory. i have created the xhtml file :
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:pt="http://xmlns.jcp.org/jsf/passthrough"
xmlns:p="http://primefaces.org/ui"
template="/WEB-INF/template/template.xhtml">
<ui:define name="title">2G</ui:define>
<ui:define name="content">
<h:form>
<h1> <font color="orange" size="7" > 2G</font></h1>
</h:form>
<h2 >Choose 2 files </h2>
<h:form>
<p:fileUpload fileUploadListener="#{import_2G.save()}"
mode="advanced" dragDropSupport="true" update="messages"
sizeLimit="100000000000" allowTypes="/(\.|\/)(xls)$/" />
<p:growl id="messages" showDetail="true" />
</h:form>
</ui:define>
</ui:composition>
and this is the bean file :
#ManagedBean
#RequestScoped
public class Import_2G {
public Import_2G() { }
#EJB
private GestionCellRef2GLocal gestionCellRef2GLocal;
private UploadedFile uploadedFile;
public void save() throws IOException {
GestionCellRef2GRemote t = null;
Path folder = Paths.get("C:\\Upload");
String filename = FilenameUtils.getBaseName(uploadedFile.getFileName());
String extension = FilenameUtils.getExtension(uploadedFile.getFileName());
Path file = Files.createTempFile(folder, filename + "-", "." + extension);
if (file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
}
try (InputStream input = uploadedFile.getInputstream()) {
Files.copy(input, folder, StandardCopyOption.REPLACE_EXISTING);
}
}
}
any help guys ?
First start reading about naming conventions in Java. If you not respect the naming conventions and use underscores, scores and things like that, you will have some troubles.
Second, you forgot the enctype. When you wanna upload binary data, you must have put the attribute: enctype="multipart/form-data". Let's build a file upload.
First your form:
<h:form enctype="multipart/form-data">
<p:fileUpload value="#{import2G.file}"
mode="advanced" dragDropSupport="true"
sizeLimit="100000000"
allowTypes="/(\.|\/)(xls)$/"
update="messages"
fileUploadListener="#{import2G.save}" />
</h:form>
<p:growl id="messages" showDetail="true" />
And your backing bean:
public void save(FileUploadEvent e) {
FileUpload file = event.getFile();
String fileName = file.getFileName();
String contentType = file.getContentType();
byte[] content = file.getContents();
saveFile(content);
}
private void saveFile(byte[] data) {
FileOutputStream fos = new FileOutputStream(DIR_NAME);
fos.write(data);
fos.close();
}
Look the listener in the form; use import2G.save instead import2G.save(), this because a FileUpload parameter is passed to the listener in runtime.

p:graphicImage streamContent nullpointer

Trying to get a blob and make it into a streamed content. I get the bytes, they do get converted into ByteArrayInputStream and I am returning the StremedContent image, but i keep getting this:
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/ConfigEmployee] threw exception
java.io.IOException: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at org.primefaces.application.resource.StreamedContentHandler.handle(StreamedContentHandler.java:56)
... 21 more
line 56 has this: externalContext.setResponseContentType(streamedContent.getContentType());
I need to add that the streamed content is returned two times per Image object.
Image bean:
public Image(byte[] bytes,String name)
{
this.id=new MyDatabase().getLastId("image")+1;
this.name=name;
this.byteData=bytes;
InputStream is=new ByteArrayInputStream(bytes);
this.image = new DefaultStreamedContent(is,"image/png");
}
public StreamedContent getImage()
{
return image;
}
HTML code
<div class="dataTable">
<h:form id="imageList">
<p:dataTable var="img" value="#{imageView.images}" rowKey="#{img.id}" rows="10" lazy="true" paginator="true">
<p:column headerText="Image">
<p:graphicImage style="width:80px; height:80px" value="#{img.image}" />
</p:column>
<p:column width="200" headerText="Name">
<h:outputText value="#{img.name}" />
</p:column>
<p:column width="200" headerText="Edit">
<h:commandButton value="Enter" actionListener="#{imageView.convertImage(img)}" action="Image?faces-redirect=true" />
</p:column>
</p:dataTable>
</h:form>
</div>
Lazy load
#Override
public List<Image> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters)
{
db.openDatabase();
ResultSet rs = db.getImage();
List<Image> imgList = new ArrayList<Image>();
try
{
if (rs.last())
this.setRowCount(rs.getRow());
for (rs.absolute(first); rs.next() && first <= (first + pageSize); first++)
{
imgList.add(new Image(rs.getBytes("byteData"), rs.getString("name")));
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
db.closeDatabase();
}
return imgList;
}
Primefaces 5.1, JSF 2.2, Tomcat v7.0
What is the scope of the bean, it should be View or Session scoped, and you will have to change the way you access your bean. For the dynamically created images, two requests are being sent. One to render the HTML, that renders the img tag. Than the second, fired based on the src attribute. The model must retain the values accross the subsequent requests.
all explained beautifully here Display dynamic image from database with p:graphicImage and StreamedContent

Editing a datatable row with a dialog

I am using Primefaces 3.5, Jsf 2 and I have a datatable, now I implemented a dialog like the primefaces showcase(singlerowselection), it works fine, but I want to edit the row IN the dialog. Furthermore I want that the inputtext is filled with the data from the cell of the datatable, so that you can easily edit it!(like the row editor does it, just in a dialog)
Not like this: http://i.stack.imgur.com/J55j0.jpg
Watermark works, but it is no option because the text disappears if you want to edit it.
It should be like that: http://i.stack.imgur.com/cAFLo.jpg
So, can someone tell me how the cell data can be displayed and edited?
Here is the xhtml (dialog is not in the datatable):
<p:dialog id="dialog" header="Server Detail" widgetVar="serDialog"
resizable="false" showEffect="clip" hideEffect="fold" dynamic="true">
<h:panelGrid id="display" columns="3" cellpadding="4">
<h:outputText value="Data Center Location " />
<p:inputText id="datacenter" value="#{server.dataCenterLocation}"></p:inputText>
<h:outputText value="Identification " />
<h:inputText id="identification" value="#{server.identification}"></h:inputText>
<p:watermark for="identification"
value="#{serverBean.selectedServer.identification}"></p:watermark>
</h:panelGrid>
<p:growl id="growl" showDetail="true" sticky="false" />
<p:commandButton value="Edit Server" action="#{server.onEdit}" update="#form, growl" />
</p:dialog>
the method in the bean(name= server)
(without the selectedServer(name =serverBean) with the getter and setter):
public void onEdit() throws Exception {
PreparedStatement ps = null;
Connection con = null;
int i = 0;
try {
Server ser = new Server();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
.newInstance();
con = DriverManager
.getConnection("jdbc:sqlserver://...");
String sql = "UPDATE VAI_Serverlist SET [Data Center Location]= ?,... WHERE Identification='"
+ ser.identification + "'";
ps = con.prepareStatement(sql);
ps.setString(1, ser.dataCenterLocation);
...
i = ps.executeUpdate();
} catch (SQLException e) {
System.out.println(i);
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks in advance!
<h:form id="form">
<p:dataTable id="table" var="item" value="#{ManagedBean.list()}"
<f:facet name="footer">
<p:commandButton id="showUpdateButton" value="#{msgForms['actions.Edit']}"
update=":update_form"
icon="ui-icon-pencil"
style="margin: 0%"
ajax="true"
immediate="true"
oncomplete="PF('DialogUpdate').show()"
/>
</f:facet>
</p:dataTable>
<h:form id="form">
<p:dialog id="dialog_update"
modal="true"
header="${msgForms['titles.update']}"
widgetVar="DialogUpdate" resizable="false"
showEffect="clip" hideEffect="fold"
>
<h:form id="update_form">
<h:panelGrid columns="3" id="panel">
<!--FIELDS-->
<h:outputLabel for="nombre" value="#{msgForms['fields.nombre']}:" />
<p:inputText id="nombre"
value="#{ManagedBean.selectedItem.nombre}"
required="true"
requiredMessage="#{msgForms['field.required']}"
>
<p:ajax event="keyup" update="nombreMsg" global="false"/>
</p:inputText>
</h:panelGrid>
<!--/FIELDS-->
<!-- BUTTONS ACTIONS-->
<p:commandButton id="updateButtonDg"
value="#{msgForms['actions.update']}"
icon="ui-icon-pencil"
actionListener="#{ManagedBean.update()}"
update=":form:"
style="margin: 0%"
ajax="true"
onclick="DialogUpdate.hide();"
>
</p:commandButton>
<!-- /BUTTONS ACTIONS-->
</h:form>
</p:dialog>
the MANAGED BEAN..
#Named("ManagedBean")
#RequestScoped
public class ManagedBean {
//Spring Item Service is injected...
#Inject
IItemService itemService; //if not required because if you use dependencies injection to connect with de database
private List<Item> filteredItems; //only if you use the attribute: filteredValue="#{ManagedBean.filteredItems}" in the dataTable
private List<Item> items;
public void update() {
//here you save the changes in the data base
this.itemService().updateItem(this.selectedItem);
}
this is more or less what I use, I can not put the literal code, but I think I have not left anything important, so i hope it could to help you.
I recommend that you take a look at the tutorial
http://www.javacodegeeks.com/2012/04/jsf-2-primefaces-3-spring-3-hibernate-4.html
it shows how to integrate jsf2 Spring3 hibernate in your project and also how to inject dependencies using annotations, i recomend you the use of hibernate framework to interact with your database

primefaces multiple file upload only updating tree table with first file uploaded

I have a treetable with a multiple file upload component. If i upload 1 file, it correctly updates my treetable with that file.
If i try and upload multiple files at the same time (lets say file1 and file2), it only updates the tree table with file 1. If i then upload another file (file3), it then updates the tree table with file1, file2, and file3 so it seems to be an issue with updating.
Does anyone have any insight into this or know if it's a bug?
<h:form id="attachmentsForm" enctype="multipart/form-data">
<p:treeTable value="#{contentEditorBacking.attachments}" var="node">
<p:column>
<f:facet name="header">Name</f:facet>
<h:outputLink value="#{node.link}" target="_blank" disabled="#{node.disabled}">
<h:outputText value="#{node.displayName}"/>
</h:outputLink>
</p:column>
<p:column>
<f:facet name="header">Size</f:facet>
<h:outputText value="#{node.size}" />
</p:column>
<p:column>
<f:facet name="header">Modified By</f:facet>
<h:outputText value="#{node.modifier}" />
</p:column>
<p:column>
<f:facet name="header">Delete</f:facet>
<p:commandLink styleClass="ui-icon ui-icon-trash" id="deleteProperty" actionListener="#{contentEditorBacking.deleteAttachment}"
rendered="#{node.canDelete}" update="attachmentsForm">
<f:attribute name="filename" value="#{node.displayName}" />
</p:commandLink>
</p:column>
</p:treeTable>
<p:fileUpload fileUploadListener="#{contentEditorBacking.handleFileUpload}"
mode="advanced" sizeLimit="#{contentEditorBacking.fileSizeLimit}"
invalidSizeMessage="#{contentEditorBacking.fileSizeMessage}"
allowTypes="#{contentEditorBacking.allowedFileTypes}" update=":controlTabs:attachmentsForm" />
</h:form>
Backer
public void handleFileUpload(FileUploadEvent event) throws Exception{
UploadedFile toSave = event.getFile();
System.out.println("fileName = "+event.getFile());
String fileName = toSave.getFileName();
String downloadLink = "";
Long size = event.getFile().getSize();
long version = 1;
User user = cm.getUser();
String creator = user.getUserName();
Date modDate = new Date();
boolean canDelete = true;
boolean canUpdate = true;
String displayName = fileName + "- pending";
new DefaultTreeNode(new Attachment(downloadLink,size,version,creator,modDate,canDelete,canUpdate,displayName,true), attachRoot);
addNeedToSaveMessage();
}
EDIT
I added an id to the treeTable and changed my fileUpload update to the id of the treeTable rather than the id of the form tag and then solved my problem.
I always thought that by updating a parent element, it should update all of its children. Is that not true or are there exceptions to this as in the treeTable?
Apparently for the file upload component, i had to update the actual tree table rather its parent form tag.

JSF1.2 Messages not rendered

Migrating from WAS6.1+JSF1.1+richfaces.3.1.5 to WAS7+JSF1.2+facelets1.1.14+richfaces3.3.3.
Error/Status messages are not rendering using h:messages, even though on debugging the facescontext.getMessages() contains the messages.
On submitting a form, I am validating an input. If the validation fails I am adding an error msg to the facescontext. It can be for multiple inputs. Each error msg is added to the facescontext
FacesMessage message = new FacesMessage();
message.setDetail(msg);
message.setSummary(msg);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
getFacesContext().addMessage(componentID, message);
and on the xhtml I am displaying it using h:messages
I was using jsp in WAS6.1 and JSF1.1 and this used to work fine
Thanks
Adding more details
My xhtml
<ui:composition template="/template.xhtml">
<ui:define name="content">
<div id="content-nosidebar">
<h:form id="uploadDoc1" >
<h:messages/>
<h:panelGrid id="panelGridContact" headerClass="standardPageHeader" width="100%" cellpadding="5">
<f:facet name="header">
<h:panelGroup>
<h:outputText value="Upload Contact Info" />
<hr/>
</h:panelGroup>
</f:facet>
<h:panelGroup id="msgId">
<xyz:errorMessages />
<xyz:statusMessages />
</h:panelGroup>
<h:panelGrid style="text-align: center;font-weight: bold;">
<h:outputText value="Click on Browse button to identify CSV file with contact information for upload."/>
<h:outputText value="File size limit is 10MB."/>
<h:panelGroup>
<rich:fileUpload id="fileuploader" fileUploadListener="#{uploadContactCntrl.onSubmit}"
acceptedTypes="csv" allowFlash="true" listHeight="50" addControlLabel="Select File" uploadControlLabel="Submit" clearControlLabel="clear"/>
</h:panelGroup>
<h:outputText value=" "/>
</h:panelGrid>
</h:panelGrid>
</h:form>
</div>
</ui:define>
</ui:composition>
errorMessages and statusMessages are common tags to display error(validation error) and status((like Update complete) messages
In the the backingbean on submit if an error is encountered (like "File not found" or "Database is down" I call a common method with the error/status message from the resource file.
WebUtils.addCustomErrorMessage("global.error.ContactInfo-DuplicateRecords-UserID", new String[]{userid,Integer.toString(j+1)}, Constants.RESOURCE_BUNDLE_NAME);
or
WebUtils.addCustomStatusMessage("global.error.ContactInfo-successMessage", new String[]{Integer.toString(noOfRowsInserted)}, Constants.RESOURCE_BUNDLE_NAME);
public static void addCustomErrorMessage(String msg, String componentID) {
FacesMessage message = new FacesMessage();
message.setDetail(msg);
message.setSummary(msg);
message.setSeverity(FacesMessage.SEVERITY_ERROR);
getFacesContext().addMessage(componentID, message);
}
public static void addCustomStatusMessage(String msg, String componentID) {
if (errorCodeParameters != null && errorCodeParameters.length > 0)
msg = MessageFormat.format(msg, (Object[])errorCodeParameters);
FacesMessage message = new FacesMessage();
message.setDetail(msg);
message.setSummary(msg);
message.setSeverity(FacesMessage.SEVERITY_INFO);
getFacesContext().addMessage(componentID, message);
}
We also use the same tags to display an error message when an error is encountered on an input field. For e.g. a Firstname field has invalid characters.
As mentioned earlier, this was working fine before we migrated to JSF1.2
Your answer need to have xhtml code too, any way i'm giving u sample for using validation in JSF 1.2...
The xhtml code should be like..
<h:inputText id="txt_project_name"
value="#{FIS_Project_Master.txt_project_name_value}"
validator="#{FIS_Project_Master.txt_project_name_validator}"/>
<h:message id="msg_txt_project_name" for="txt_project_name" />
The java code should be like...
public void txt_project_name_validator(FacesContext context, UIComponent component, Object value) {
if (bmwpProjectMstFacade.ispmProjName_exists(value.toString().toUpperCase().trim())) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Warning", "Project Name Already Exist");
throw new ValidatorException(message);
}
}

Categories

Resources