• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

File upload

 
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
After a two month visit to Tucson, Arizona, where I am normally based, I got back to France earlier this month, and am back trying to learn how to use JavaServer Faces effectively for my work in Lyon. One important issue that I am stuck on is how to upload files. I am well aware that the form enctype has to be set to "multipart/form-data", and also as JSF does not support file uploads directly, code has to be modified and extra jar files included.

I used the instructions and code downloaded from http://www.onjava.com/pub/a/onjava/2005/07/13/jsfupload.html in an attempt to get this to work, after making a number of changes. I took the code for "MyBean.java" and the only change I made was to change the first line to "package com.onjava;" then put it in the path "<my-root>/src/java/com/onjava" rather than in the path given in the example to simpify things a bit. Likewise I put the jsp files as provided in the in the path "<my-root>/web" omitting "/jsfupload" and added a plain "index.html" file which loads first then immideately redirects to "index.jsp".

So far so good, in "<my-root>/web/WEB-INF" I modified the xml files for JSF 1.2 and have the following code for "web.xml":

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<servlet>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.faces</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.component.html.util.ExtensionsFilter</filter-class>
<init-param>
<param-name>uploadMaxFileSize</param-name>
<param-value>10m</param-value>
</init-param>
<init-param>
<param-name>uploadThresholdSize</param-name>
<param-value>100k</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ExtensionsFilter</filter-name>
<servlet-name>FacesServlet</servlet-name>
</filter-mapping>
<welcome-file-list>
<welcome-file>/index.html</welcome-file>
</welcome-file-list>
</web-app>

and for "faces.config.xml" have the following code:

<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
version="1.2">
<managed-bean>
<managed-bean-name>myBean</managed-bean-name>
<managed-bean-class>com.onjava.MyBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/MyForm.jsp</from-view-id>
<navigation-case>
<from-outcome>OK</from-outcome>
<to-view-id>/MyResult.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>

Then in order to compile "MyBean" I had to include in "<my-root>/web/WEB-INF/lib" the following jar files:
commons-fileupload-1.1.jar
commons-io-1.2.jar
jsf-api.jar
jsf-impl.jar
tomahawk-1.1.6.jar

The last one I had a bit of difficulty finding, but it seems to have the correct code. Anyway, I managed to compile the code successfully and the compiler created a class file in "<my-root>/web/WEB-INF/classes/com/onjava". However, on creating a war file and deploying it I get in my browser the error message "HTTP Status 503 - ... The requested service () is not currently available", and in the log I get the message:

Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.myfaces.renderkit.html.util.ExtensionsPhaseListener.<clinit>(ExtensionsPhaseListener.java:49) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) blah blah blah..... etc.

I would most appreciate some kind help in getting this sorted out. There must be some people around who know how to write a simple file upload utility with JSF. It is quite difficult working here in apparent isolation in France with nobody that I know of who knows JSF.

Christopher Sharp
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have some dummy HTML and JavaScript that act as a placeholder where the required code in a .jsp page is to be placed. If you go to http://phoenix.ens-lyon.fr/simulator/ then click in the right button (Isochron chi-squared fitting) then in "Specify the photometric system" select the last option (Other filter set) and additional inputs for the form are displayed, including initially one file upload. By specifying more than 1 filter several files are to be uploaded.

At the moment this is just dummy JavaScript code that does nothing other than changing the display, and I want to be able to specify one or more files that can be uploaded to the server. I would be most grateful to know how to do this.

Christopher Sharp
 
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howzit Chris,

You're in France so you should be on more or less the same timezone as me. Give or take an hour or 3. This has caught my interest, so i'm trying to get it working. What I found so far which might be of use to you is this..

http://myfaces.apache.org/tomahawk/extensionsFilter.html

I'm going to work through it, and see if it helps in getting this working. Will let you know my progress. Got to also do some work in between so it might take a while ;-)
 
Darryl Nortje
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello again,

I got it working. I'm using MyFaces. I had to setup the MyFacesExtensionsFilter in the web.xml, to handle the multipart messages, then I used the tomahawk inputFileUpload tag, which basically is bound to org.apache.myfaces.custom.fileupload.UploadedFile in my bean.

The tieing together of these things is pretty straight forward.

enjoy
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

Many thanks, I was just about to reply to your first message, when I refreshed my browser and saw your second. Incidentally, I'm 1 hour ahead of the UK, 2 hours ahead of GMT and 9 hours ahead of Arizona, so getting replies from my contacts in Tucson isn't very easy.

