List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java
/** * Uploading SAML file(s) for interaction with the Java Applet. * The parameters are filled in by the SAML assiertion applet. * This function contains a fallback to the help provider of gUSE. * @param request ResourceRequest//www . j a v a2 s . c om * @param response ResouceResponse * @throws PortletException * @throws IOException */ @Override public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException { logger.debug("serveResource: guse=" + request.getParameter("guse")); if (!"doAppletUpload".equals(request.getParameter("guse"))) { super.serveResource(request, response); return; } String msg; try { logger.debug("Assertion-doUpload"); FileItem samlFile = null; String sresource = null; // selected resource try { DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(1048576); // Maximum upload size 1Mb Iterator iter = pfu.parseRequest(PortalUtil.getHttpServletRequest(request)).iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { // retrieve parameters if item is a form field if ("sresource".equals(item.getFieldName())) { sresource = item.getString(); } } else { if ("samlFile".equals(item.getFieldName())) { samlFile = item; } } } List<String> result = uploadSaml(request.getPortletSession(), samlFile, sresource, request.getRemoteUser()); StringBuilder sb = new StringBuilder(); boolean flag = false; for (String m : result) { if (flag) { sb.append("\n"); } else { flag = true; } sb.append(m); } msg = sb.toString(); } catch (Exception e) { msg = "Upload failed. Reason: " + e.getMessage(); logger.info("Upload of assertion failed. Reason: " + e.getMessage()); logger.debug("Exception:", e); } response.setContentType("text/plain"); response.addProperty("Cache-Control", "no-cache"); response.getWriter().write(msg); logger.info("Returning: " + msg); } catch (Exception e2) { logger.error("Error in " + getClass().getName() + "\n", e2); } return; }
From source file:it.eng.spago.dispatching.httpchannel.AdapterPortlet.java
/** * Handle multipart form./*from www. j ava 2 s. c o m*/ * * @param request the request * @param requestContext the request context * * @throws Exception the exception */ private void handleMultipartForm(ActionRequest request, RequestContextIFace requestContext) throws Exception { SourceBean serviceRequest = requestContext.getServiceRequest(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler PortletFileUpload upload = new PortletFileUpload(factory); // Parse the request List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); serviceRequest.setAttribute(name, value); } else { processFileField(item, requestContext); } } }
From source file:controller.uploadProductController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . j av a 2 s . c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); String userPath = request.getServletPath(); if (userPath.equals("/uploadProduct")) { boolean success = true; // configures upload settings DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); // sets temporary location to store files factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // constructs the directory path to store upload file // this path is relative to application's directory String uploadPath = getServletContext().getInitParameter("upload.location"); //creates a HashMap of all inputs HashMap hashMap = new HashMap(); String productId = UUID.randomUUID().toString(); try { @SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(request); for (FileItem item : formItems) { // processes only fields that are not form fields if (!item.isFormField()) { File file = new File(item.getName()); File file2 = new File(productId + ".jpg"); String filePath = uploadPath + File.separator + file.getName(); // saves the file on disk File storeFile = new File(filePath); item.write(storeFile); File rename = new File(filePath); boolean flag = rename.renameTo(file2); } else { hashMap.put(item.getFieldName(), item.getString()); } } } catch (FileUploadException ex) { Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("error", true); request.setAttribute("errorMessage", ex.getMessage()); success = false; } catch (Exception ex) { Logger.getLogger(uploadProductController.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("error", true); request.setAttribute("errorMessage", ex.getMessage()); success = false; } String owner = (String) session.getAttribute("customerEmail"); if (owner == null) { owner = "shop"; } String pName = hashMap.get("pName").toString(); String mNo = hashMap.get("mNo").toString(); String brand = hashMap.get("brand").toString(); String description = hashMap.get("description").toString(); String quantity = hashMap.get("quantity").toString(); String price = hashMap.get("price").toString(); String addInfo = hashMap.get("addInfo").toString(); int categoryId = Integer.parseInt(hashMap.get("category").toString()); ProductDAO productDAO = new ProductDAOImpl(); Product product; try { double priceDouble = Double.parseDouble(price); int quantityInt = Integer.parseInt(quantity); Category category = (new CategoryDAOImpl()).getCategoryFromID(categoryId); if (owner.equals("shop")) { product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand, description, addInfo, true, true, owner); } else { product = new Product(productId, pName, mNo, category, quantityInt, priceDouble, brand, description, addInfo, false, false, owner); } if (!(productDAO.addProduct(product, category.getName()))) { throw new Exception("update unsuccessful"); } } catch (Exception e) { request.setAttribute("error", true); request.setAttribute("errorMessage", e.getMessage()); success = false; } request.setAttribute("pName", pName); request.setAttribute("mNo", mNo); request.setAttribute("brand", brand); request.setAttribute("description", description); request.setAttribute("quantity", quantity); request.setAttribute("price", price); request.setAttribute("addInfo", addInfo); request.setAttribute("categoryId", categoryId); request.setAttribute("success", success); if (success == true) { request.setAttribute("error", false); request.setAttribute("errorMessage", null); } String url; if (owner.equals("shop")) { url = "/WEB-INF/view/adminAddProducts.jsp"; } else { url = "/WEB-INF/view/clientSideView/addRecycleProduct.jsp"; } try { request.getRequestDispatcher(url).forward(request, response); } catch (ServletException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:edu.wustl.bulkoperator.action.BulkHandler.java
/** * This method will be called to get request parameters. * @param request HttpServletRequest./*from w w w.j a va 2s .c o m*/ * @param bulkOperationForm form. * @throws BulkOperationException Exception. */ private void getRequestParameters(HttpServletRequest request, BulkOperationForm bulkOperationForm) throws BulkOperationException { try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setRepository(new File(CommonServiceLocator.getInstance().getAppHome())); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); // If file size exceeds, a FileUploadException will be thrown servletFileUpload.setSizeMax(10000 * 1000 * 100 * 10); List<FileItem> fileItems; fileItems = servletFileUpload.parseRequest(request); Iterator<FileItem> itr = fileItems.iterator(); while (itr.hasNext()) { FileItem fileItem = itr.next(); //Check if not form field so as to only handle the file inputs //else condition handles the submit button input if (!fileItem.isFormField()) { if ("csvFile".equals(fileItem.getFieldName())) { bulkOperationForm.setCsvFile(getFormFile(fileItem)); } else { bulkOperationForm.setXmlTemplateFile(getFormFile(fileItem)); } logger.info("Field =" + fileItem.getFieldName()); } else { if ("operation".equals(fileItem.getFieldName())) { bulkOperationForm.setOperationName(fileItem.getString()); } } } } catch (Exception exp) { ErrorKey errorkey = ErrorKey.getErrorKey("bulk.operation.request.param.error"); throw new BulkOperationException(errorkey, exp, exp.getMessage()); } }
From source file:property_update.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www .j a v a2s .c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, FileUploadException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); HttpSession hs = request.getSession(); try { if (hs.getAttribute("user") != null) { Login ln = (Login) hs.getAttribute("user"); System.out.println(ln.getUId()); String pradd1 = ""; String pradd2 = ""; String prage = ""; String prbhk = ""; String prdescrip = ""; String prprice = ""; String state = ""; String city = ""; String area = ""; String prname = ""; String prtype = ""; String prphoto = ""; String prphoto1 = ""; String prphoto2 = ""; String prphoto3 = ""; String prfarea = ""; int prid = 0; FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //get the list of all fields from request List<FileItem> fields = upload.parseRequest(request); // iterates the object of list Iterator<FileItem> it = fields.iterator(); //getting objects one by one while (it.hasNext()) { //assigning coming object if list to object of FileItem FileItem fileItem = it.next(); //check whether field is form field or not boolean isFormField = fileItem.isFormField(); if (isFormField) { //get the filed name String fieldName = fileItem.getFieldName(); if (fieldName.equals("pname")) { //getting value of field prname = fileItem.getString(); System.out.println(prname); } else if (fieldName.equals("price")) { //getting value of field prprice = fileItem.getString(); System.out.println(prprice); } else if (fieldName.equals("pid")) { prid = Integer.parseInt(fileItem.getString()); } else if (fieldName.equals("state")) { state = fileItem.getString(); } else if (fieldName.equals("city")) { city = fileItem.getString(); } else if (fieldName.equals("area")) { area = fileItem.getString(); } else if (fieldName.equals("pbhk")) { prbhk = fileItem.getString(); System.out.println(prbhk); } else if (fieldName.equals("pdescription")) { prdescrip = fileItem.getString(); System.out.println(prdescrip); } else if (fieldName.equals("ptype")) { prtype = fileItem.getString(); System.out.println(prtype); } else if (fieldName.equals("paddress1")) { pradd1 = fileItem.getString(); System.out.println(pradd1); } else if (fieldName.equals("paddress2")) { pradd2 = fileItem.getString(); System.out.println(pradd2); } else if (fieldName.equals("page")) { prage = fileItem.getString(); System.out.println(prage); } else if (fieldName.equals("pfarea")) { prfarea = fileItem.getString(); System.out.println(prfarea); } else if (fieldName.equals("prid")) { prid = Integer.parseInt(fileItem.getString()); System.out.println("prid is " + prid); } } else { String fieldName = fileItem.getFieldName(); if (fieldName.equals("pic1")) { //getting name of file prphoto = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring // String extension=custphoto.substring(custphoto.indexOf(".")+1,custphoto.length());; //rename file...concate name and extension // custphoto=ln.getUId()+"."+extension; try { // FOR UBUNTU add GETRESOURCE and GETPATH String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // String filePath= this.getServletContext().getResource("/images/profilepic").getPath()+"\\"; System.out.println("====" + fp); fileItem.write(new File(fp + prphoto)); } catch (Exception ex) { out.println(ex.toString()); } } if (fieldName.equals("pic2")) { prphoto1 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // String filePath= this.getServletContext().getResource("/images/profilepic").getPath()+"\\"; System.out.println("====" + fp); fileItem.write(new File(fp + prphoto1)); } catch (Exception ex) { out.println(ex.toString()); } } if (fieldName.equals("pic3")) { prphoto2 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // String filePath= this.getServletContext().getResource("/images/profilepic").getPath()+"\\"; System.out.println("====" + fp); fileItem.write(new File(fp + prphoto2)); } catch (Exception ex) { out.println(ex.toString()); } } if (fieldName.equals("pic4")) { prphoto3 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // String filePath= this.getServletContext().getResource("/images/profilepic").getPath()+"\\"; System.out.println("====" + fp); fileItem.write(new File(fp + prphoto3)); } catch (Exception ex) { out.println(ex.toString()); } } } } SessionFactory sf = NewHibernateUtil.getSessionFactory(); Session ss = sf.openSession(); Transaction tr = ss.beginTransaction(); // String state=""; // Criteria cr = ss.createCriteria(StateMaster.class); // cr.add(Restrictions.eq("sId", Integer.parseInt(stateid))); // ArrayList<StateMaster> ar = (ArrayList<StateMaster>)cr.list(); // System.out.println("----------"+ar.size()); // if(ar.isEmpty()){ // // }else{ // state = ar.get(0).getSName(); // System.out.println("-------"+ar.get(0)); // } // // String city=""; // Criteria cr2 = ss.createCriteria(CityMaster.class); // cr2.add(Restrictions.eq("cityId", Integer.parseInt(cityid))); // ArrayList<CityMaster> ar2 = (ArrayList<CityMaster>)cr2.list(); // System.out.println("----------"+ar2.size()); // if(ar2.isEmpty()){ // // }else{ // city = ar2.get(0).getCityName(); // System.out.println("-------"+city); // } // // String area=""; // Criteria cr3 = ss.createCriteria(AreaMaster.class); // cr3.add(Restrictions.eq("areaId", Integer.parseInt(areaid))); // ArrayList<AreaMaster> ar3 = (ArrayList<AreaMaster>)cr3.list(); // System.out.println("----------"+ar3.size()); // if(ar3.isEmpty()){ // // }else{ // area = ar3.get(0).getAreaName(); // System.out.println("-------"+area); // } // // Criteria crr=ss.createCriteria(AgentDetail.class); // crr.add(Restrictions.eq("uId", ln.getUId())); // ArrayList<AgentDetail> arr=(ArrayList<AgentDetail>)crr.list(); // if(arr.isEmpty()) // { // out.print("array empty"); // } // else // { // AgentDetail agd=arr.get(0); PropDetail prd = (PropDetail) ss.get(PropDetail.class, prid); System.out.println("old object id is " + prd.getPId()); PropDetail prd1 = new PropDetail(); prd1.setUId(prd.getUId()); prd1.setPId(prd.getPId()); prd1.setPDescription(prdescrip); prd1.setPImg1(prphoto1); prd1.setPImg2(prphoto2); prd1.setPImg3(prphoto3); prd1.setPImg4(prphoto); prd1.setPAdd1(pradd1); prd1.setPAdd2(pradd2); prd1.setPAge(Integer.parseInt(prage)); prd1.setPBhk(prbhk); prd1.setPFloor(Integer.parseInt(prfarea)); prd1.setPGmap(null); prd1.setPName(prname); prd1.setPPrice(Integer.parseInt(prprice)); prd1.setPStatus(null); prd1.setPCity(city); prd1.setPArea(area); prd1.setPState(state); prd1.setPType(prtype); ss.evict(prd); ss.update(prd1); tr.commit(); RequestDispatcher rd = request.getRequestDispatcher("getstate?id=9"); rd.forward(request, response); } } catch (HibernateException e) { out.println(e.getMessage()); } }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *//*w w w .j a v a 2 s .c o m*/ @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:datalab.upo.ladonspark.controller.uploadFile.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . j av a2 s . co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, Exception { List<objectresult> lor = new ArrayList<>(); List<objectresult> loraux = new ArrayList<>(); boolean result = false; String urlf = ""; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // req es la HttpServletRequest que recibimos del formulario. // Los items obtenidos sern cada uno de los campos del formulario, // tanto campos normales como ficheros subidos. List items = upload.parseRequest(request); // Se recorren todos los items, que son de tipo FileItem for (Object item : items) { FileItem uploaded = (FileItem) item; // Hay que comprobar si es un campo de formulario. Si no lo es, se guarda el fichero // subido donde nos interese if (!uploaded.isFormField()) { // No es campo de formulario, guardamos el fichero en algn sitio if (!uploaded.getName().equals("")) { urlf = uploaded.getName(); File fichero = new File(this.getPath() + "src/main/webapp/algorithm/dataAlgoritm/", uploaded.getName()); uploaded.write(fichero); } else { result = true; } } else { // es un campo de formulario, podemos obtener clave y valor String key = uploaded.getFieldName(); String value = uploaded.getString(); lor.add(new objectresult(key, value)); if (value == null || value.equals("")) { result = true; } } } if (result) { request.getSession().setAttribute("error", "error"); String url = "algorithm/addalgo.jsp"; response.sendRedirect(url); } else { Algorithm a = new Algorithm(lor.get(0).getValue(), lor.get(1).getValue(), urlf); DaoAlgoritm da = new DaoAlgoritm(); da.create(a); a = da.getAlgoritm(a.getNameAlg()); DaoParameter dp = new DaoParameter(); for (int i = 3; i < lor.size(); i++) { dp.create(new Parameter(a, lor.get(i).getValue(), lor.get(i + 1).getValue())); i++; } request.getSession().setAttribute("algorithm", new DaoAlgoritm().optenerAlgoritmos()); String url = "algorithm/masteralgo.jsp"; response.sendRedirect(url); } }
From source file:fr.cnes.sitools.extensions.astro.application.uws.jobmanager.AbstractJobTask.java
protected final void copyFile(final FileItem fi) throws UniversalWorkerException { final String uri = "riap://application/jobCache/" + jobTaskId + "/" + fi.getName(); final ClientResource client = new ClientResource(uri); client.put(fi.getString()); client.release();/*from ww w . j av a 2 s.c o m*/ }
From source file:com.nartex.FileManager.java
public JSONObject add() { JSONObject fileInfo = null;/*w w w . j a v a2s . c o m*/ Iterator it = this.files.iterator(); String mode = ""; String currentPath = ""; if (!it.hasNext()) { this.error(lang("INVALID_FILE_UPLOAD")); } else { String allowed[] = { ".", "-" }; FileItem item = null; String fileName = ""; try { while (it.hasNext()) { item = (FileItem) it.next(); if (item.isFormField()) { if (item.getFieldName().equals("mode")) { mode = item.getString(); if (!mode.equals("add")) { this.error(lang("INVALID_FILE_UPLOAD")); } } else if (item.getFieldName().equals("currentpath")) { currentPath = item.getString(); } } else if (item.getFieldName().equals("newfile")) { fileName = item.getName(); // strip possible directory (IE) int pos = fileName.lastIndexOf(File.separator); if (pos > 0) fileName = fileName.substring(pos + 1); boolean error = false; long maxSize = 0; if (config.getProperty("upload-size") != null) { maxSize = Integer.parseInt(config.getProperty("upload-size")); if (maxSize != 0 && item.getSize() > (maxSize * 1024 * 1024)) { this.error(sprintf(lang("UPLOAD_FILES_SMALLER_THAN"), maxSize + "Mb")); error = true; } } if (!error) { if (!isImage(fileName) && (config.getProperty("upload-imagesonly") != null && config.getProperty("upload-imagesonly").equals("true") || this.params.get("type") != null && this.params.get("type").equals("Image"))) { this.error(lang("UPLOAD_IMAGES_ONLY")); } else { fileInfo = new JSONObject(); LinkedHashMap<String, String> strList = new LinkedHashMap<String, String>(); strList.put("fileName", fileName); fileName = (String) cleanString(strList, allowed).get("fileName"); if (config.getProperty("upload-overwrite").equals("false")) { fileName = this.checkFilename(this.documentRoot + currentPath, fileName, 0); } File saveTo = new File(this.documentRoot + currentPath + fileName); item.write(saveTo); fileInfo.put("Path", currentPath); fileInfo.put("Name", fileName); fileInfo.put("Error", ""); fileInfo.put("Code", 0); } } } } } catch (Exception e) { this.error(lang("INVALID_FILE_UPLOAD")); } } return fileInfo; }
From source file:com.mx.nibble.middleware.web.util.FileParse.java
public String execute(ActionInvocation invocation) throws Exception { Iterator iterator = parameters.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue()); }/*from www . j a va 2 s.c o m*/ ActionContext ac = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE); /** * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org. * * Note: * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. * * * * * * */ // Directory to store all the uploaded files String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = request.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { // Get URL Parameters. Enumeration paraNames = request.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); // write the file fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// //Chunk management: if it was the last chunk, let's recover the complete file //by concatenating all chunk parts. // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //System.out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); PrintWriter out = ServletActionContext.getResponse().getWriter(); out.write("SUCCESS"); //System.out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }