Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Tuesday, April 17, 2012

How to upload with PrimeFaces 3.2 under Tomcat 6


Download a complete example tested under Tomcat 6 from here



Few months ago I’ve wrote the “How to upload with PrimeFaces under Tomcat 6” tip which was using the PrimeFaces 2.2 version. Since then, PrimeFaces has been changed and the current version, 3.2, has a lot of new great features. In this tip, we will explore all these features.

For start, you will need the following JARs, under your /lib folder (you can take them separately from web, or if you take this complete example from http://www.filefactory.com/file/3lnbxg0x85d/n/primeFileUpload.rar, then they are already included):
- primefaces-3.2.jar (this is what I’ve used, but you can take the latest Prime Faces library from PrimeFaces site – http://www.primefaces.org).
- jsf-api-2.0.2-FCS.jar (again, take the latest, if you consider that you need it)
- jsf-impl-2.0.2-FCS.jar
- el-api-2.2.jar
- el-impl-2.2.jar
- commons-io-1.4.jar
- commons-fileupload-1.2.jar

Next, I’ve configure the application descriptor, web.xml (depending on Prime Faces version, these configurations may be slightly different). In this descriptor I’ve configured Prime Faces upload filter and the ui-lightness-1.0.4 PrimeFaces theme:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
<web-app>
<context-param>
<description>Context param for JSTL 1.2 to work in Tomcat 6 sun RI
</description>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<context-param>
<description>Parameter required by Mojarra 2.0</description>
<param-name>com.sun.faces.allowTextChildren</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.VALIDATE_EMPTY_FIELDS</param-name>
<param-value>true</param-value>
</context-param>
<!-- Adding a PrimeFaces theme -->
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>ui-lightness</param-value>
</context-param>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
<init-param>
<param-name>thresholdSize</param-name>
<param-value>10240</param-value> <!-- 10 Mb -->
</init-param>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>

Next, I wrote a simple JSF page to test the Prime Faces upload component:

<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Prime Faces</title>
<style type="text/css">
.ui-fileupload {
width: 800px;
margin: 0 auto;
}
</style>
</h:head>
<h:body>
<h:outputText value="PrimeFaces Single Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
sizeLimit="1048576"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 1 Megabyte !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" sticky="true"/>
</h:form>

<h:outputText value="PrimeFaces Multiple Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
sizeLimit="10485760"
multiple="true"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>

<h:outputText value="PrimeFaces Auto Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file"
auto="true"
sizeLimit="10485760"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>

<h:outputText value="PrimeFaces Drag and Drop Upload"
style="font:30px bold; margin-left:15%;"/>
<h:form enctype="multipart/form-data">
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced"
update="messages"
label="Choose a file or drag and drop it here"
sizeLimit="10485760"
allowTypes="/(\.|\/)(gif|jpe?g|png)$/"
invalidSizeMessage="The maximum file size allowed is 10 Megabytes !"
invalidFileMessage="You are allowed to upload only images !"
/>
<p:growl id="messages" showDetail="true" life="5000"/>
</h:form>
</h:body>
</html>

As you can see, p:fileUpload is very flexible and customizable, allowing us to specify upload characteristics with a few simple attributes. Going further, we need a managed bean capable of dealing with upload itself. A possible implementation (probably not the best, but for sure not the worst) is listed below:

package com.extensions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.FacesException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.FileUploadEvent;

@ManagedBean(name = "fileUploadController")
@RequestScoped
public class uploadFilesBean {

//Primitives
private static final int BUFFER_SIZE = 6124;
private String folderToUpload;

/** Creates a new instance of UploadBean */
public uploadFilesBean() {
}

public void handleFileUpload(FileUploadEvent event) {

ExternalContext extContext =
FacesContext.getCurrentInstance().getExternalContext();
File result = new File(extContext.getRealPath
("//WEB-INF//files//" + event.getFile().getFileName()));
System.out.println(extContext.getRealPath
("//WEB-INF//files//" + event.getFile().getFileName()));

try {
FileOutputStream fileOutputStream = new FileOutputStream(result);

byte[] buffer = new byte[BUFFER_SIZE];

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();

FacesMessage msg =
new FacesMessage("File Description", "file name: " +
event.getFile().getFileName() + "<br/>file size: " +
event.getFile().getSize() / 1024 +
" Kb<br/>content type: " +
event.getFile().getContentType() +
"<br/><br/>The file was uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);

} catch (IOException e) {
e.printStackTrace();

FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,
"The files were not uploaded!", "");
FacesContext.getCurrentInstance().addMessage(null, error);
}
}
}

The uploaded files goes to /WEB-INF/files folder.

Here it is a nice screenshot of Prime Faces upload:



That’s it ! Hope you like it !

Download a complete example tested under Tomcat 6 from here


Monday, April 16, 2012

How to programmatically access PrimeFaces tags


This is FYI kind tip. Recently, I tried to programmatically acess PrimeFaces tags from Java beans. I found two solutions that can be extrapolated to almost all PrimeFaces tags.

1. Use the findComponent() method

Per example, the below code contains a DataTable, and I want to programmatically to set the zero-relative row number of the first row to be displayed.

<p:layoutUnit position="center" styleClass="welcome">
<p:tabView id="centerTabIds" activeIndex="2">
<p:tab title="LBD">
<p:accordionPanel id="dataId">
<p:tab title="Data Table Viewer">
<h:panelGrid columns="1" cellpadding="5"
style="margin-left: auto; margin-right: auto;">
<h:form id="tableViewFormId" prependId="false">
<p:dataTable id="tableViewId" var="t" value="#{tableViewBean.lazyModel}"
paginator="true" rows="5"
currentPageReportTemplate="{currentPage} of {totalPages}"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink}
{PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10" emptyMessage="No records found"
paginatorPosition="top" first="0">
<f:facet name="header">
Data Table
</f:facet>
<c:forEach items="#{tableViewBean.simpleColumns}" var="column">
<p:column headerText="#{column.header}">
<h:outputText value="#{t[column.property]}"/>
</p:column>
</c:forEach>
<f:facet name="footer">
<c:when test="#{not empty tableViewBean.selectedTable}">
<h:outputText value="#{tableViewBean.selectedTable}" />
</c:when>
</f:facet>
</p:dataTable>
</h:form>
</h:panelGrid>
</p:tab>
</p:accordionPanel>
</p:tab>
...

And here it is the programmatically solution using the findComponent() method:

((DataTable)(FacesContext.getCurrentInstance().getViewRoot().findComponent(
"centerTabIds:dataId:tableViewFormId:tableViewId"))).setFirst(0);

This is a tip in a tip – using multiple dynamic data tables and switching between them will get you to an unpleasant situation. PrimeFaces does not reset the data table to the first page every time you switch to another table, but this code fixes that problem.

Even if it is not a good idea to hardcode components ids, this can save a lot of time when no solution is available.

2. Use ActionEvent

Another common scenario is like this: I have a PrimeFaces menu, with several menu items. Each menu item has a value attribute, and all of them indicates the same action listener. I want to get the value of the menu item that was selected. The code looks like this:

...
<c:forEach items="#{iccAnalysisBean.wellIds}" var="row">
<p:menuitem value="#{row.toString()}"
actionListener="#{iccAnalysisBean.selectedWellAction}" ajax="true"/>
</c:forEach>
...

And I’ve accommplish my task like this:

public void selectedWellAction(ActionEvent e) {
String valueOfWell = String.valueOf(e.getComponent().getAttributes().get("value"));
...
}

I hope that this will help you when you are stack in such issues!