List of usage examples for org.apache.commons.fileupload FileUploadException getMessage
public String getMessage()
From source file:fll.web.setup.CreateDB.java
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response, final ServletContext application, final HttpSession session) throws IOException, ServletException { String redirect;//from w w w . j ava 2 s . c o m final StringBuilder message = new StringBuilder(); InitFilter.initDataSource(application); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try { connection = datasource.getConnection(); // must be first to ensure the form parameters are set UploadProcessor.processUpload(request); if (null != request.getAttribute("chooseDescription")) { final String description = (String) request.getAttribute("description"); try { final URL descriptionURL = new URL(description); final Document document = ChallengeParser .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } catch (final MalformedURLException e) { throw new FLLInternalException("Could not parse URL from choosen description: " + description, e); } } else if (null != request.getAttribute("reinitializeDatabase")) { // create a new empty database from an XML descriptor final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument"); if (null == xmlFileItem || xmlFileItem.getSize() < 1) { message.append("<p class='error'>XML description document not specified</p>"); redirect = "/setup"; } else { final Document document = ChallengeParser .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET)); GenerateDB.generateDB(document, connection); application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database</i></p>"); redirect = "/admin/createUsername.jsp"; } } else if (null != request.getAttribute("createdb")) { // import a database from a dump final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump"); if (null == dumpFileItem || dumpFileItem.getSize() < 1) { message.append("<p class='error'>Database dump not specified</p>"); redirect = "/setup"; } else { ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection); // remove application variables that depend on the database application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT); message.append("<p id='success'><i>Successfully initialized database from dump</i></p>"); redirect = "/admin/createUsername.jsp"; } } else { message.append( "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>"); redirect = "/setup"; } } catch (final FileUploadException fue) { message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>"); LOG.error(fue, fue); redirect = "/setup"; } catch (final IOException ioe) { message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>"); LOG.error(ioe, ioe); redirect = "/setup"; } catch (final SQLException sqle) { message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>"); LOG.error(sqle, sqle); redirect = "/setup"; } finally { SQLFunctions.close(connection); } session.setAttribute("message", message.toString()); response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect)); }
From source file:com.ikon.servlet.admin.CssServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); String userId = request.getRemoteUser(); updateSessionManager(request);/*from w w w . j av a 2 s .com*/ try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Css css = new Css(); css.setActive(false); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("css_id")) { if (!item.getString("UTF-8").isEmpty()) { css.setId(new Long(item.getString("UTF-8")).longValue()); } } else if (item.getFieldName().equals("css_name")) { css.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_context")) { css.setContext(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_content")) { css.setContent(item.getString("UTF-8")); } else if (item.getFieldName().equals("css_active")) { css.setActive(true); } } } if (action.equals("edit")) { CssDAO.getInstance().update(css); // Activity log UserActivity.log(userId, "ADMIN_CSS_UPDATE", String.valueOf(css.getId()), null, css.getName()); } else if (action.equals("delete")) { String name = WebUtils.getString(request, "css_name"); CssDAO.getInstance().delete(css.getId()); // Activity log UserActivity.log(userId, "ADMIN_CSS_DELETE", String.valueOf(css.getId()), null, name); } else if (action.equals("create")) { long id = CssDAO.getInstance().create(css); // Activity log UserActivity.log(userId, "ADMIN_CSS_CREATE", String.valueOf(id), null, css.getName()); } } list(userId, request, response); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:ca.myewb.frame.PostParamWrapper.java
public PostParamWrapper(HttpServletRequest request) throws Exception { if (!FileUpload.isMultipartContent(request)) { return;//from w w w .jav a 2 s .c o m } DiskFileUpload upload = new DiskFileUpload(); upload.setRepositoryPath(Helpers.getUserFilesDir() + "/temp"); try { List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { stringParams.put(item.getFieldName(), item.getString()); allParams.put(item.getFieldName(), item); } else if (item.getSize() > 0) { fileParams.put(item.getFieldName(), item); allParams.put(item.getFieldName(), item); } } } catch (FileUploadException ex) { log.debug("The file upload exception returned the message: " + ex.getMessage()); // Usually means user cancelled upload and connection timed out. // Do nothing. } }
From source file:mitm.djigzo.web.pages.admin.JCEPolicyManager.java
@OnEvent(UploadEvents.UPLOAD_EXCEPTION) protected Object onUploadException(FileUploadException uploadException) { logger.error("Error uploading file", uploadException); uploadError = true;// w w w . j a v a 2s . c om uploadErrorMessage = uploadException.getMessage(); return JCEPolicyManager.class; }
From source file:filter.MultipartRequestFilter.java
/** * Parse the given HttpServletRequest. If the request is a multipart request, then all multipart * request items will be processed, else the request will be returned unchanged. During the * processing of all multipart request items, the name and value of each regular form field will * be added to the parameterMap of the HttpServletRequest. The name and File object of each form * file field will be added as attribute of the given HttpServletRequest. If a * FileUploadException has occurred when the file size has exceeded the maximum file size, then * the FileUploadException will be added as attribute value instead of the FileItem object. * @param request The HttpServletRequest to be checked and parsed as multipart request. * @return The parsed HttpServletRequest. * @throws ServletException If parsing of the given HttpServletRequest fails. *//*www .ja v a2 s .co m*/ @SuppressWarnings("unchecked") // ServletFileUpload#parseRequest() does not return generic type. private HttpServletRequest parseRequest(HttpServletRequest request) throws ServletException { // Check if the request is actually a multipart/form-data request. if (!ServletFileUpload.isMultipartContent(request)) { // If not, then return the request unchanged. return request; } // Prepare the multipart request items. // I'd rather call the "FileItem" class "MultipartItem" instead or so. What a stupid name ;) List<FileItem> multipartItems = null; try { // Parse the multipart request items. multipartItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); // Note: we could use ServletFileUpload#setFileSizeMax() here, but that would throw a // FileUploadException immediately without processing the other fields. So we're // checking the file size only if the items are already parsed. See processFileField(). } catch (FileUploadException e) { throw new ServletException("Cannot parse multipart request: " + e.getMessage()); } // Prepare the request parameter map. Map<String, String[]> parameterMap = new HashMap<String, String[]>(); // Loop through multipart request items. for (FileItem multipartItem : multipartItems) { if (multipartItem.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). processFormField(multipartItem, parameterMap); } else { // Process form file field (input type="file"). processFileField(multipartItem, request); } } // Wrap the request with the parameter map which we just created and return it. return wrapRequest(request, parameterMap); }
From source file:com.softwarementors.extjs.djn.router.processor.standard.form.upload.UploadFormPostRequestProcessor.java
public void handleFileUploadException(FileUploadException e) { assert e != null; com.softwarementors.extjs.djn.router.processor.standard.form.upload.FileUploadException ex = com.softwarementors.extjs.djn.router.processor.standard.form.upload.FileUploadException .forFileUploadException(e);//from w ww . j a v a 2 s.co m logger.error(ex.getMessage(), ex); throw ex; }
From source file:Controle.Controle_foto.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); ArrayList<Object> obj = new ArrayList<Object>(); Mensagem msg = new Mensagem(); Gson gson = new Gson(); PrintWriter out = response.getWriter(); Foto foto = new Foto(); FotoDAO fotoDAO = new FotoDAO(); System.out.println("teste"); if (isMultipart) { System.out.println("teste2"); FileItemFactory factory = new DiskFileItemFactory(); System.out.println("teste3"); ServletFileUpload upload = new ServletFileUpload(factory); try {//from www . j a va 2 s .co m System.out.println("teste4"); List itens = upload.parseRequest(request); Iterator iterator = itens.iterator(); String id = ""; String legenda = ""; id = request.getParameter("id"); // // if(id.equals("null")){ // System.out.println("sem id da foto"); // }else{ // System.out.println("com id da foto"); // } System.out.println("id da foto: " + request.getParameter("id")); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); if (!item.isFormField()) { String nomeArquivo = item.getName(); String extensao = ""; System.out.println(nomeArquivo); int cont = 4; for (int i = 0; i <= 3; i++) { extensao += nomeArquivo.charAt(nomeArquivo.length() - cont); cont = cont - 1; } Random rdm = new Random(); int n = rdm.nextInt(99999); nomeArquivo = id + n + extensao; System.out.println(nomeArquivo); String diretorio = getServletContext().getRealPath("/"); File destino = new File(diretorio + "/segura/img"); System.out.println(destino); //apagar arquivo antigo. foto = fotoDAO.buscarPorId(Integer.parseInt(id)); if (foto.getId() <= 0) { throw new Exception("Foto no encontrada!!!!"); } else { File arquivoAntigo = new File(diretorio + "/" + foto.getEndereco()); System.out.println("Endereo da imagem antiga !!!!!!!!!" + foto.getEndereco()); if (!foto.getEndereco().equals("segura/default/sem_foto.jpg")) { boolean bool = arquivoAntigo.delete(); System.out.println("arquivo apagado? " + bool); System.out.println("O seguinte arquivo antigo foi apagardo!!!!!!!!!" + arquivoAntigo.getAbsolutePath()); } foto.setEndereco("/segura/img/" + nomeArquivo); foto.setLegenda(legenda); fotoDAO.atualizar(foto); } // if (!destino.exists()) { // boolean status = destino.mkdirs(); // // } File arquivoRecebido = new File(destino + "/" + nomeArquivo); System.out.println(arquivoRecebido.getAbsolutePath()); item.write(arquivoRecebido); } else { if (!item.getFieldName().equals("legenda")) { id = item.getString(); } else { legenda = item.getString(); } System.out.println("Nome do campo !!!" + item.getFieldName()); System.out.println("Olha o valor do id !!!" + item.getString()); } } msg.setMensagem("Cadastrado com sucesso!!!!"); msg.setTipo(1); obj.add(msg); } catch (FileUploadException e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } catch (Exception e) { e.printStackTrace(); System.out.println("Erro!!" + e.getMessage()); msg.setMensagem("Erro!!" + e.getMessage()); msg.setTipo(2); obj.add(msg); } finally { out.printf(gson.toJson(obj)); } } else { System.out.println("deu ruim no multpart"); } }
From source file:com.qualogy.qafe.web.upload.DatagridUploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { byte[] filecontent = null; ServletFileUpload upload = new ServletFileUpload(); InputStream inputStream = null; ByteArrayOutputStream outputStream = null; boolean isFirstLineHeader = false; String delimiter = ","; writeUploadInfo(request);/* w ww . ja va2 s .co m*/ log(request.getHeader("User-Agent")); response.setContentType("text/html"); PrintWriter out = response.getWriter(); try { FileItemIterator fileItemIterator = upload.getItemIterator(request); while (fileItemIterator.hasNext()) { FileItemStream item = fileItemIterator.next(); inputStream = item.openStream(); // Read the file into a byte array. outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int len = 0; while (-1 != (len = inputStream.read(buffer))) { outputStream.write(buffer, 0, len); } if (filecontent == null) { filecontent = outputStream.toByteArray(); } if (FORM_PARAMETER_DELIMITER.equals(item.getFieldName())) { delimiter = outputStream.toString(); } else if (FORM_PARAMETER_ISFIRSTLINEHEADER.equals(item.getFieldName())) { if ("on".equals(outputStream.toString())) { isFirstLineHeader = true; } } } inputStream.close(); outputStream.close(); } catch (FileUploadException e) { ExceptionHelper.printStackTrace(e); } catch (RuntimeException e) { out.print("Conversion failed. Please check the file. Message :" + e.getMessage()); } DocumentParameter dp = new DocumentParameter(); dp.setDelimiter(delimiter); dp.setFirstFieldHeader(isFirstLineHeader); dp.setData(filecontent); try { DocumentOutput dout = documentService.processExcelUpload(dp); String uploadUUID = DataStore.KEY_LOOKUP_DATA + dout.getUuid(); ApplicationLocalStore.getInstance().store(uploadUUID, uploadUUID, dout.getData()); out.print("UUID=" + uploadUUID); } catch (Exception e) { out.print("Conversion failed. Please check the file (" + e.getMessage() + ")"); } }
From source file:com.carolinarollergirls.scoreboard.jetty.MediaServlet.java
protected void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w .ja v a 2 s .c o m*/ if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(response.SC_BAD_REQUEST); return; } String media = null, type = null; FileItemFactory fiF = new DiskFileItemFactory(); ServletFileUpload sfU = new ServletFileUpload(fiF); List<FileItem> fileItems = new LinkedList<FileItem>(); Iterator i = sfU.parseRequest(request).iterator(); while (i.hasNext()) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("media")) media = item.getString(); else if (item.getFieldName().equals("type")) type = item.getString(); } else if (item.getName().matches(zipExtRegex)) { processZipFileItem(fiF, item, fileItems); } else if (uploadFileNameFilter.accept(null, item.getName())) { fileItems.add(item); } } if (fileItems.size() == 0) { setTextResponse(response, response.SC_BAD_REQUEST, "No files provided to upload"); return; } processFileItemList(fileItems, media, type); int len = fileItems.size(); setTextResponse(response, response.SC_OK, "Successfully uploaded " + len + " file" + (len > 1 ? "s" : "")); } catch (FileNotFoundException fnfE) { setTextResponse(response, response.SC_NOT_FOUND, fnfE.getMessage()); } catch (IllegalArgumentException iaE) { setTextResponse(response, response.SC_BAD_REQUEST, iaE.getMessage()); } catch (FileUploadException fuE) { setTextResponse(response, response.SC_INTERNAL_SERVER_ERROR, fuE.getMessage()); } }
From source file:controlador.SerCandidato.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //ruta relativa en donde se guardan las fotos de candidatos String ruta = getServletContext().getRealPath("/") + "images/files/candidatos/"; //Partido p = new Partido(); Candidato c = new Candidato(); int accion = 1; //1=gregar 2=modificar if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(40960); File repositoryPath = new File("/temp"); diskFileItemFactory.setRepository(repositoryPath); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); servletFileUpload.setSizeMax(81920); // bytes upload.setSizeMax(307200); // 1024 x 300 = 307200 bytes = 300 Kb List listUploadFiles = null; FileItem item = null;//from www. j a va 2 s. c om try { listUploadFiles = upload.parseRequest(request); Iterator it = listUploadFiles.iterator(); while (it.hasNext()) { item = (FileItem) it.next(); if (!item.isFormField()) { if (item.getSize() > 0) { String nombre = item.getName(); String tipo = item.getContentType(); long tamanio = item.getSize(); String extension = nombre.substring(nombre.lastIndexOf(".")); File archivo = new File(ruta, nombre); item.write(archivo); if (archivo.exists()) { c.setFoto(nombre); } else { out.println("FALLO AL GUARDAR. NO EXISTE " + archivo.getAbsolutePath() + "</p>"); } } } else { //se reciben los campos de texto enviados y se igualan a los atributos del objeto if (item.getFieldName().equals("slPartido")) { c.setIdPartido(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("slDepartamento")) { c.setIdDepartamento(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("txtDui")) { c.setNumDui(item.getString()); } if (item.getFieldName().equals("txtId")) { c.setIdCandidato(Integer.parseInt(item.getString())); } if (item.getFieldName().equals("txtTipo")) { //definimos que el candidato es tipo 1 (Partidario) c.setTipo(Integer.parseInt(item.getString())); } } } //si no se selecciono una imagen distinta, se conserva la imagen anterior if (c.getFoto() == null) { c.setFoto(CandidatoDTO.mostrarCandidato(c.getIdCandidato()).getFoto()); } //cuando se presiona el boton de agregar if (c.getIdCandidato() == 0) { if (CandidatoDTO.agregarCandidato(c)) { //candidato partidario = 1 //candidato independiente = 2 if (c.getTipo() == 1) { //crud de canidatos partidadios response.sendRedirect(this.redireccionJSP); } else { //crud de canidatos independientes response.sendRedirect(this.redireccionJSP2); } } else { //cambiar por alguna accion en caso de error out.print("Error al insertar"); } } //cuando se presiona el boton de modificar else { if (CandidatoDTO.modificarCandidato(c)) { if (c.getTipo() == 1) { //crud de canidatos partidadios response.sendRedirect(this.redireccionJSP); } else { //crud de canidatos independientes response.sendRedirect(this.redireccionJSP2); } } else { out.print("Error al modificar"); } } } catch (FileUploadException e) { out.println("Error Upload: " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { out.println("Error otros: " + e.getMessage()); e.printStackTrace(); } } }