Componente customizado

Olá, adaptei um código que estava rolando na internet de um componente customizado em JSF para fazer o papel de <input type="file"> está dando um erro muito louco e já esgotei minhas ideias.
Tenho as seguintes limitações.:
JSF 1.1
Java 1.4

são as ferramentas aceitas pelo cliente, não posso utilizar outras implementações do JSF como o MyFaces.

segue os códigos fontes:

Render

public class UploadRenderizador extends Renderer {
   public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
      if ( !component.isRendered() ) return;
      
      ResponseWriter writer = context.getResponseWriter();
      String clientId = component.getClientId(context);
      
      writer.startElement("input", component);
      writer.writeAttribute("type", "file", "type");
      writer.writeAttribute("name", clientId, "clientId");
      writer.endElement("input");
      writer.flush();
   }

   public void decode(FacesContext context, UIComponent component) {
      ExternalContext external = context.getExternalContext(); 
      HttpServletRequest request = (HttpServletRequest) external.getRequest();
      String clientId = component.getClientId(context);
      FileItem item = (FileItem) request.getAttribute(clientId);

      Object newValue;
      ValueBinding valueExpr = component.getValueBinding("value");
      if (valueExpr != null) {
         Class valueType = valueExpr.getType(context);
         if (valueType == byte[].class) {
            newValue = item.get();
         }
         else if (valueType == InputStream.class) {
            try {
               newValue = item.getInputStream();
            } catch (IOException ex) {
               throw new FacesException(ex);
            }
         }
         else {
            String encoding = request.getCharacterEncoding();
            if (encoding != null)
               try {
                  newValue = item.getString(encoding);
               } catch (UnsupportedEncodingException ex) {
                  newValue = item.getString(); 
               }
            else 
               newValue = item.getString(); 
         }
         ((EditableValueHolder) component).setSubmittedValue(newValue);  
         ((EditableValueHolder) component).setValid(true);  
      }

      Object target = component.getAttributes().get("target");
         
      if (target != null) {
         File file;
         if (target instanceof File)
            file = (File) target;
         else {
            ServletContext servletContext = (ServletContext) external.getContext();
            String realPath = servletContext.getRealPath(target.toString());
            file = new File(realPath); 
         }

         try {
            item.write(file);
         } catch (Exception ex) { 
            throw new FacesException(ex);
         }
      }
   }   
}

Filter

public class UploadFiltro implements Filter {
   private int sizeThreshold = -1;
   private String repositoryPath;

   public void init(FilterConfig config) throws ServletException {
      repositoryPath = config.getInitParameter("br.com.ht4j.filtro.UploadFiltro.repositoryPath");

      try {
         String paramValue = config.getInitParameter("br.com.ht4j.filtro.UploadFiltro.sizeThreshold");
         
         if ( paramValue != null ) sizeThreshold = Integer.parseInt(paramValue);
      
      } catch (NumberFormatException ex) {
         ServletException servletEx = new ServletException();
         servletEx.initCause(ex);
         throw servletEx;
      }
   }

   public void destroy() {
	   // sem implementação
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      if ( !(request instanceof HttpServletRequest) ) {
         chain.doFilter(request, response);
         return;
      }

      HttpServletRequest httpRequest = (HttpServletRequest) request;
      RequestContext requestContext = new ServletRequestContext(httpRequest);
      boolean isMultipartContent = ServletFileUpload.isMultipartContent(requestContext);
      
      if ( !isMultipartContent ) {
         chain.doFilter(request, response);
         return;
      }

      DiskFileItemFactory factory = new DiskFileItemFactory();
      if ( sizeThreshold >= 0 ) factory.setSizeThreshold(sizeThreshold);
      if ( repositoryPath != null ) factory.setRepository(new File(repositoryPath));
      ServletFileUpload upload = new ServletFileUpload(factory);
      
      try {
         List items = (List) upload.parseRequest(httpRequest);
         Iterator iteradorItem = items.iterator();
         
         final Map map = new HashMap();

         while( iteradorItem.hasNext() ) {
        	FileItem item =(FileItem)iteradorItem; 
            String str = item.getString();
            if ( item.isFormField() )
               map.put(item.getFieldName(), new String[] { str });
            else
               httpRequest.setAttribute(item.getFieldName(), item);
         }
            
         chain.doFilter(new 
            HttpServletRequestWrapper(httpRequest) {
               public Map getParameterMap() {
                  return map;
               }                   
               public String[] getParameterValues(String name) {
                  Map map = getParameterMap();
                  return (String[]) map.get(name);
               }
               public String getParameter(String name) {
                  String[] params = getParameterValues(name);
                  if (params == null) return null;
                  return params[0];
               }
               public Enumeration getParameterNames() {
                  Map map = getParameterMap();
                  return Collections.enumeration(map.keySet());
               }
            }, response);

      } catch (FileUploadException fue) {
         ServletException servletEx = new ServletException();
         servletEx.initCause(fue);
         throw servletEx;
      }      
   }   
}

