List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:com.mx.nibble.middleware.web.util.FileUpload.java
public void performTask(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) { /**//from w w w . ja va 2 s . com * 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. * * * * * * */ logger.debug(" Directory to store all the uploaded files"); String ourTempDirectory = "/opt/erp/import/obras/"; try { out = response.getWriter(); } catch (Exception e) { e.printStackTrace(); } byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF; out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); logger.debug("Initialization for chunk management."); boolean bLastChunk = false; int numChunk = 0; logger.debug( "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(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Headers of the received request:"); logger.debug("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); out.println("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); logger.debug("[parseRequest.jsp] " + header + ": " + request.getHeader(header)); } out.println("[parseRequest.jsp] ------------------------------ "); try { logger.debug(" Get URL Parameters."); Enumeration paraNames = request.getParameterNames(); out.println("[parseRequest.jsp] ------------------------------ "); out.println("[parseRequest.jsp] Parameters: "); logger.debug("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = request.getParameter(pname); out.println("[parseRequest.jsp] " + pname + " = " + pvalue); logger.debug("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { numChunk = Integer.parseInt(pvalue); } if (pname.equals("error") && pvalue.equals("true")) { generateError = true; logger.debug( "For debug convenience, putting error=true as a URL parameter, will generate an error in this response."); } if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; logger.debug( "For debug convenience, putting warning=true as a URL parameter, will generate a warning in this response."); } if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; logger.debug( "For debug convenience, putting readRequest=true as a URL parameter, will send back the request content into the response of this page."); } } 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/ /////////////////////////////////////////////////////////////////////////////////////////////////////// logger.debug(" Create a factory for disk-based file items"); DiskFileItemFactory factory = new DiskFileItemFactory(); logger.debug(" Set factory constraints"); factory.setSizeThreshold(ourMaxMemorySize); logger.debug("ourTempDirectory" + ourTempDirectory); factory.setRepository(new File(ourTempDirectory)); logger.debug(" Create a new file upload handler"); ServletFileUpload upload = new ServletFileUpload(factory); logger.debug(" Set overall request size constraint"); upload.setSizeMax(ourMaxRequestSize); logger.debug(" Parse the request"); if (sendRequest) { logger.debug("For debug only. Should be removed for production systems. "); out.println( "[parseRequest.jsp] ==========================================================================="); out.println("[parseRequest.jsp] Sending the received request content: "); logger.debug("[parseRequest.jsp] Sending the received request content: "); InputStream is = request.getInputStream(); int c; while ((c = is.read()) >= 0) { out.write(c); } logger.debug("while"); is.close(); out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!request.getContentType().startsWith("multipart/form-data")) { out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + request.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(request); logger.debug(" Process the uploaded items" + items.size()); Iterator iter = items.iterator(); FileItem fileItem; File fout; out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); logger.debug( "If we receive the md5sum parameter, we've read finished to read the current file. It's not"); logger.debug( "a very good (end of file) signal. Will be better in the future ... probably !"); logger.debug("Let's put a separator, to make output easier to read."); if (fileItem.getFieldName().equals("md5sum[]")) { out.println("[parseRequest.jsp] ------------------------------ "); } } else { logger.debug("Ok, we've got a file. Let's process it."); logger.debug("Again, for all informations of what is exactly a FileItem, please"); logger.debug("have a look to http://jakarta.apache.org/commons/fileupload/"); out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); logger.debug( "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()); out.println("[parseRequest.jsp] File Out: " + fout.toString()); logger.debug(" write the file"); fileItem.write(fout); // logger.debug("Chunk management: if it was the last chunk, let's recover the complete file"); logger.debug("by concatenating all chunk parts."); logger.debug(""); if (bLastChunk) { out.println("[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); logger.debug("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; out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } logger.debug(" End of chunk management"); // fileItem.delete(); } } logger.debug("while"); } if (generateWarning) { out.println("WARNING: just a warning message.\\nOn two lines!"); } out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); logger.debug("Let's wait a little, to simulate the server time to manage the file."); Thread.sleep(500); logger.debug("Do you want to test a successful upload, or the way the applet reacts to an error ?"); if (generateError) { out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { out.println("SUCCESS"); logger.debug(""); } out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { out.println(""); out.println("ERROR: Exception e = " + e.toString()); out.println(""); } }
From source file:com.funambol.json.gui.GuiServlet.java
private void manageUpload(HttpServletRequest request, Map<String, String> parameters, Map<String, File> files) throws Exception { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { parameters.put(item.getFieldName(), item.getString()); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); File output = File.createTempFile(fieldName, fileName); item.write(output);/*from w ww . ja v a 2 s. com*/ files.put(fieldName, output); } } } else { throw new Exception("File upload failed."); } }
From source file:es.sm2.openppm.front.servlets.AbstractGenericServlet.java
/** * Find Multipart filed by name/*from ww w . j a v a2 s . co m*/ * * @param name - name of field * @return field in String format * @throws UnsupportedEncodingException bad encoding format */ protected String getMultipartField(String name, String encoding) throws UnsupportedEncodingException { if (getMultipartFields() != null) { FileItem fileItem = getMultipartFields().get(name); if (fileItem != null) { return encoding == null ? fileItem.getString() : fileItem.getString(encoding); } } return StringPool.BLANK; }
From source file:com.tremolosecurity.proxy.ProxyRequest.java
public ProxyRequest(HttpServletRequest req, HttpSession session) throws Exception { super(req);/*from www .j a v a 2 s . c om*/ this.session = session; ServletRequestContext reqCtx = new ServletRequestContext(req); this.isMultiPart = "POST".equalsIgnoreCase(req.getMethod()) && reqCtx.getContentType() != null && reqCtx.getContentType().toLowerCase(Locale.ENGLISH).startsWith("multipart/form-data"); this.isParamsInBody = true; this.isPush = false; this.paramList = new ArrayList<String>(); this.reqParams = new HashMap<String, ArrayList<String>>(); this.queryString = new ArrayList<NVP>(); HttpServletRequest request = (HttpServletRequest) super.getRequest(); if (request.getQueryString() != null && !request.getQueryString().isEmpty()) { StringTokenizer toker = new StringTokenizer(request.getQueryString(), "&"); while (toker.hasMoreTokens()) { String qp = toker.nextToken(); int index = qp.indexOf('='); if (index > 0) { String name = qp.substring(0, qp.indexOf('=')); String val = URLDecoder.decode(qp.substring(qp.indexOf('=') + 1), "UTf-8"); this.queryString.add(new NVP(name, val)); } } } if (this.isMultiPart) { this.isPush = true; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(req); this.reqFiles = new HashMap<String, ArrayList<FileItem>>(); for (FileItem item : items) { //this.paramList.add(item.getName()); if (item.isFormField()) { ArrayList<String> vals = this.reqParams.get(item.getFieldName()); if (vals == null) { vals = new ArrayList<String>(); this.reqParams.put(item.getFieldName(), vals); } this.paramList.add(item.getFieldName()); vals.add(item.getString()); } else { ArrayList<FileItem> vals = this.reqFiles.get(item.getFieldName()); if (vals == null) { vals = new ArrayList<FileItem>(); this.reqFiles.put(item.getFieldName(), vals); } vals.add(item); } } } else { Enumeration enumer = req.getHeaderNames(); String contentType = null; while (enumer.hasMoreElements()) { String name = (String) enumer.nextElement(); if (name.equalsIgnoreCase("content-type") || name.equalsIgnoreCase("content-length")) { this.isPush = true; if (name.equalsIgnoreCase("content-type")) { contentType = req.getHeader(name); } } } if (this.isPush) { if (contentType == null || !contentType.startsWith("application/x-www-form-urlencoded")) { this.isParamsInBody = false; ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = req.getInputStream(); int len; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } req.setAttribute(ProxySys.MSG_BODY, baos.toByteArray()); } else if (contentType.startsWith("application/x-www-form-urlencoded")) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream in = req.getInputStream(); int len; byte[] buffer = new byte[1024]; while ((len = in.read(buffer)) > 0) { baos.write(buffer, 0, len); } StringTokenizer toker = new StringTokenizer(new String(baos.toByteArray()), "&"); this.orderedList = new ArrayList<NVP>(); while (toker.hasMoreTokens()) { String token = toker.nextToken(); int index = token.indexOf('='); String name = token.substring(0, index); if (name.indexOf('%') != -1) { name = URLDecoder.decode(name, "UTF-8"); } String val = ""; if (index < (token.length() - 1)) { val = URLDecoder.decode(token.substring(token.indexOf('=') + 1), "UTF-8"); } this.orderedList.add(new NVP(name, val)); this.paramList.add(name); ArrayList<String> params = this.reqParams.get(name); if (params == null) { params = new ArrayList<String>(); this.reqParams.put(name, params); } params.add(val); } } } } }
From source file:fr.cnes.sitools.extensions.astro.application.uws.jobmanager.AbstractJobTask.java
private Form uploadFile(final Representation rep) throws FileUploadException, Exception { // The Apache FileUpload project parses HTTP requests which // conform to RFC 1867, "Form-based File Upload in HTML". That // is, if an HTTP request is submitted using the POST method, // and with a content type of "multipart/form-data", then // FileUpload can parse that request, and get all uploaded files // as FileItem. // 1/ Create a factory for disk-based file items final DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1000240);//from w ww .j a va 2s.c o m // 2/ Create a new file upload handler based on the Restlet // FileUpload extension that will parse Restlet requests and // generates FileItems. final RestletFileUpload upload = new RestletFileUpload(factory); List items; // 3/ Request is parsed by the handler which generates a // list of FileItems items = upload.parseRepresentation(rep); // Process only the uploaded item and save it on disk final Form form = new Form(); for (final Iterator it = items.iterator(); it.hasNext();) { final FileItem fi = (FileItem) it.next(); if (fi.isFormField()) { form.add(fi.getFieldName(), fi.getString()); } else { form.add(fi.getFieldName(), fi.getName()); this.copyFile(fi); } } return form; }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST * data as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link PostMethod} * @throws javax.servlet.ServletException If something fails when uploading the content to the server */// w ww .j ava 2 s. com @SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" }) 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:hu.sztaki.lpds.pgportal.portlets.credential.AssertionPortlet.java
/** * Uploading SAML file(s)./* www.j a v a 2 s . c om*/ * The parameters are filled in by the user on the saml/UploadAssertion.jsp page. * @param request ActionRequest * @param response ActionResponse */ @Override public synchronized void doUpload(ActionRequest request, ActionResponse response) { logger.trace(""); // logger.info("Assertion-doUpload"); FileItem samlFile = null; String sresource = null; // selected resource String action = request.getParameter("guse"); logger.info("Action:" + action); try { DiskFileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload pfu = new PortletFileUpload(factory); pfu.setSizeMax(1048576); // Maximum upload size 1Mb Iterator iter = pfu.parseRequest(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 msg : result) { if (flag) { sb.append("<br />"); } else { flag = true; } sb.append(msg); } request.setAttribute("msg", sb.toString()); } catch (Exception e) { request.setAttribute("msg", "Upload failed. Reason: " + e.getMessage()); logger.info("Upload of asseriont failed. Reason: " + e.getMessage()); logger.debug("Exception:", e); } }
From source file:com.sun.faban.harness.webclient.CLIServlet.java
private void doSubmit(String[] reqC, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (reqC.length < 3) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark and profile not provided in request."); return;/*from w ww. j av a 2s . c o m*/ } // first is the bench name BenchmarkDescription desc = BenchmarkDescription.getDescription(reqC[1]); if (desc == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Benchmark " + reqC[1] + " not deployed."); return; } try { String user = null; String password = null; boolean hasPermission = true; ArrayList<String> runIdList = new ArrayList<String>(); DiskFileUpload fu = new DiskFileUpload(); // No maximum size fu.setSizeMax(-1); // maximum size that will be stored in memory fu.setSizeThreshold(8192); // the location for saving data larger than getSizeThreshold() fu.setRepositoryPath(Config.TMP_DIR); List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw new ServletException(e); } for (Iterator i = fileItems.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("sun".equals(fieldName)) { user = item.getString(); } else if ("sp".equals(fieldName)) { password = item.getString(); } continue; } if (reqC[2] == null) // No profile break; if (desc == null) break; if (!"configfile".equals(fieldName)) continue; if (Config.SECURITY_ENABLED) { if (Config.CLI_SUBMITTER == null || Config.CLI_SUBMITTER.length() == 0 || !Config.CLI_SUBMITTER.equals(user)) { hasPermission = false; break; } if (Config.SUBMIT_PASSWORD == null || Config.SUBMIT_PASSWORD.length() == 0 || !Config.SUBMIT_PASSWORD.equals(password)) { hasPermission = false; break; } } String usrDir = Config.PROFILES_DIR + reqC[2]; File dir = new File(usrDir); if (dir.exists()) { if (!dir.isDirectory()) { logger.severe(usrDir + " should be a directory"); dir.delete(); logger.fine(dir + " deleted"); } else logger.fine("Saving parameter file to" + usrDir); } else { logger.fine("Creating new profile directory for " + reqC[2]); if (dir.mkdirs()) logger.fine("Created new profile directory " + usrDir); else logger.severe("Failed to create profile " + "directory " + usrDir); } // Save the latest config file into the profile directory String dstFile = Config.PROFILES_DIR + reqC[2] + File.separator + desc.configFileName + "." + desc.shortName; item.write(new File(dstFile)); runIdList.add(RunQ.getHandle().addRun(user, reqC[2], desc)); } response.setContentType("text/plain"); Writer writer = response.getWriter(); if (!hasPermission) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); writer.write("Permission denied!\n"); } if (runIdList.size() == 0) writer.write("No runs submitted.\n"); for (String newRunId : runIdList) { writer.write(newRunId); } writer.flush(); writer.close(); } catch (ServletException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (IOException e) { logger.log(Level.SEVERE, e.getMessage(), e); throw e; } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); throw new ServletException(e); } }
From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java
public String execute() throws Exception { //ActionContext ac = invocation.getInvocationContext(); HttpServletResponse response = ServletActionContext.getResponse(); // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest()); HttpServletRequest multipartRequest = ServletActionContext.getRequest(); List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest); System.out.println("TAMAO ITEMS " + items2.size()); System.out.println("Check that we have a file upload request"); boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest); System.out.println("isMultipart: " + isMultipart); 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;//from w ww.j a v a2 s .c o m 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 = multipartRequest.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 + ": " + multipartRequest.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { System.out.println(" Get URL Parameters."); Enumeration paraNames = multipartRequest.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = multipartRequest.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { System.out.println("pname.equals(\"jufinal\")"); bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { System.out.println("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 = multipartRequest.getInputStream(); int c; while ((c = is.read()) >= 0) { System.out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + multipartRequest.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(multipartRequest); // 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()); System.out.println(" write the file"); fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// System.out.println( " Chunk management: if it was the last chunk, let's recover the complete file"); System.out.println(" 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) { //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"); //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; }
From source file:prop_add_serv.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va 2 s . com*/ * * @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"); HttpSession hs = request.getSession(); PrintWriter out = response.getWriter(); try { if (hs.getAttribute("user") != null) { Login ln = (Login) hs.getAttribute("user"); System.out.println(ln.getUId()); String pradd1 = ""; String pradd2 = ""; String prage = ""; String prarea = ""; String prbhk = ""; String prdescrip = ""; String prprice = ""; String prcity = ""; String prstate = ""; String prname = ""; String prtype = ""; String prfarea = ""; String prphoto1 = ""; String prphoto2 = ""; String prphoto3 = ""; String prphoto4 = ""; // // creates FileItem instances which keep their content in a temporary file on disk 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("city")) { prcity = fileItem.getString(); System.out.println(prcity); } else if (fieldName.equals("state")) { prstate = fileItem.getString(); System.out.println(prstate); } else if (fieldName.equals("area")) { prarea = fileItem.getString(); System.out.println(prarea); } 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 { String fieldName = fileItem.getFieldName(); if (fieldName.equals("photo1")) { //getting name of file prphoto1 = new File(fileItem.getName()).getName(); //get the extension of file by diving name into substring // String extension=prphoto.substring(prphoto.indexOf(".")+1,prphoto.length());; //rename file...concate name and extension //prphoto=prname+"."+extension; //System.out.println(prphoto); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; // FOR UBUNTU add GETRESOURCE and GETPATH // String filePath = this.getServletContext().getResource("/images").getPath() + "\\"; fileItem.write(new File(fp + prphoto1)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 2 else if (fieldName.equals("photo2")) { prphoto2 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto2)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 3 else if (fieldName.equals("photo3")) { prphoto3 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto3)); } catch (Exception ex) { out.println(ex.toString()); } } //PHOTO 4 else if (fieldName.equals("photo4")) { prphoto4 = new File(fileItem.getName()).getName(); try { String fp = "/home/rushin/NetBeansProjects/The_Asset_Consultancy/web/images/property/"; fileItem.write(new File(fp + prphoto4)); } catch (Exception ex) { out.println(ex.toString()); } } } } SessionFactory sf = NewHibernateUtil.getSessionFactory(); Session ss = sf.openSession(); Transaction tr = ss.beginTransaction(); String op = ""; Criteria cr = ss.createCriteria(StateMaster.class); cr.add(Restrictions.eq("sId", Integer.parseInt(prstate))); ArrayList<StateMaster> ar = (ArrayList<StateMaster>) cr.list(); if (ar.isEmpty()) { } else { StateMaster sm = ar.get(0); op = sm.getSName(); } String city = ""; Criteria cr2 = ss.createCriteria(CityMaster.class); cr2.add(Restrictions.eq("cityId", Integer.parseInt(prcity))); 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(prarea))); 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); } PropDetail pd = new PropDetail(); pd.setUId(ln); pd.setPAge(Integer.parseInt(prage)); pd.setPBhk(prbhk); pd.setPDescription(prdescrip.trim()); pd.setPAdd1(pradd1); pd.setPAdd2(pradd2); pd.setPPrice(Integer.parseInt(prprice)); pd.setPCity(city); pd.setPState(op); pd.setPArea(area); pd.setPName(prname); pd.setPType(prtype); pd.setPImg1(prphoto1); System.out.println(prphoto1); System.out.println(prphoto2); pd.setPImg2(prphoto2); pd.setPImg3(prphoto3); pd.setPImg4(prphoto4); pd.setPFloor(Integer.parseInt(prfarea)); ss.save(pd); tr.commit(); RequestDispatcher rd = request.getRequestDispatcher("property_search_1.jsp"); rd.forward(request, response); } } catch (HibernateException e) { out.println(e.getMessage()); } }