List of usage examples for org.apache.commons.fileupload FileUploadException getMessage
public String getMessage()
From source file:my.mavenproject10.FileuploadController.java
@RequestMapping(method = RequestMethod.POST) ModelAndView upload(HttpServletRequest request, HttpServletResponse response) { boolean isMultipart = ServletFileUpload.isMultipartContent(request); String fileName = ""; int size = 0; ArrayList<String> result = new ArrayList<String>(); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try {/*from w ww .j a va 2 s . c o m*/ List items = upload.parseRequest(request); Iterator iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); fileName = item.getName(); System.out.println("file name " + item.getName()); JAXBContext jc = JAXBContext.newInstance(CustomersType.class); SAXParserFactory spf = SAXParserFactory.newInstance(); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource( new InputStreamReader(item.getInputStream(), "UTF-8")); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller unmarshaller = jc.createUnmarshaller(); CustomersType data2 = (CustomersType) unmarshaller.unmarshal(source); //System.out.println("size " + data2.getCustomer().size()); size = data2.getCustomer().size(); for (CustomerType customer : data2.getCustomer()) { System.out.println(customer.toString()); } // double summ = 0.0; HashMap<Integer, Float> ordersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { for (OrderType orderType : customer.getOrders().getOrder()) { Float summPerOrder = 0.0f; //System.out.println(orderType); for (PositionType positionType : orderType.getPositions().getPosition()) { //System.out.println(positionType); summPerOrder += positionType.getCount() * positionType.getPrice(); summ += positionType.getCount() * positionType.getPrice(); } ordersMap.put(orderType.getId(), summPerOrder); } } summ = new BigDecimal(summ).setScale(2, RoundingMode.UP).doubleValue(); System.out.println(" " + summ); result.add(" " + summ); // HashMap<Integer, Float> customersMap = new HashMap<Integer, Float>(); for (CustomerType customer : data2.getCustomer()) { Float summPerCust = 0.0f; customersMap.put(customer.getId(), summPerCust); for (OrderType orderType : customer.getOrders().getOrder()) { for (PositionType positionType : orderType.getPositions().getPosition()) { summPerCust += positionType.getCount() * positionType.getPrice(); } } //System.out.println(customer.getId() + " orders " + summPerCust); customersMap.put(customer.getId(), summPerCust); } TreeMap sortedMap = sortByValue(customersMap); System.out.println(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); result.add(" " + sortedMap.keySet().toArray()[0] + " : " + sortedMap.get(sortedMap.firstKey())); // TreeMap sortedMapOrders = sortByValue(ordersMap); System.out.println(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); result.add(" " + sortedMapOrders.keySet().toArray()[0] + " : " + sortedMapOrders.get(sortedMapOrders.firstKey())); // System.out.println(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); result.add(" " + sortedMapOrders.keySet().toArray()[sortedMapOrders.keySet().toArray().length - 1] + " : " + sortedMapOrders.get(sortedMapOrders.lastKey())); // System.out.println(" " + sortedMapOrders.size()); result.add(" " + sortedMapOrders.size()); // ArrayList<Float> floats = new ArrayList<Float>(sortedMapOrders.values()); Float summAvg = 0.0f; Float avg = 0.0f; for (Float f : floats) { summAvg += f; } avg = new BigDecimal(summAvg / floats.size()).setScale(2, RoundingMode.UP).floatValue(); System.out.println(" " + avg); result.add(" " + avg); } } catch (FileUploadException e) { System.out.println("FileUploadException:- " + e.getMessage()); } catch (JAXBException ex) { //Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedEncodingException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } catch (SAXException ex) { Logger.getLogger(FileuploadController.class.getName()).log(Level.SEVERE, null, ex); } } ModelAndView modelAndView = new ModelAndView("fileuploadsuccess"); modelAndView.addObject("files", result); modelAndView.addObject("name", fileName); modelAndView.addObject("size", size); return modelAndView; }
From source file:mitm.djigzo.web.pages.admin.backup.BackupManager.java
@OnEvent(UploadEvents.UPLOAD_EXCEPTION) protected Object onUploadException(FileUploadException uploadException) { restoreBackup = true;/*from w w w. ja v a 2s . c o m*/ failureMessage = uploadException.getMessage(); return this; }
From source file:com.app.framework.web.MultipartFilter.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./* w w w .j a va 2 s . c o m*/ * * @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. */ @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. // Wrap the request with the parameter map which we just created and return it. 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:fr.gael.dhus.server.http.webapp.api.controller.UploadController.java
@PreAuthorize("hasRole('ROLE_UPLOAD')") @RequestMapping(value = "/upload", method = { RequestMethod.POST }) public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // 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 try {/*from w w w . j a v a 2 s .c o m*/ ArrayList<String> collectionIds = new ArrayList<>(); FileItem product = null; List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (COLLECTIONSKEY.equals(item.getFieldName())) { if (item.getString() != null && !item.getString().isEmpty()) { for (String cid : item.getString().split(",")) { collectionIds.add(cid); } } } else if (PRODUCTKEY.equals(item.getFieldName())) { product = item; } } if (product == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your request is missing a product file to upload."); return; } productUploadService.upload(product, collectionIds); res.setStatus(HttpServletResponse.SC_CREATED); res.getWriter().print("The file was created successfully."); res.flushBuffer(); } catch (FileUploadException e) { LOGGER.error("An error occurred while parsing request.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while parsing request : " + e.getMessage()); } catch (UserNotExistingException e) { LOGGER.error("You need to be connected to upload a product.", e); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product."); } catch (UploadingException e) { LOGGER.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (RootNotModifiableException e) { LOGGER.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (ProductNotAddedException e) { LOGGER.error("Your product can not be read by the system.", e); res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system."); } } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:fr.gael.dhus.api.UploadController.java
@SuppressWarnings("unchecked") @PreAuthorize("hasRole('ROLE_UPLOAD')") @RequestMapping(value = "/upload", method = { RequestMethod.POST }) public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); // 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 try {/*from w w w .j av a 2s . c o m*/ ArrayList<Long> collectionIds = new ArrayList<>(); FileItem product = null; List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (COLLECTIONSKEY.equals(item.getFieldName())) { if (item.getString() != null && !item.getString().isEmpty()) { for (String cid : item.getString().split(",")) { collectionIds.add(new Long(cid)); } } } else if (PRODUCTKEY.equals(item.getFieldName())) { product = item; } } if (product == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your request is missing a product file to upload."); return; } productUploadService.upload(user.getId(), product, collectionIds); res.setStatus(HttpServletResponse.SC_CREATED); res.getWriter().print("The file was created successfully."); res.flushBuffer(); } catch (FileUploadException e) { logger.error("An error occurred while parsing request.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while parsing request : " + e.getMessage()); } catch (UserNotExistingException e) { logger.error("You need to be connected to upload a product.", e); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product."); } catch (UploadingException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (RootNotModifiableException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (ProductNotAddedException e) { logger.error("Your product can not be read by the system.", e); res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system."); } } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:bijian.util.upload.MyMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's * multipart classes (see class description). * * @param saveDir the directory to save off the file * @param request the request containing the multipart * @throws java.io.IOException is thrown if encoding fails. *//*from w w w. ja v a2s. c o m*/ public void parse(HttpServletRequest request, String saveDir) throws IOException { try { processUpload(request, saveDir); } catch (FileUploadException e) { LOG.warn("Unable to parse request", e); errors.add(e.getMessage()); } }
From source file:at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet.java
/** * Gets the signer certificate from the InfoboxReadRequest and * responds with a new /* www. j a v a 2s .c o m*/ * <code>CreateXMLSignatureRequest</code>. * <br> * Request parameters: * <ul> * <li>MOASessionID: ID of associated authentication session</li> * <li>XMLResponse: <code><InfoboxReadResponse></code></li> * </ul> * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("POST VerifyCertificateServlet"); Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); String pendingRequestID = null; Map<String, String> parameters; try { parameters = getParameters(req); } catch (FileUploadException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); throw new IOException(e.getMessage()); } String sessionID = req.getParameter(PARAM_SESSIONID); // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); AuthenticationSession session = null; try { // check parameter if (!ParamValidatorUtils.isValidSessionID(sessionID)) throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); session = AuthenticationServer.getSession(sessionID); //change MOASessionID sessionID = AuthenticationSessionStoreage.changeSessionID(session); X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters); if (cert == null) { Logger.error("Certificate could not be read."); throw new AuthenticationException("auth.14", null); } boolean useMandate = session.getUseMandate(); if (useMandate) { // verify certificate for OrganWalter String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() .verifyCertificate(session, cert); try { AuthenticationSessionStoreage.storeSession(session); } catch (MOADatabaseException e) { throw new MOAIDException("session store error", null); } ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); } else { String countrycode = CertificateUtils.getIssuerCountry(cert); if (countrycode != null) { if (countrycode.compareToIgnoreCase("AT") == 0) { Logger.error( "Certificate issuer country code is \"AT\". Login not support in foreign identities mode."); throw new AuthenticationException("auth.22", null); } } // Foreign Identities Modus String createXMLSignatureRequest = AuthenticationServer.getInstance() .createXMLSignatureRequestForeignID(session, cert); // build dataurl (to the GetForeignIDSerlvet) String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_GET_FOREIGN_ID, session.getSessionID()); try { AuthenticationSessionStoreage.storeSession(session); } catch (MOADatabaseException e) { throw new MOAIDException("session store error", null); } ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); Logger.debug("Send CreateXMLSignatureRequest to BKU"); } } catch (MOAIDException ex) { handleError(null, ex, req, resp, pendingRequestID); } catch (Exception e) { Logger.error("CertificateValidation has an interal Error.", e); } finally { ConfigurationDBUtils.closeSession(); } }
From source file:mitm.djigzo.web.pages.crl.CRLImport.java
@OnEvent(UploadEvents.UPLOAD_EXCEPTION) protected Object onUploadException(FileUploadException uploadException) { logger.error("Error uploading file", uploadException); importError = true;//from ww w . ja v a2s . c o m importErrorMessage = uploadException.getMessage(); return CRLImport.class; }
From source file:com.glaf.base.utils.upload.FileUploadBackGroundServlet.java
/** * ?//w w w. j a va 2 s .c o m */ private void processFileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String serviceKey = request.getParameter("serviceKey"); if (serviceKey == null) { serviceKey = "global"; } int maxUploadSize = conf.getInt(serviceKey + ".maxUploadSize", 0); if (maxUploadSize == 0) { maxUploadSize = conf.getInt("upload.maxUploadSize", 10);// 10MB } maxUploadSize = maxUploadSize * FileUtils.MB_SIZE; DiskFileItemFactory factory = new DiskFileItemFactory(); // ? factory.setSizeThreshold(204800); File tempDir = new File(getUploadDir() + "/temp"); if (!tempDir.exists()) { tempDir.mkdir(); } // ? factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); // ? upload.setFileSizeMax(maxUploadSize); // request upload.setSizeMax(maxUploadSize); upload.setProgressListener(new FileUploadListener(request)); upload.setHeaderEncoding("UTF-8"); // ???FileUploadStatus Bean FileMgmtFactory.saveStatusBean(request, initStatusBean(request)); try { List<?> items = upload.parseRequest(request); // url for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { break; } } // String uploadDir = com.glaf.base.utils.StringUtil.createDir(getUploadDir()); // ? for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); // ? if (FileMgmtFactory.getStatusBean(request).getCancel()) { deleteUploadedFile(request); break; } else if (!item.isFormField() && item.getName().length() > 0) { logger.debug("" + item.getName()); // ? String fileId = UUID32.getUUID(); String path = uploadDir + FileUtils.sp + fileId; File uploadedFile = new File(new File(getUploadDir(), uploadDir), fileId); item.write(uploadedFile); // FileUploadStatus satusBean = FileMgmtFactory.getStatusBean(request); FileInfo fileInfo = new FileInfo(); fileInfo.setCreateDate(new Date()); fileInfo.setFileId(fileId); fileInfo.setFile(uploadedFile); fileInfo.setFilename(FileUtils.getFilename(item.getName())); fileInfo.setSize(item.getSize()); fileInfo.setPath(path); satusBean.getUploadFileUrlList().add(fileInfo); FileMgmtFactory.saveStatusBean(request, satusBean); Thread.sleep(500); } } } catch (FileUploadException ex) { uploadExceptionHandle(request, "?:" + ex.getMessage()); } catch (Exception ex) { uploadExceptionHandle(request, "??:" + ex.getMessage()); } String forwardURL = request.getParameter("forwardURL"); if (StringUtils.isEmpty(forwardURL)) { forwardURL = "/others/attachment.do?method=showResult"; } request.getRequestDispatcher(forwardURL).forward(request, response); }
From source file:com.example.webapp.filter.MultipartFilter.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./* www . j a v a2 s. co m*/ * * @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. */ @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); }