I had previously got the upload example in chapter 13 of "Core JavaSever Faces" by D.Geary and C.Horstmann (see http://corejsf.com) to work, but chapter 13 seems to be a bit of an afterthought, and the code in the example seems to be far more complicated than necessary, and not very well explained, and as I'm still a novice, it's difficult for me to understand. It's one thing just to download some code and get it to work, it's another to understand what is happening, so a really simple example would be much more helpful.

I will try your approach first with a very simple file upload example and let you know if I'm successful.

Cheers,

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I'm still having problems and the code won't deploy and I still get the HTTP 503 error.

Here are exactly the files I have as follows:

1) Java source code - "<my_project>/src/java/com/csharp/MyBean.java":

package com.csharp;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class MyBean {
private UploadedFile myFile;
private String myParam;
private String myResult;

public UploadedFile getMyFile() {
return myFile;
}

public void setMyFile(UploadedFile myFile) {
this.myFile = myFile;
}

public String getMyParam() {
return myParam;
}

public void setMyParam(String myParam) {
this.myParam = myParam;
}

public String getMyResult() {
return myResult;
}

public void setMyResult(String myResult) {
this.myResult = myResult;
}

public String processMyFile() {
try {
MessageDigest md
= MessageDigest.getInstance(myParam);
InputStream in = new BufferedInputStream(
myFile.getInputStream());
try {
byte[] buffer = new byte[64 * 1024];
int count;
while ((count = in.read(buffer)) > 0)
md.update(buffer, 0, count);
} finally {
in.close();
}
byte hash[] = md.digest();
StringBuffer buf = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
int b = hash[i] & 0xFF;
int c = (b >> 4) & 0xF;
c = c < 10 ? '0' + c : 'A' + c - 10;
buf.append((char) c);
c = b & 0xF;
c = c < 10 ? '0' + c : 'A' + c - 10;
buf.append((char) c);
}
myResult = buf.toString();
return "OK";
} catch (Exception x) {
FacesMessage message = new FacesMessage(
FacesMessage.SEVERITY_FATAL,
x.getClass().getName(), x.getMessage());
FacesContext.getCurrentInstance().addMessage(
null, message);
return null;
}
}
}

After copying the jar files, including tomahawk-1.1.6.jar into "<my_project>/web/WEB-INF/lib/" then compiling, I create the class file without errors in "<my_project>/web/WEB-INF/classes/com/csharp/".

Then we have the HTML/JSP files.

2) HTML start file - "<my_project>/web/index.html":

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Refresh" content= "0; URL=index.faces"/>
<title>Start Web Application</title>
</head>
<body>
<p>Please wait for the web application to start.</p>
</body>
</html>

This just redirects to index.jsp, which I added and use as recommended in "Core JavaServer Faces".

3) JSP start file - "<my_project>/web/index.jsp":

<jsp:forward page="MyForm.faces"/>

This is just one line and is the start point from the code taken from the "onjava" reference mentioned earlier. In a real application this is redundant.

4) JSP MyForm page - "<my_project>/web/MyForm.jsp" which is where the real display is supposed to start:

<%@ page contentType="text/html" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://myfaces.apache.org/extensions" prefix="x"%>
<f:view>
<html>
<head>
<title>Test 2 of Uploading Files</title>
</head>
<body>
<h:form id="MyForm" enctype="multipart/form-data" >
<h:messages globalOnly="true" styleClass="message"/>
<h:panelGrid columns="3" border="0" cellspacing="5">
<h:outputLabel for="myFileId" value="File: "/>
<x:inputFileUpload id="myFileId"
value="#{myBean.myFile}"
storage="file"
required="true"/>
<h:message for="myFileId"/>
<h:outputLabel for="myParamId" value="Param: "/>
<h:selectOneMenu id="myParamId"
value="#{myBean.myParam}"
required="true">
<f:selectItem itemLabel="" itemValue=""/>
<f:selectItem itemLabel="MD5" itemValue="MD5"/>
<f:selectItem itemLabel="SHA-1" itemValue="SHA-1"/>
<f:selectItem itemLabel="SHA-256" itemValue="SHA-256"/>
<f:selectItem itemLabel="SHA-384" itemValue="SHA-384"/>
<f:selectItem itemLabel="SHA-512" itemValue="SHA-512"/>
</h:selectOneMenu>
<h:message for="myParamId"/>
<h:outputText value=" "/>
<h:commandButton value="Submit"
action="#{myBean.processMyFile}"/>
<h:outputText value=" "/>
</h:panelGrid>
</h:form>
</body>
</html>
</f:view>

5) JSP MyResults page - "<my_project>/web/MyResult.jsp":

