List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload getItemIterator
public FileItemIterator getItemIterator(HttpServletRequest request) throws FileUploadException, IOException
From source file:org.daxplore.presenter.server.servlets.AdminUploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { try {/*from www . j a va 2s .co m*/ long time = System.nanoTime(); int statusCode = HttpServletResponse.SC_OK; response.setContentType("text/html; charset=UTF-8"); ServletFileUpload upload = new ServletFileUpload(); PersistenceManager pm = null; String prefix = null; try { FileItemIterator fileIterator = upload.getItemIterator(request); String fileName = ""; byte[] fileData = null; while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { if (item.getFieldName().equals("prefix")) { prefix = Streams.asString(stream); } else { throw new BadRequestException("Form contains extra fields"); } } else { fileName = item.getName(); fileData = IOUtils.toByteArray(stream); } } } if (SharedResourceTools.isSyntacticallyValidPrefix(prefix)) { if (fileData != null && !fileName.equals("")) { pm = PMF.get().getPersistenceManager(); unzipAll(pm, prefix, fileData); } else { throw new BadRequestException("No file uploaded"); } } else { throw new BadRequestException("Request made with invalid prefix: '" + prefix + "'"); } logger.log(Level.INFO, "Unpacked new data for prefix '" + prefix + "' in " + ((System.nanoTime() - time) / 1000000000.0) + " seconds"); } catch (FileUploadException | IOException | BadRequestException e) { logger.log(Level.WARNING, e.getMessage(), e); statusCode = HttpServletResponse.SC_BAD_REQUEST; } catch (InternalServerException e) { logger.log(Level.SEVERE, e.getMessage(), e); statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } catch (DeadlineExceededException e) { logger.log(Level.SEVERE, "Timeout when uploading new data for prefix '" + prefix + "'", e); // the server is currently unavailable because it is overloaded (hopefully) statusCode = HttpServletResponse.SC_SERVICE_UNAVAILABLE; } finally { if (pm != null) { pm.close(); } } response.setStatus(statusCode); try (PrintWriter resWriter = response.getWriter()) { if (resWriter != null) { resWriter.write(Integer.toString(statusCode)); resWriter.close(); } } } catch (IOException | RuntimeException e) { logger.log(Level.SEVERE, "Unexpected exception: " + e.getMessage(), e); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.dspace.rest.providers.AbstractBaseProvider.java
public Object translateFormattedData(EntityReference ref, String format, InputStream input, Map<String, Object> params) { String IS = ""; if (format.equals("xml") || format.equals("json")) { try {/*from w w w . j a va 2 s . c om*/ IS = readIStoString(input); // System.out.println("is+= " + IS); } catch (IOException ex) { ex.printStackTrace(); } } Map<String, Object> decodedInput = null; EntityEncodingManager em = new EntityEncodingManager(null, null); if (format.equals("xml")) { decodedInput = em.decodeData(IS, Formats.XML); } else if (format.equals("json")) { decodedInput = em.decodeData(IS, Formats.JSON); } else if (format.equals("stream")) { try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(requestGetter.getRequest()); while (iter.hasNext()) { FileItemStream item = iter.next(); return item.openStream(); } } catch (Exception e) { e.printStackTrace(); } } System.out.println("== translate formated data called"); System.out.println("got: \n" + IS + "\ndecoded " + decodedInput); return decodedInput; }
From source file:org.duracloud.common.rest.RestUtilImpl.java
/** * Retrieves the contents of the HTTP Request. * * @return InputStream from the request//from w w w . ja v a2s . c o m */ @Override public RequestContent getRequestContent(HttpServletRequest request, HttpHeaders headers) throws Exception { RequestContent rContent = null; // See if the request is a multi-part file upload request if (ServletFileUpload.isMultipartContent(request)) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request, use the first available File item FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { rContent = new RequestContent(); rContent.contentStream = item.openStream(); rContent.mimeType = item.getContentType(); FileItemHeaders itemHeaders = item.getHeaders(); if (itemHeaders != null) { String contentLength = itemHeaders.getHeader("Content-Length"); if (contentLength != null) { rContent.size = Long.parseLong(contentLength); } } break; } } } else { // If the content stream was not found as a multipart, // try to use the stream from the request directly rContent = new RequestContent(); rContent.contentStream = request.getInputStream(); if (request.getContentLength() >= 0) { rContent.size = request.getContentLength(); } } // Attempt to set the mime type and size if not already set if (rContent != null) { if (rContent.mimeType == null) { MediaType mediaType = headers.getMediaType(); if (mediaType != null) { rContent.mimeType = mediaType.toString(); } } if (rContent.size == 0) { List<String> lengthHeaders = headers.getRequestHeader("Content-Length"); if (lengthHeaders != null && lengthHeaders.size() > 0) { rContent.size = Long.parseLong(lengthHeaders.get(0)); } } } return rContent; }
From source file:org.duracloud.duradmin.spaces.controller.ContentItemUploadController.java
@RequestMapping(value = "/spaces/content/upload", method = RequestMethod.POST) public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { try {//w ww . ja v a 2 s . c o m log.debug("handling request..."); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); String spaceId = null; String storeId = null; String contentId = null; List<ContentItem> results = new ArrayList<ContentItem>(); while (iter.hasNext()) { FileItemStream item = iter.next(); if (item.isFormField()) { String value = Streams.asString(item.openStream(), "UTF-8"); if (item.getFieldName().equals("spaceId")) { log.debug("setting spaceId: {}", value); spaceId = value; } else if (item.getFieldName().equals("storeId")) { storeId = value; } else if (item.getFieldName().equals("contentId")) { contentId = value; } } else { log.debug("setting fileStream: {}", item); if (StringUtils.isBlank(spaceId)) { throw new IllegalArgumentException("space id required."); } ContentItem ci = new ContentItem(); if (StringUtils.isBlank(contentId)) { contentId = item.getName(); } ci.setContentId(contentId); ci.setSpaceId(spaceId); ci.setStoreId(storeId); ci.setContentMimetype(item.getContentType()); ContentStore contentStore = contentStoreManager.getContentStore(ci.getStoreId()); ContentItemUploadTask task = new ContentItemUploadTask(ci, contentStore, item.openStream(), request.getUserPrincipal().getName()); task.execute(); ContentItem result = new ContentItem(); Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication(); SpaceUtil.populateContentItem(ContentItemController.getBaseURL(request), result, ci.getSpaceId(), ci.getContentId(), contentStore, auth); results.add(result); contentId = null; } } return new ModelAndView("javascriptJsonView", "results", results); } catch (Exception ex) { ex.printStackTrace(); throw ex; } }
From source file:org.ebayopensource.turmeric.policy.adminui.server.PlcImportServlet.java
/** * Parses the input stream./*from w w w . j a v a 2s . c o m*/ * * @param request * the request * @param response * the response * @return the byte array output stream * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ public ByteArrayOutputStream parseInputStream(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletFileUpload upload = new ServletFileUpload(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream stream = item.openStream(); // Process the input stream int len; byte[] buffer = new byte[8192]; while ((len = stream.read(buffer, 0, buffer.length)) != -1) { out.write(buffer, 0, len); } int maxFileSize = 10 * (1024 * 1024); // 10 megs max if (out.size() > maxFileSize) { response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Max allowed file size: 10 Mb"); } } } catch (Exception e) { e.printStackTrace(); } return out; }
From source file:org.eclipse.rap.addons.fileupload.internal.FileUploadProcessor.java
void handleFileUpload(HttpServletRequest request, HttpServletResponse response) throws IOException { try {//from www . j a va 2 s. c om ServletFileUpload upload = createUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); if (!item.isFormField()) { receive(item); } } if (tracker.isEmpty()) { String errorMessage = "No file upload data found in request"; tracker.setException(new Exception(errorMessage)); tracker.handleFailed(); response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMessage); } else { tracker.handleFinished(); } } catch (Exception exception) { Throwable cause = exception.getCause(); if (cause instanceof FileSizeLimitExceededException) { exception = (Exception) cause; } tracker.setException(exception); tracker.handleFailed(); int errorCode = exception instanceof FileSizeLimitExceededException ? HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.sendError(errorCode, exception.getMessage()); } }
From source file:org.eclipse.rdf4j.workbench.util.WorkbenchRequest.java
private Map<String, String> getMultipartParameterMap() throws RepositoryException, IOException, FileUploadException { Map<String, String> parameters = new HashMap<String, String>(); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(this); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if ("content".equals(name)) { content = item.openStream(); contentFileName = item.getName(); break; } else {//w ww . j a v a 2 s. c o m parameters.put(name, firstLine(item)); } } return parameters; }
From source file:org.eclipse.scout.rt.ui.html.json.UploadRequestHandler.java
protected void readUploadData(HttpServletRequest httpReq, long maxSize, Map<String, String> uploadProperties, List<BinaryResource> uploadResources) throws FileUploadException, IOException { ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); upload.setSizeMax(maxSize);/* w ww. j a va 2 s. c o m*/ for (FileItemIterator it = upload.getItemIterator(httpReq); it.hasNext();) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // Handle non-file fields (interpreted as properties) uploadProperties.put(name, Streams.asString(stream, StandardCharsets.UTF_8.name())); } else { // Handle files String filename = item.getName(); if (StringUtility.hasText(filename)) { String[] parts = StringUtility.split(filename, "[/\\\\]"); filename = parts[parts.length - 1]; } String contentType = item.getContentType(); byte[] content = IOUtility.getContent(stream); // Info: we cannot set the charset property for uploaded files here, because we simply don't know it. // the only thing we could do is to guess the charset (encoding) by reading the byte contents of // uploaded text files (for binary file types the encoding is not relevant). However: currently we // do not set the charset at all. uploadResources.add(new BinaryResource(filename, contentType, content)); } } }
From source file:org.ejbca.ui.web.HttpUpload.java
/** * Creates a new upload state and receives all file and parameter data. * This constructor can only be called once per request. * /*from w w w.java 2s . c o m*/ * Use getParameterMap() and getFileMap() on the new object to access the data. * * @param request The servlet request object. * @param fileFields The names of the file fields to receive uploaded data from. * @param maxbytes Maximum file size. * @throws IOException if there are network problems, etc. * @throws FileUploadException if the request is invalid. */ @SuppressWarnings("unchecked") // Needed in some environments, and detected as unnecessary in others. Do not remove! public HttpUpload(HttpServletRequest request, String[] fileFields, int maxbytes) throws IOException, FileUploadException { if (ServletFileUpload.isMultipartContent(request)) { final Map<String, ArrayList<String>> paramTemp = new HashMap<String, ArrayList<String>>(); fileMap = new HashMap<String, byte[]>(); final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); final String name = item.getFieldName(); if (item.isFormField()) { ArrayList<String> values = paramTemp.get(name); if (values == null) { values = new ArrayList<String>(); paramTemp.put(name, values); } values.add(Streams.asString(item.openStream(), request.getCharacterEncoding())); } else if (ArrayUtils.contains(fileFields, name)) { byte[] data = getFileBytes(item, maxbytes); if (data != null && data.length > 0) { fileMap.put(name, data); } } } // Convert to String,String[] map parameterMap = new ParameterMap(); for (Entry<String, ArrayList<String>> entry : paramTemp.entrySet()) { final ArrayList<String> values = entry.getValue(); final String[] valuesArray = new String[values.size()]; parameterMap.put(entry.getKey(), values.toArray(valuesArray)); } } else { parameterMap = new ParameterMap(request.getParameterMap()); fileMap = new HashMap<String, byte[]>(); } }
From source file:org.elfinder.servlets.AbstractConnectorServlet.java
/** * Parse request parameters and files./*from ww w . ja v a2s .c om*/ * @param request * @param response */ protected void parseRequest(HttpServletRequest request, HttpServletResponse response) { requestParams = new HashMap<String, Object>(); listFiles = new ArrayList<FileItemStream>(); listFileStreams = new ArrayList<ByteArrayOutputStream>(); // Parse the request if (ServletFileUpload.isMultipartContent(request)) { // multipart request try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { listFiles.add(item); ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); listFileStreams.add(os); } } } } catch (Exception e) { logger.error("Unexpected error parsing multipart content", e); } } else { // not a multipart for (Object mapKey : request.getParameterMap().keySet()) { String mapKeyString = (String) mapKey; if (mapKeyString.endsWith("[]")) { // multiple values String values[] = request.getParameterValues(mapKeyString); List<String> listeValues = new ArrayList<String>(); for (String value : values) { listeValues.add(value); } requestParams.put(mapKeyString, listeValues); } else { // single value String value = request.getParameter(mapKeyString); requestParams.put(mapKeyString, value); } } } }