001 package com.khubla.pragmatach.framework.form;
002
003 import java.util.Hashtable;
004 import java.util.List;
005
006 import javax.servlet.http.HttpServletRequest;
007
008 import org.apache.commons.fileupload.FileItem;
009 import org.apache.commons.fileupload.FileItemFactory;
010 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
011 import org.apache.commons.fileupload.servlet.ServletFileUpload;
012
013 import com.khubla.pragmatach.framework.api.PragmatachException;
014
015 /**
016 * @author tome
017 */
018 public class Form {
019 /**
020 * get form POST data
021 */
022 public static Form parse(HttpServletRequest httpServletRequest) throws PragmatachException {
023 try {
024 /*
025 * POST is actually a form?
026 */
027 if (ServletFileUpload.isMultipartContent(httpServletRequest)) {
028 /*
029 * item factory
030 */
031 final FileItemFactory fileItemFactory = new DiskFileItemFactory();
032 /*
033 * the upload
034 */
035 final ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
036 /*
037 * the items
038 */
039 @SuppressWarnings("unchecked")
040 final List<FileItem> fileItems = servletFileUpload.parseRequest(httpServletRequest);
041 /*
042 * the hashtable
043 */
044 final Hashtable<String, FormItem> formItems = new Hashtable<String, FormItem>();
045 /*
046 * walk the items
047 */
048 for (final FileItem fileItem : fileItems) {
049 final FormItem formItem = new FormItem(fileItem.getFieldName(), fileItem.getString(), fileItem.getContentType());
050 formItems.put(formItem.getName(), formItem);
051 }
052 /*
053 * return the form
054 */
055 return new Form(formItems);
056 } else {
057 /*
058 * invalid form encoding
059 */
060 return null;
061 }
062 } catch (final Exception e) {
063 throw new PragmatachException("Exception in process", e);
064 }
065 }
066
067 /**
068 * items
069 */
070 private final Hashtable<String, FormItem> items;
071
072 /**
073 * ctor
074 */
075 public Form(Hashtable<String, FormItem> items) {
076 this.items = items;
077 }
078
079 public FormItem getFormItem(String name) {
080 if (null != items) {
081 return items.get(name);
082 }
083 return null;
084 }
085
086 public String getFormItemValue(String name) {
087 if (null != items) {
088 final FormItem formItem = items.get(name);
089 if (null != formItem) {
090 return formItem.getValue();
091 }
092 }
093 return null;
094 }
095
096 public Hashtable<String, FormItem> getItems() {
097 return items;
098 }
099
100 public int size() {
101 if (null != items) {
102 return items.size();
103 }
104 return 0;
105 }
106 }