<%@ page contentType="text/html"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head>
<title>Test 2 of Uploading Files Results Page</title>
</head>
<body>
<h:panelGrid columns="2" border="0" cellspacing="5">
<h:outputText value="File Name:"/>
<h:outputText value="#{myBean.myFile.name}"/>
<h:outputText value="File Size:"/>
<h:outputText value="#{myBean.myFile.size}"/>
<h:outputText value="Param:"/>
<h:outputText value="#{myBean.myParam}"/>
<h:outputText value="Result:"/>
<h:outputText value="#{myBean.myResult}"/>
</h:panelGrid>
</body>
</html>
</f:view>

Now we have the XML files, which is presumably where I am having the problemss:

6) web.xml file - "<my_project>/web/WEB-INF/web.xml":

<?xml version="1.0"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<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>

<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>

<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
<init-param>
<param-name>maxFileSize</param-name>
<param-value>20m</param-value>
<!--<description>Set the size limit for uploaded files.
Format: 10 - 10 bytes
10k - 10 KB
10m - 10 MB
1g - 1 GB
</description>-->
</init-param>
</filter>

<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>

</web-app>

On attempting to deploy, the <description> tag generated an error, as apparently it was not recognised, so I commented it out and continued.

7) faces-config.xml file "<my_project>/web/WEB-INF/faces-config.xml":
<?xml version="1.0"?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
version="1.2">

<managed-bean>
<managed-bean-name>myBean</managed-bean-name>
<managed-bean-class>com.csharp.MyBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<navigation-rule>
<from-view-id>/MyForm.jsp</from-view-id>
<navigation-case>
<from-outcome>OK</from-outcome>
<to-view-id>/MyResult.jsp</to-view-id>
</navigation-case>
</navigation-rule>

</faces-config>

After deployment I get the HTTP Status 503 error, followed by this blurb in the log:

Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory at org.apache.myfaces.renderkit.html.util.ExtensionsPhaseListener.<clinit>(ExtensionsPhaseListener.java:49) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at..........

Obviously something is not working properly, and it must have something to do with one or both xml files.

Sorry for cluttering up my posting with all that code, but this has been bugging me for some time, and I think that the best way of getting some help is to show exactly what I have. As I said before, I don't know anybody here in Lyon, France, who can help me, be it in English or in French.

Christopher
 
Darryl Nortje
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The error --> java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory points towards apache commons-logging project. Have you got that jar file in WEB-INF/lib. In your earlier post you said you have the following files...

commons-fileupload-1.1.jar
commons-io-1.2.jar
jsf-api.jar
jsf-impl.jar
tomahawk-1.1.6.jar

try putting this jar file in, it should then at least get you to the next step.

Going home now. Will check in tomorrow and see if you came right.

cheers
Don't drink too much wine.
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

Many thanks for your reply, and in the mean time I took a break and watched some jet skiers on the River Rhone here before trying your suggestion. I downloaded the commons-logging-1.1.1.zip file and extracted commons-logging-1.1.1.jar, which I put in /lib, recompiled and redeployed and got the HTTP Status 500 error message:

org.apache.jasper.JasperException: /MyForm.jsp(4,64) PWC6188: The absolute uri: http://myfaces.apache.org/extensions cannot be resolved in either web.xml or the jar files deployed with this application

and in the log got:

Servlet.service() for servlet jsp threw exception org.apache.jasper.JasperException: /MyForm.jsp(4,64) PWC6188: The absolute uri: http://myfaces.apache.org/extensions cannot be resolved in either web.xml or the jar files deployed with this application at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:73) at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:359) at.......

so something is still missing. All the other jar files I mentioned before are in my /lib folder.

I had no wine today, but I'm going to a party tomorrow evening where there should be lots!

Best wishes,

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've just revisited the problem, and it looks as if it has something to do with tags, of which as yet I know very little unfortunately.

Anyway, in using Google for a search on information, it seems that I have to replace

<%@ taglib uri="http://myfaces.apache.org/extensions" prefix="x" %>

by

<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t" %>

in my jsp page.

However, I still don't really understand what is going on, and where does this link point to, and how do I make it point to the required place? Do I also need an xml file called whatever.tld, and if so, how can I get documentation on it?

This is rather time consuming and slow finding out all this, so would most appreciate some help.

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I've made a small amount of progress of sorts. I changed the tag in the page to
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t" %>
and made sure that the file tomahawk-1.1.6.jar was in WEB-INF/lib/ then redeployed. The server generated a blank page without any http error message, but in looking at the log, I got the three warning messages:

Message ID: phase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@1e146ca) threw exception