TAG

public class UploadTag extends UIComponentTag { 
	private ValueBinding value;
	private ValueBinding target;
   
   public String getRendererType() {
	   return "br.com.ht4j.Upload";
   } 
   
   public String getComponentType() {
	   return "br.com.ht4j.Upload";
   }  
   
   public void setValue(ValueBinding newValue) {
	   value = newValue;
   }
   
   public void setTarget(ValueBinding newValue) {
	   target = newValue;
   } 
   
   public void setProperties(UIComponent component) { 
      super.setProperties(component); 
      component.setValueBinding("target", target);
      component.setValueBinding("value", value);
   } 

   public void release() {
      super.release();
      value = null;
      target = null;
   }
}

faces-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
    "http://java.sun.com/dtd/web-facesconfig_1_1.dtd">

<faces-config>
   <component>
      <component-type>br.com.ht4j.Upload</component-type>
      <component-class>javax.faces.component.UIInput</component-class>
   </component>

   <render-kit>
      <renderer>
         <component-family>javax.faces.Input</component-family>
         <renderer-type>br.com.ht4j.Upload</renderer-type>
         <renderer-class>br.com.ht4j.renderizador.UploadRenderizador</renderer-class>
      </renderer>
   </render-kit>

</faces-config>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">

	<display-name>TestaUploadTag</display-name>

	<context-param>
		<param-name>javax.faces.STATE_SAVING_METHOD</param-name> 
		<param-value>server</param-value>
	</context-param>

	<context-param>
		<param-name>javax.faces.CONFIG_FILES</param-name> 
		<param-value>/WEB-INF/faces-config.xml</param-value> 
	</context-param>

	<filter>
	   <filter-name>Upload Filter</filter-name>
	   <filter-class>br.com.ht4j.filtro.UploadFiltro</filter-class>
	   <init-param>
	      <param-name>sizeThreshold</param-name>
	      <param-value>1024</param-value>
	   </init-param>
	</filter>
	
	<filter-mapping>
	   <filter-name>Upload Filter</filter-name>
	   <url-pattern>/web/*</url-pattern>
	</filter-mapping>
	
	<listener>
        <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
    </listener>

	<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>*.jsf</url-pattern>
	</servlet-mapping>

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

</web-app>

Pagina JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
   	<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
   	<%@ taglib uri="http://ht4j.com.br/upload" prefix="ht" %>
	<title>Escolha seu arquivo</title>
</head>
<body>
<f:view>
	<h:form id="formRecebe" enctype="multipart/form-data">
	   <ht:upload target="pages/image.jpg" />
	   <h:commandButton value="Enviar" action="submit"/>
	</h:form>
</f:view>
</body>
</html>

alguem tem alguma ideia do que pode ser??
obr

Tive a mesma necessidade…

Ai começei a usar o Myfaces + Tomahawk que ja tem o componente pronto.

[]'s

Rodrigo

certo, se vc puder usar o myfaces, blz… Pode?

Infelizmente não posso utilizar outras implementações do JSF tem que ser o 1.1 mesmo

abr

Colega, vc já conseguiu fazer isso? Sua postagem ficou bem completa, mas vc esqueceu de postar o “erro muito louco” que tá dando! :lol:

Tembém tenho a necessidade deste conponente, alguém tem o código pronto para me ajudar.