List of usage examples for org.apache.commons.fileupload FileItem getString
String getString();
From source file:com.cloudbees.plugins.deployer.CloudbeesDeployWarTest.java
public void assertOnFileItems(String buildDescription) throws IOException { for (FileItem fileItem : cloudbeesServer.cloudbessServlet.items) { //archive check it's a war content //description check Jenkins BUILD_ID if (fileItem.getFieldName().equals("description")) { String description = fileItem.getString(); assertEquals(buildDescription, description); } else if (fileItem.getFieldName().equals("api_key")) { assertEquals("Testing121212Testing", fileItem.getString()); } else if (fileItem.getFieldName().equals("app_id")) { assertEquals("test-account/test-app", fileItem.getString()); } else if (fileItem.getFieldName().equals("archive")) { assertOnArchive(fileItem.getInputStream()); } else {/* w ww . j a v a2 s. c o m*/ System.out.println(" item " + fileItem); } } }
From source file:Controller.ControllerCustomers.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/* w w w . j a v a2 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 { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (Exception e) { e.printStackTrace(); } Iterator iter = items.iterator(); Hashtable params = new Hashtable(); String fileName = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { params.put(item.getFieldName(), item.getString()); } else { try { String itemName = item.getName(); fileName = itemName.substring(itemName.lastIndexOf("\\") + 1); String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName; String username = (String) params.get("txtusername"); String password = (String) params.get("txtpassword"); String hoten = (String) params.get("txthoten"); String gioitinh = (String) params.get("txtgioitinh"); String email = (String) params.get("txtemail"); String role = (String) params.get("txtrole"); String anh = (String) params.get("txtanh"); //Update product if (fileName.equals("")) { Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh); CustomerDAO.SuaThongTinKhachHang(Cus); RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } else { // bat dau ghi file File savedFile = new File(RealPath); item.write(savedFile); //ket thuc ghi Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, "upload\\" + fileName); CustomerDAO.SuaThongTinKhachHang(Cus); RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp"); rd.forward(request, response); } } catch (Exception e) { System.out.println(e); RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp"); rd.forward(request, response); } } } } }
From source file:AES.Controllers.FileController.java
@RequestMapping(value = "/upload", method = RequestMethod.GET) public void upload(HttpServletResponse response, HttpServletRequest request, @RequestParam Map<String, String> requestParams) throws IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Hello<br/>"); boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { out.println("You are not trying to upload<br/>"); return;//from w ww . j a va 2 s .c om } out.println("You are trying to upload<br/>"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> fields = upload.parseRequest(request); out.println("Number of fields: " + fields.size() + "<br/><br/>"); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { out.println("No fields found"); return; } out.println("<table border=\"1\">"); while (it.hasNext()) { out.println("<tr>"); FileItem fileItem = it.next(); boolean isFormField = fileItem.isFormField(); if (isFormField) { out.println("<td>regular form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString()); out.println("</td>"); } else { out.println("<td>file form field</td><td>FIELD NAME: " + fileItem.getFieldName() + "<br/>STRING: " + fileItem.getString() + "<br/>NAME: " + fileItem.getName() + "<br/>CONTENT TYPE: " + fileItem.getContentType() + "<br/>SIZE (BYTES): " + fileItem.getSize() + "<br/>TO STRING: " + fileItem.toString()); out.println("</td>"); String path = request.getSession().getServletContext().getRealPath("") + "\\uploads\\"; //System.out.println(request.getSession().getServletContext().getRealPath("")); File f = new File(path + fileItem.getName()); if (!f.exists()) f.createNewFile(); fileItem.write(f); } out.println("</tr>"); } out.println("</table>"); } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception ex) { Logger.getLogger(FileController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.app.framework.web.MultipartFilter.java
/** * Process multipart request item as regular form field. The name and value * of each regular form field will be added to the given parameterMap. * * @param formField The form field to be processed. * @param parameterMap The parameterMap to be used for the * HttpServletRequest.//w w w.j a va 2 s. c o m */ private void processFormField(FileItem formField, Map<String, String[]> parameterMap) { String name = formField.getFieldName(); String value = formField.getString(); String[] values = parameterMap.get(name); if (values == null) { // Not in parameter map yet, so add as new value. parameterMap.put(name, new String[] { value }); } else { // Multiple field values, so add new value to existing array. int length = values.length; String[] newValues = new String[length + 1]; System.arraycopy(values, 0, newValues, 0, length); newValues[length] = value; parameterMap.put(name, newValues); } }
From source file:com.silverpeas.form.displayers.CheckBoxDisplayer.java
@Override public List<String> update(List<FileItem> items, TextField field, FieldTemplate template, PagesContext pageContext) throws FormException { SilverTrace.debug("form", "AbstractForm.getParameterValues", "root.MSG_GEN_ENTER_METHOD", "parameterName = " + template.getFieldName()); String value = ""; Iterator<FileItem> iter = items.iterator(); String parameterName = template.getFieldName(); while (iter.hasNext()) { FileItem item = iter.next(); if (parameterName.equals(item.getFieldName())) { value += item.getString(); if (iter.hasNext()) { value += "##"; }/* ww w. j a va 2 s .co m*/ } } SilverTrace.debug("form", "AbstractForm.getParameterValues", "root.MSG_GEN_EXIT_METHOD", "parameterValue = " + value); if (pageContext.getUpdatePolicy() == PagesContext.ON_UPDATE_IGNORE_EMPTY_VALUES && !StringUtil.isDefined(value)) { return new ArrayList<String>(); } return update(value, field, template, pageContext); }
From source file:com.rapidsist.portal.cliente.editor.SimpleUploaderServlet.java
/** * Manage the Upload requests.<br> * * The servlet accepts commands sent in the following format:<br> * simpleUploader?Type=ResourceType<br><br> * It store the file (renaming it in case a file with the same name exists) and then return an HTML file * with a javascript command in it.//from w ww . j a v a 2s. c o m * */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("PASO POR EL METODO doPost DEL SERVLET SimpleUploaderServlet"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String typeStr = request.getParameter("Type"); String currentPath = baseDir + typeStr; String currentDirPath = getServletContext().getRealPath(currentPath); currentPath = request.getContextPath() + currentPath; String retVal = "0"; String newName = ""; String fileUrl = ""; String errorMessage = ""; if (enabled) { DiskFileUpload upload = new DiskFileUpload(); try { List items = upload.parseRequest(request); Map fields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } FileItem uplFile = (FileItem) fields.get("NewFile"); String fileNameLong = uplFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); String[] pathParts = fileNameLong.split("/"); String fileName = pathParts[pathParts.length - 1]; String nameWithoutExt = getNameWithoutExtension(fileName); String ext = getExtension(fileName); File pathToSave = new File(currentDirPath, fileName); fileUrl = currentPath + "/" + fileName; if (extIsAllowed(typeStr, ext)) { int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + counter + ")" + "." + ext; fileUrl = currentPath + "/" + newName; retVal = "201"; pathToSave = new File(currentDirPath, newName); counter++; } uplFile.write(pathToSave); } else { retVal = "202"; errorMessage = ""; } } catch (Exception ex) { retVal = "203"; } } else { retVal = "1"; errorMessage = "This file uploader is disabled. Please check the WEB-INF/web.xml file"; } out.println("<script type=\"text/javascript\">"); out.println("window.parent.OnUploadCompleted(" + retVal + ",'" + fileUrl + "','" + newName + "','" + errorMessage + "');"); out.println("</script>"); out.flush(); out.close(); }
From source file:Emporium.Servlet.ServImportarDestinatario.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va 2 s.c o 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 IOException { HttpSession sessao = request.getSession(); String nomeBD = (String) sessao.getAttribute("nomeBD"); if (nomeBD != null) { boolean isMultiPart = FileUpload.isMultipartContent(request); int idCliente = 0; int idDepartamento = 0; if (isMultiPart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 2); List items = upload.parseRequest(request); Iterator iter = items.iterator(); FileItem itemImg = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("idCliente")) { idCliente = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("idDepartamento")) { idDepartamento = Integer.parseInt(item.getString()); } } if (!item.isFormField()) { if (item.getName().length() > 0) { itemImg = item; } } } if (!itemImg.getName().toUpperCase().endsWith(".CSV") && !itemImg.getName().toUpperCase().endsWith(".TXT")) { response.sendRedirect( "Cliente/Cadastros/destinatario_lista.jsp?msg=Escolha um arquivo para importacao !"); } else { //CONSULTA DADOS DO CLIENTE/DEPARTAMENTO/CONTRATO Clientes cli = contrCliente.consultaClienteById(idCliente, nomeBD); if (cli != null) { String condicao = ContrDestinatarioImporta.importaPedido(itemImg, idCliente, idDepartamento, nomeBD); response.sendRedirect("Cliente/Cadastros/destinatario_lista.jsp?msg=" + condicao); } else { response.sendRedirect( "Cliente/Cadastros/destinatario_lista.jsp?msg=Cliente nao encontrado no banco de dados!"); } } } catch (FileUploadException ex) { response.sendRedirect( "Cliente/Cadastros/destinatario_lista.jsp?msg=Falha no Upload do Arquivo de Importacao!\n" + ex); } catch (Exception ex) { response.sendRedirect( "Cliente/Cadastros/destinatario_lista.jsp?msg=Falha na importacao!\n" + ex); } } } else { response.sendRedirect("Cliente/Cadastros/destinatario_lista.jsp?msg=Sua sessao expirou!"); } }
From source file:Emporium.Servlet.ServImportaVpne.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// ww w . ja va 2 s. c o 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 { HttpSession sessao = request.getSession(); String nomeBD = (String) sessao.getAttribute("nomeBD"); boolean isMultiPart = FileUpload.isMultipartContent(request); int idCliente = 0, idDepartamento = 0; if (nomeBD != null) { if (isMultiPart) { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024 * 2); List items = upload.parseRequest(request); Iterator iter = items.iterator(); ArrayList<FileItem> listaArq = new ArrayList<>(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("idCliente")) { idCliente = Integer.parseInt(item.getString()); } if (item.getFieldName().equals("idDepartamento")) { idDepartamento = Integer.parseInt(item.getString()); } } if (!item.isFormField()) { if (item.getName().length() > 0) { listaArq.add(item); } } } if (listaArq.isEmpty()) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Escolha um arquivo para importacao !"); } else if (listaArq.size() > 200) { response.sendRedirect( "Cliente/Servicos/vpne.jsp?msg=Importacao maxima de 200 arquivos de cada vez!"); } else { String condicao = ContrVpne.importaPedidoVpne(listaArq, idCliente, idDepartamento, nomeBD); if (condicao.startsWith("ERRO")) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao); } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=" + condicao); } } } catch (FileUploadException ex) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex); } catch (Exception ex) { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Falha na importacao!\n" + ex); } } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=is not a multipart form"); } } else { response.sendRedirect("Cliente/Servicos/vpne.jsp?msg=Sua sessao expirou!"); } }
From source file:net.scran24.staff.server.services.UploadUserInfoService.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = new PrintWriter(outputStream); if (!ServletFileUpload.isMultipartContent(req)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); } else {// w w w . j a v a2 s . c o m DiskFileItemFactory factory = new DiskFileItemFactory(); ServletContext servletContext = this.getServletConfig().getServletContext(); File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); factory.setRepository(repository); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(req); InputStream file = null; String role = null; Set<String> permissions = new HashSet<String>(); String surveyId = req.getParameter("surveyId"); for (FileItem i : items) { if (i.getFieldName().equals("file")) file = i.getInputStream(); else if (i.getFieldName().equals("role")) role = i.getString(); else if (i.getFieldName().equals("permission")) permissions.add(i.getString()); } if (file == null) throw new ServletException("file field not specified"); if (role == null) throw new ServletException("role field not specified"); if (surveyId == null) throw new ServletException("surveyId field not specified"); List<UserRecord> userRecords = UserRecordCSV.fromCSV(file); try { Set<String> roles = new HashSet<String>(); roles.add(role); dataStore.saveUsers(surveyId, mapToSecureUserRecords(userRecords, roles, permissions)); writer.print("OK"); } catch (DataStoreException e) { writer.print("ERR:" + e.getMessage()); } catch (DuplicateKeyException e) { writer.print("ERR:" + e.getMessage()); } } catch (FileUploadException e) { writer.print("ERR:" + e.getMessage()); } catch (IOException e) { writer.print("ERR:" + e.getMessage()); } } writer.close(); }
From source file:edu.um.umflix.stubs.UploadServletStub.java
protected List<FileItem> getFileItems(HttpServletRequest request) throws FileUploadException { if (error.equals("fileUpload")) new FileUploadException(); File file = null;/*from w w w .j a va2 s . c o m*/ FileItem item1 = null; List<FileItem> list = new ArrayList<FileItem>(); for (int i = 0; i < fields.length; i++) { FileItem item = Mockito.mock(FileItem.class); Mockito.when(item.isFormField()).thenReturn(true); Mockito.when(item.getFieldName()).thenReturn(fields[i]); if (fields[i].equals("premiere") || fields[i].equals("endDate") || fields[i].equals("startDate")) { Mockito.when(item.getString()).thenReturn("2013-06-01"); } else { Mockito.when(item.getString()).thenReturn("11"); } if (fields[i].equals("premiere") && error.equals("date")) Mockito.when(item.getString()).thenReturn("11"); if (fields[i].equals("clipduration0")) { Mockito.when(item.getString()).thenReturn("01:22:01"); } list.add(item); } try { file = File.createTempFile("aaaa", "aaaatest"); item1 = Mockito.mock(FileItem.class); Mockito.when(item1.getInputStream()).thenReturn(new FileInputStream(file)); } catch (IOException e) { e.printStackTrace(); } list.add(item1); FileItem token = Mockito.mock(FileItem.class); Mockito.when(token.isFormField()).thenReturn(true); Mockito.when(token.getFieldName()).thenReturn("token"); if (error.equals("token")) { Mockito.when(token.getString()).thenReturn("invalidToken"); } else Mockito.when(token.getString()).thenReturn("validToken"); list.add(token); return list; }