Complete Message: java.lang.NoClassDefFoundError: org/apache/commons/el/Logger org/apache/commons/el/Logger org.apache.myfaces.shared_tomahawk.util.ClassUtils.<clinit>(ClassUtils.java:44) org.apache.myfaces.shared_tomahawk.config.MyfacesConfig.<clinit>(MyfacesConfig.java:94) org.apache.myfaces.renderkit.html.util.ExtensionsPhaseListener.writeCodeBeforeBodyEnd(ExtensionsPhaseListener.java:129)....

Message ID: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@10fbe75) threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java

Complete Message: 183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245) at....

Message ID: phase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@10fbe75) threw exception

Complete Message: java.lang.NoClassDefFoundError: Could not initialize class org.apache.myfaces.shared_tomahawk.config.MyfacesConfig Could not initialize class org.apache.myfaces.shared_tomahawk.config.MyfacesConfig org.apache.myfaces.renderkit.html.util.ExtensionsPhaseListener.writeCodeBeforeBodyEnd(ExtensionsPhaseListener.java:129) org.apache.myfaces.renderkit.html.util.ExtensionsPhaseListener.getCodeBeforeBodyEnd(ExtensionsPhaseListener.java:104)....

Followed by the severe message:

Message ID: StandardWrapperValve[Faces Servlet]

Complete Message: PWC1406: Servlet.service() for servlet Faces Servlet threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java:183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at....

So something is still not working. I would most appreciate some help on this as I really seem to be stuck - many thanks.

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I continue to have frustrations. Because of the message:

java.lang.NoClassDefFoundError: org/apache/commons/el/Logger

in my previous test, I found the class in commons-el-1.0.jar, which I downloaded and installed in my /WEB-INF/lib/ folder. I now have the following jar files in that folder:

commons-el-1.0.jar
commons-fileupload-1.1.jar
commons-io-1.2.jar
commons-logging-1.1.1.jar
jsf-api.jar
jsf-impl.jar
tomahawk-1.1.6.jar

and on redeploying I got rid of the no class found error, but instead get the warning message:

Message ID: executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@1b6847a) threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java

Complete Message: 183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:144) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:245) at....

followed by the severe message:

Message ID: StandardWrapperValve[Faces Servlet]

Complete Message: PWC1406: Servlet.service() for servlet Faces Servlet threw exception java.lang.NullPointerException at com.sun.faces.renderkit.RenderKitImpl.createResponseWriter(RenderKitImpl.java:183) at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:168) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:106) at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:251) at....

so it's still not working.

I'm just about on the point on giving up, the problem is that I badly need this to work.

Christopher Sharp
 
Darryl Nortje
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there Christopher,

Sorry for not responding the last couple of days, I was on leave.

I got this working in no time at all, and with very little hassles. I have a test web project that I test all these sorts of things out on, so some of the below mentioned files might not necessarily be needed for this particular example, but none the less it worked with all these files. So let me give you my dir structure and what's inside, hopefully it helps sort out some issues that you're having.



WEB-INF\lib
commons-beanutils.jar
commons-collections.jar
commons-digester.jar
commons-el.jar
commons-fileupload.jar
commons-lang.jar
commons-logging.jar
javaee.jar
jsf-api.jar
jsf-impl.jar
jstl.jar
standard.jar
tomahawk.jar

You should not need more than this, if anything this is too much.

Then, here is the code for the bean.



Nothing funny...

Here is the jsp file...


You have to have the following in your web.xml There apparently is another way of doing this, but I got it working with this



And lastly, obviously, you have to have your bean defined as a managed bean in your faces-config.xml file.

cheers
Darryl
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

Many thanks for your help, I was unable to get to the problem this morning, but apparently got the code to work this afternoon without any obvious errors. I used the same jar files I used before, as they seem to include the classes in the jar files you listed.

This is certainly much simpler that examples I've seen, such as in chapter 13 of Core JavaServer faces, which includes masses of code that is intimidating for someone starting in this.

However, there is one little wrinkle in that I can't find were the uploaded file has gone. Using the linux "find -name filename" I was unable to locate it. Any ideas?

Christopher
 
Darryl Nortje
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In the code I posted it doesn't actually save the file anywhere. It just notes how big the file is. You can specify though where you want the file to be saved, or written to, by using FileOutputStream, or something like that...

if you search the io forum I'm sure you'll find something there that'll help with this.

cheers
Darryl
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

OK, many thanks, and I'm looking at the link you provided as well as the code. I also need to know how to save the uploaded file with the same filename.

In some old code I have for other purposes I used BufferedWriter and FileWriter, but as you are using InputStream, I should be able to use OutputStream.

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

