List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
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 .jav a 2s . 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:fr.paris.lutece.portal.web.upload.UploadServlet.java
/** * {@inheritDoc}//from w w w . ja v a2 s. com */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { MultipartHttpServletRequest request = (MultipartHttpServletRequest) req; List<FileItem> listFileItems = new ArrayList<FileItem>(); JSONObject json = new JSONObject(); json.element(JSON_FILES, new JSONArray()); for (Entry<String, FileItem> entry : ((Map<String, FileItem>) request.getFileMap()).entrySet()) { FileItem fileItem = entry.getValue(); JSONObject jsonFile = new JSONObject(); jsonFile.element(JSON_FILE_NAME, fileItem.getName()); jsonFile.element(JSON_FILE_SIZE, fileItem.getSize()); // add to existing array json.accumulate(JSON_FILES, jsonFile); listFileItems.add(fileItem); } IAsynchronousUploadHandler handler = getHandler(request); if (handler == null) { AppLogService.error("No handler found, removing temporary files"); for (FileItem fileItem : listFileItems) { fileItem.delete(); } } else { handler.process(request, response, json, listFileItems); } if (AppLogService.isDebugEnabled()) { AppLogService.debug("Aysnchronous upload : " + json.toString()); } response.getOutputStream().print(json.toString()); }
From source file:com.uniquesoft.uidl.servlet.UploadServlet.java
/** * Delete an uploaded file./* ww w.j a va 2 s . c om*/ * * @param request * @param response * @return FileItem * @throws IOException */ protected static FileItem removeUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException { String parameter = request.getParameter(UConsts.PARAM_REMOVE); FileItem item = findFileItem(getSessionFileItems(request), parameter); if (item != null) { getSessionFileItems(request).remove(item); logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter + " " + item.getName() + " " + item.getSize()); } else { logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") removeUploadedFile: " + parameter + " not in session."); } renderXmlResponse(request, response, XML_DELETED_TRUE); return item; }
From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java
private File doUploadPrivateKey(final List<FileItem> items, final String sshHostname) throws IOException { File privateKeyPath = null;//from ww w .j av a2 s .co m for (FileItem item : items) { if (item.getFieldName().equals(GerritConfiguration.FIELD_SSH_PRIVATE_KEY) && item.getSize() > 0) { File dataDir = new File(jiraHome.getDataDirectory(), StringUtils.join(PACKAGE_PARTS, File.separatorChar)); if (!dataDir.exists()) { dataDir.mkdirs(); } String tempFilePrefix = configurationManager.getSshHostname(); String tempFileSuffix = ".key"; try { privateKeyPath = File.createTempFile(tempFilePrefix, tempFileSuffix, dataDir); } catch (IOException e) { log.info("---- Cannot create temporary file: " + e.getMessage() + ": " + dataDir.toString() + tempFilePrefix + tempFileSuffix + " ----"); break; } privateKeyPath.setReadable(false, false); privateKeyPath.setReadable(true, true); InputStream is = item.getInputStream(); FileOutputStream fos = new FileOutputStream(privateKeyPath); IOUtils.copy(is, fos); IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); item.delete(); break; } } return privateKeyPath; }
From source file:com.arcbees.bourseje.server.upload.Upload.java
@Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { FileItem fileItem = sessionFiles.get(0); InputStream inputStream;/* ww w. jav a2 s . c om*/ try { inputStream = fileItem.getInputStream(); } catch (IOException e) { throw new RuntimeException(e); } String servingUrl = imageUploadService.upload(fileItem.getName(), inputStream, fileItem.getSize()); removeSessionFileItems(request); return servingUrl; }
From source file:com.siberhus.web.ckeditor.servlet.BaseActionServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String requestURI = request.getRequestURI(); if (requestURI != null && requestURI.lastIndexOf("/") != -1) { String actionName = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length()); int paramIdx = actionName.indexOf("?"); if (paramIdx != -1) { actionName = actionName.substring(0, actionName.indexOf("?")); }//w w w . ja v a 2 s . c o m Method method = null; try { method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class); } catch (Exception e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_NOT_FOUND, "Action=" + actionName + " not found for servlet=" + this.getClass()); return; } try { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { request = new MultipartServletRequest(request); log.debug("Files *********************"); MultipartServletRequest mrequest = (MultipartServletRequest) request; for (FileItem fileItem : mrequest.getFileItems()) { log.debug("File[fieldName={}, fileName={}, fileSize={}]", new Object[] { fileItem.getFieldName(), fileItem.getName(), fileItem.getSize() }); } } if (log.isDebugEnabled()) { log.debug("Parameters **************************"); Enumeration<String> paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = paramNames.nextElement(); log.debug("Param[name={},value(s)={}]", new Object[] { paramName, Arrays.toString(request.getParameterValues(paramName)) }); } } Object result = method.invoke(this, request, response); if (result instanceof StreamingResult) { if (!response.isCommitted()) { ((StreamingResult) result).execute(request, response); } } } catch (Exception e) { e.printStackTrace(); if (e instanceof InvocationTargetException) { throw new ServletException(((InvocationTargetException) e).getTargetException()); } throw new ServletException(e); } } }
From source file:com.sa.osgi.jetty.UploadServlet.java
private void processUploadedFile(FileItem item) { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); System.out.println("file name: " + fileName); try {// w w w . j av a 2 s .com // InputStream inputStream = item.getInputStream(); // FileOutputStream fout = new FileOutputStream("/tmp/aa"); // fout.write(inputStream.rea); String newFileName = "/tmp/" + fileName; item.write(new File(newFileName)); ServiceFactory factory = ServiceFactory.INSTANCE; MaoService maoService = factory.getMaoService(); boolean b = maoService.installBundle(newFileName); System.out.println("Installation Result: " + b); } catch (IOException ex) { Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:br.com.caelum.vraptor.interceptor.multipart.CommonsUploadMultipartInterceptor.java
protected void processFile(FileItem item, String name) { try {/*w w w . j a va 2 s. c o m*/ UploadedFile upload = new DefaultUploadedFile(item.getInputStream(), item.getName(), item.getContentType(), item.getSize()); parameters.setParameter(name, name); request.setAttribute(name, upload); logger.debug("Uploaded file: {} with {}", name, upload); } catch (IOException e) { throw new InvalidParameterException("Cant parse uploaded file " + item.getName(), e); } }
From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java
/** * Do the effective upload of files./* ww w . jav a2 s . c om*/ * * @param session the HttpSession * @param request the multpart request * @throws IOException */ @SuppressWarnings("unchecked") private void doFileUpload(HttpSession session, HttpServletRequest request) throws IOException { try { session.setAttribute(UPLOAD_ERRORS, ""); session.setAttribute(UPLOAD_FATAL_ERROR, ""); List<String> paths = new ArrayList<String>(); session.setAttribute(FILE_UPLOAD_PATHS, paths); FileUploadListener listener = new FileUploadListener(request.getContentLength()); session.setAttribute(FILE_UPLOAD_STATS, listener.getFileUploadStats()); FileItemFactory factory = new MonitoringFileItemFactory(listener); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = (List<FileItem>) upload.parseRequest(request); startingToSaveUploadedFile(session); String errorMessage = ""; for (FileItem fileItem : items) { if (!fileItem.isFormField() && fileItem.getSize() > 0L) { try { String filename = fileItem.getName(); if (filename.indexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.indexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (!isInWhiteList(filename)) { errorMessage += "The file " + filename + " is not uploaded!"; errorMessage += (StringUtil.isDefined(whiteList) ? " Only " + whiteList.replaceAll(" ", ", ") + " file types can be uploaded<br/>" : " No allowed file format has been defined for upload<br/>"); session.setAttribute(UPLOAD_ERRORS, errorMessage); } else { filename = System.currentTimeMillis() + "-" + filename; File targetDirectory = new File(uploadDir, fileItem.getFieldName()); targetDirectory.mkdirs(); File uploadedFile = new File(targetDirectory, filename); OutputStream out = null; try { out = new FileOutputStream(uploadedFile); IOUtils.copy(fileItem.getInputStream(), out); paths.add(uploadedFile.getParentFile().getName() + '/' + uploadedFile.getName()); } finally { IOUtils.closeQuietly(out); } } } finally { fileItem.delete(); } } } } catch (Exception e) { Logger.getLogger(getClass().getSimpleName()).log(Level.WARNING, e.getMessage()); session.setAttribute(UPLOAD_FATAL_ERROR, "Could not process uploaded file. Please see log for details."); } finally { endingToSaveUploadedFile(session); } }
From source file:de.knurt.fam.core.model.config.FileUploadController.java
private void setError(List<FileItem> items) { long size_sum = 0; if (items.size() > this.getExistingFileNames().length + MAX_NUMBER_OF_FILES) { this.error = "maxNumberOfFiles"; } else {// w w w .j a va 2s. co m for (FileItem item : items) { size_sum += item.getSize(); if (item.getSize() > MAX_FILE_SIZE) { this.error = "maxFileSize"; break; } if (item.getSize() < MIN_FILE_SIZE) { this.error = "minFileSize"; break; } boolean acceptedFileType = false; for (String suffix : ACCEPT_FILE_TYPES) { if (item.getName().endsWith(suffix)) { acceptedFileType = true; break; } } if (!acceptedFileType) { this.error = "acceptFileTypes"; } } } if (this.error == null && this.getSizeOfAllFiles() + size_sum > MAX_FILE_SIZE_SUM) { this.error = "maxFileSize"; } }