OK, I've figured out how to get the name of the file, now I just need an easy way of saving it at a known location.

In case I have not already mentioned it, I want to modify part of a page for file uploads. If you go to http://phoenix.ens-lyon.fr/simulator/ , then click on the right button "ISOCHRONE chi^2-fitting" this takes you to the next page, where if you select "Other filter set" in the drop-down menu for "Specify the photometric system" this will render visible part of the form below the drop-down menu. The idea here is that eventually one or more files can be uploaded, but so far this part of the form has dummy HTML and JavaScript, and nothing happens when clicking the buttons, other than the number of entries changes when the "Update" button is clicked. It is this part of the form that I want to activate so that files can be uploaded.

Most of this code was written before I got involved with JSF, in fact due to no suitable server being provided by the French when I first worked on this project, all the coding was client side with HTML, CSS and JavaScript, leaving open at the time last year what server side programming I would use. Since then I've had to learn JSF from scratch and on my own.

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

Well, I finally got it to work as required. Here is the code:

package upload;

import java.io.InputStream;
import java.io.FileOutputStream;
import org.apache.myfaces.custom.fileupload.UploadedFile;

public class UploadBean {

private UploadedFile uploadedFile;
private boolean success;
private boolean failure;

public String upload() {
String result = "";
try {
InputStream stream = uploadedFile.getInputStream();
long size = uploadedFile.getSize();
System.out.println("Size of the file is " + size);
String name = uploadedFile.getName();
System.out.println("Name of the file is " + name);
byte[] buffer = new byte[(int) size];
stream.read(buffer, 0, (int) size);
stream.close();
FileOutputStream outstream = new FileOutputStream(name);
outstream.write(buffer);
outstream.close();
success = true;
failure = false;
System.out.println("File Upload Successful.");
result = "ok";
} catch (Exception ioe) {
System.out.println("File Upload Unsuccessful.");
success = false;
failure = true;
result = "no";
}
return result;
}

public UploadedFile getUploadedFile() {
return uploadedFile;
}

public void setUploadedFile(UploadedFile uploadedFile) {
this.uploadedFile = uploadedFile;
}

public boolean isSuccess() {
return success;
}

public void setSuccess(boolean success) {
this.success = success;
}

public boolean isFailure() {
return failure;
}

public void setFailure(boolean failure) {
this.failure = failure;
}

}

I added the getName() method to get the name of the uploaded file, and added the FileOutputStream to write the file to a folder, which by default is the config folder in Glassfish. Obviously I will probably want to put the uploaded files in a more suitable folder.

Regards,

Christopher
 
Darryl Nortje
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
cool.

There are also more effecient ways of writing the file, as opposed to writing out the whole chunk, you can write it out in 1024kb chunks, or 4096.. Depending on your expected average file size. But like I said, I'm sure in the io forum that will have been discussed to death.

Great news though that you got it working,

cheers
Darryl
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Darryl,

OK, many thanks, and I wish I could share a beer with you!

Anyway, the uploaded files will probably be quite short, but I should still look at more efficient ways of doing this. I would now be quite interested in being able to load two or more files, as illustrated in the http://phoenix.ens-lyon.fr/simulator/ link above. I suppose one possible idea is to use a list, map, or array so that there can be multiple upload input fields which are activated by a click of the single upload button.

On a related matter, the code handling the file uploads can't be in the same form as the rest of the input parameters, so one way to deal with this is to have it on a separate page then display it between iframe tags.

Christopher
 
Christopher Sharp
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, it turns out that for this application I only need the following jar files in WEB-INF/lib/

commons-el-1.0.jar
commons-io-1.2.jar
tomahawk-1.1.6.jar
commons-fileupload-1.1.jar
commons-logging-1.1.1.jar

and of these, I only need to specify the classpath for tomahawk-1.1.6.jar when compiling the bean as it contains the class org.apache.myfaces.custom.fileupload.UploadedFile which is imported.

It's a good idea to keep things as simple as possible and not import redundant code. The way Glassfish is set up on my computer standard Java classes are in my default classpath.

Christopher
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 60
IBM DB2 Eclipse IDE Fedora
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, I am having some problems while uploading with UploadBean.

If I put the jar files in the WEB-INF/lib/ folder , then Apache Geronimo 2.1 fails to publish.

I am using Eclipse . My OS is Linux.

My Server is WebSphere Application Server Community Edition ( Apache Geronimo 2.1 )

Database is DB2 Express C Version 9.7.2

Thanks

 
Clowns were never meant to be THAT big! We must destroy it with this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic