List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:org.chiba.adapter.web.HttpRequestHandler.java
/** * @param request Servlet request/*from w w w. j a va 2 s . c om*/ * @param trigger Trigger control * @return the calculated trigger * @throws XFormsException If an error occurs */ protected String processMultiPartRequest(HttpServletRequest request, String trigger) throws XFormsException { DiskFileUpload upload = new DiskFileUpload(); String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = "ISO-8859-1"; } upload.setRepositoryPath(this.uploadRoot); if (LOGGER.isDebugEnabled()) { LOGGER.debug("root dir for uploads: " + this.uploadRoot); } List items; try { items = upload.parseRequest(request); } catch (FileUploadException fue) { throw new XFormsException(fue); } Map formFields = new HashMap(); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String itemName = item.getName(); String fieldName = item.getFieldName(); String id = fieldName.substring(Config.getInstance().getProperty("chiba.web.dataPrefix").length()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Multipart item name is: " + itemName + " and fieldname is: " + fieldName + " and id is: " + id); LOGGER.debug("Is formfield: " + item.isFormField()); LOGGER.debug("Content: " + item.getString()); } if (item.isFormField()) { // check for upload-remove action if (fieldName.startsWith(getRemoveUploadPrefix())) { id = fieldName.substring(getRemoveUploadPrefix().length()); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, "", "", null); continue; } // It's a field name, it means that we got a non-file // form field. Upload is not required. We must treat it as we // do in processUrlencodedRequest() processMultipartParam(formFields, fieldName, item, encoding); } else { String uniqueFilename = new File(getUniqueParameterName("file"), new File(itemName).getName()) .getPath(); File savedFile = new File(this.uploadRoot, uniqueFilename); byte[] data = null; data = processMultiPartFile(item, id, savedFile, encoding, data); // if data is null, file will be removed ... // TODO: remove the file from the disk as well chibaBean.updateControlValue(id, item.getContentType(), itemName, data); } // handle regular fields if (formFields.size() > 0) { Iterator it = formFields.keySet().iterator(); while (it.hasNext()) { fieldName = (String) it.next(); String[] values = (String[]) formFields.get(fieldName); // [1] handle data handleData(fieldName, values); // [2] handle selector handleSelector(fieldName, values[0]); // [3] handle trigger trigger = handleTrigger(trigger, fieldName); } } } return trigger; }
From source file:org.chiba.agent.web.servlet.HttpRequestHandler.java
protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)"); }// www .ja v a2s .co m try { // update repeat indices Iterator iterator = uploads.keySet().iterator(); String id; FileItem item; byte[] data; while (iterator.hasNext()) { id = (String) iterator.next(); item = (FileItem) uploads.get(id); if (item.getSize() > 0) { LOGGER.debug("i'm here"); String name = item.getName(); if (name.contains("/")) { name = name.substring(name.lastIndexOf('/') + 1); } if (name.contains("\\")) { name = name.substring(name.lastIndexOf('\\') + 1); } if (this.xformsProcessor.isFileUpload(id, "anyURI")) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("found upload type 'anyURI'"); } String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/') .append(name).toString(); File localFile = new File(this.uploadRoot, localPath); localFile.getParentFile().mkdirs(); item.write(localFile); if (LOGGER.isDebugEnabled()) { LOGGER.debug("saving data to path: " + localFile); } // todo: externalize file handling and uri generation data = localFile.toURI().toString().getBytes("UTF-8"); } else { data = item.get(); } this.xformsProcessor.setUploadValue(id, item.getContentType(), name, data); // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done' request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo", new UploadInfo(1, 0, 0, 0, "done")); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ignoring empty upload " + id); } // todo: removal ? } item.delete(); } } catch (Exception e) { LOGGER.error(e); throw new XFormsException(e); } }
From source file:org.chiba.web.servlet._HttpRequestHandler.java
protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException { LOGGER.info("updating " + uploads.keySet().size() + " uploads(s)"); try {/*from ww w.jav a2 s.c om*/ // update repeat indices Iterator iterator = uploads.keySet().iterator(); String id; FileItem item; byte[] data; while (iterator.hasNext()) { id = (String) iterator.next(); item = (FileItem) uploads.get(id); if (item.getSize() > 0) { if (this.chibaBean.hasControlType(id, "anyURI")) { String localPath = new StringBuffer().append('/').append(id).toString(); File localFile = new File(uploadRoot + this.sessionKey, localPath); localFile.getParentFile().mkdirs(); item.write(localFile); // todo: externalize file handling and uri generation data = localFile.toURI().toString().getBytes("UTF-8"); } else { data = item.get(); } this.chibaBean.updateControlValue(id, item.getContentType(), item.getName(), data); // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done' request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo", new UploadInfo(1, 0, 0, 0, "done")); } else { LOGGER.info("ignoring empty upload " + id); // todo: removal ? } item.delete(); } } catch (Exception e) { throw new XFormsException(e); } }
From source file:org.codelabor.system.file.web.controller.xplatform.FileController.java
@RequestMapping("/upload-test") public String upload(Model model, HttpServletRequest request, ServletContext context) throws Exception { logger.debug("upload-teset"); DataSetList outputDataSetList = new DataSetList(); VariableList outputVariableList = new VariableList(); try {/*from w w w . jav a 2 s .co m*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(uniqueFilenameGenerationService.getNextStringId()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } else { } XplatformUtils.setSuccessMessage( messageSource.getMessage("info.success", new Object[] {}, forcedLocale), outputVariableList); logger.debug("success"); } catch (Exception e) { logger.error("fail"); e.printStackTrace(); logger.error(e.getMessage()); throw new XplatformException(messageSource.getMessage("error.failure", new Object[] {}, forcedLocale), e); } model.addAttribute(OUTPUT_DATA_SET_LIST, outputDataSetList); model.addAttribute(OUTPUT_VARIABLE_LIST, outputVariableList); return VIEW_NAME; }
From source file:org.codelabor.system.file.web.servlet.FileUploadServlet.java
/** * ?? .</br> ? ? ?? ? , (: ?) ? mapId . ? * ?? ? repositoryType , ?/*from w w w.j av a 2 s . c o m*/ * org.codelabor.system.file.RepositoryType . * * @param request * * @param response * ? * @throws Exception * */ @SuppressWarnings("unchecked") protected void upload(HttpServletRequest request, HttpServletResponse response) throws Exception { WebApplicationContext ctx = WebApplicationContextUtils .getRequiredWebApplicationContext(this.getServletContext()); FileManager fileManager = (FileManager) ctx.getBean("fileManager"); boolean isMultipart = ServletFileUpload.isMultipartContent(request); Map<String, Object> paramMap = RequestUtils.getParameterMap(request); logger.debug("paramMap: {}", paramMap.toString()); String mapId = (String) paramMap.get("mapId"); RepositoryType acceptedRepositoryType = repositoryType; String requestedRepositoryType = (String) paramMap.get("repositoryType"); if (StringUtils.isNotEmpty(requestedRepositoryType)) { acceptedRepositoryType = RepositoryType.valueOf(requestedRepositoryType); } if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); factory.setRepository(new File(tempRepositoryPath)); factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(this.getServletContext())); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(fileSizeMax); upload.setSizeMax(requestSizeMax); upload.setHeaderEncoding(characterEncoding); upload.setProgressListener(new FileUploadProgressListener()); try { List<FileItem> fileItemList = upload.parseRequest(request); Iterator<FileItem> iter = fileItemList.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); logger.debug("fileItem: {}", fileItem.toString()); FileDTO fileDTO = null; if (fileItem.isFormField()) { paramMap.put(fileItem.getFieldName(), fileItem.getString(characterEncoding)); } else { if (fileItem.getName() == null || fileItem.getName().length() == 0) continue; // set DTO fileDTO = new FileDTO(); fileDTO.setMapId(mapId); fileDTO.setRealFilename(FilenameUtils.getName(fileItem.getName())); if (acceptedRepositoryType == RepositoryType.FILE_SYSTEM) { fileDTO.setUniqueFilename(getUniqueFilename()); } fileDTO.setContentType(fileItem.getContentType()); fileDTO.setRepositoryPath(realRepositoryPath); logger.debug("fileDTO: {}", fileDTO.toString()); UploadUtils.processFile(acceptedRepositoryType, fileItem.getInputStream(), fileDTO); } if (fileDTO != null) fileManager.insertFile(fileDTO); } } catch (FileUploadException e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } } else { paramMap = RequestUtils.getParameterMap(request); } try { processParameters(paramMap); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); throw e; } dispatch(request, response, forwardPathUpload); }
From source file:org.codemucker.testserver.capturing.CapturedFileItem.java
public CapturedFileItem(final FileItem item) { fieldName = item.getFieldName();/*from w w w . ja va2 s .c o m*/ fileName = item.getName(); size = item.getSize(); contentType = item.getContentType(); payloadBytes = item.get(); }
From source file:org.coodex.concrete.attachments.server.UploadByFormResource.java
@Path("/{clientId}/{tokenId}") @POST/*www . j a v a2 s. co m*/ @Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA }) @Produces(MediaType.APPLICATION_JSON) public void uploadByForm(@Suspended final AsyncResponse asyncResponse, @Context final HttpServletRequest request, @PathParam("clientId") final String clientId, @PathParam("tokenId") final String tokenId) { Thread t = new Thread(new Runnable() { @Override public void run() { try { ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); List<FileItem> items = uploadHandler.parseRequest(request); List<AttachmentEntityInfo> result = new ArrayList<AttachmentEntityInfo>(); for (FileItem item : items) { if (!item.isFormField()) { if (!Common.isBlank(item.getName())) { AttachmentInfo attachmentInfo = new AttachmentInfo(); attachmentInfo.setName(item.getName()); attachmentInfo.setOwner(clientId); attachmentInfo.setSize(item.getSize()); attachmentInfo.setContentType(item.getContentType()); result.add(saveToRepo(clientId, tokenId, attachmentInfo, item.getInputStream())); } } } asyncResponse.resume(result); } catch (Throwable t) { asyncResponse.resume(t); } } }); t.setPriority(AttachmentServiceHelper.ATTACHMENT_PROFILE.getInt("upload.priority", 5)); t.start(); }
From source file:org.deegree.services.controller.OGCFrontController.java
/** * Handles HTTP POST requests.//from w w w . j a v a2 s . com * <p> * An HTTP POST request specifies parameters in the request body. OGC service specifications use three different * ways to encode the parameters: * <ul> * <li><b>KVP</b>: Parameters are given as <code>key=value</code> pairs which are separated using the & * character. This is equivalent to standard HTTP GET requests, except that the parameters are not part of the query * string, but the POST body. In this case, the <code>content-type</code> field in the header must be * <code>application/x-www-form-urlencoded</code>.</li> * <li><b>XML</b>: The POST body contains an XML document. In this case, the <code>content-type</code> field in the * header has to be <code>text/xml</code>, but the implementation does not rely on this in order to be more tolerant * to clients.</li> * <li><b>SOAP</b>: TODO</li> * <li><b>Multipart</b>: TODO</li> * </ul> */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseBuffer responseBuffer = createHttpResponseBuffer(request, response); try { logHeaders(request); addHeaders(responseBuffer); responseBuffer = handleCompression(responseBuffer); LOG.debug("doPost(), contentType: '" + request.getContentType() + "'"); long entryTime = System.currentTimeMillis(); try { // check if content-type implies that it's a KVP request String contentType = request.getContentType(); boolean isKVP = false; if (contentType != null) { isKVP = request.getContentType().startsWith("application/x-www-form-urlencoded"); } List<FileItem> multiParts = checkAndRetrieveMultiparts(request); InputStream is = request.getInputStream(); if (isKVP) { String queryString = readPostBodyAsString(is); LOG.debug("Treating POST input stream as KVP parameters. Raw input: '" + queryString + "'."); Map<String, String> normalizedKVPParams = null; String encoding = request.getCharacterEncoding(); if (encoding == null) { LOG.debug("Request has no further encoding information. Defaulting to '" + DEFAULT_ENCODING + "'."); normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, DEFAULT_ENCODING); } else { LOG.debug("Client encoding information :" + encoding); normalizedKVPParams = KVPUtils.getNormalizedKVPMap(queryString, encoding); } dispatchKVPRequest(normalizedKVPParams, request, responseBuffer, multiParts, entryTime); } else { // if( handle multiparts, get first body from multipart (?) // body->requestDoc InputStream requestInputStream = null; if (multiParts != null && multiParts.size() > 0) { for (int i = 0; i < multiParts.size() && requestInputStream == null; ++i) { FileItem item = multiParts.get(i); if (item != null) { LOG.debug("Using multipart item: " + i + " with contenttype: " + item.getContentType() + " as the request."); requestInputStream = item.getInputStream(); } } } else { requestInputStream = is; } if (requestInputStream == null) { String msg = "Could not create a valid inputstream from request " + ((multiParts != null && multiParts.size() > 0) ? "without" : "with") + " multiparts."; LOG.error(msg); throw new IOException(msg); } String dummySystemId = "HTTP Post request from " + request.getRemoteAddr() + ":" + request.getRemotePort(); XMLStreamReader xmlStream = XMLInputFactoryUtils.newSafeInstance() .createXMLStreamReader(dummySystemId, requestInputStream); // skip to start tag of root element XMLStreamUtils.nextElement(xmlStream); if (isSOAPRequest(xmlStream)) { dispatchSOAPRequest(xmlStream, request, responseBuffer, multiParts); } else { dispatchXMLRequest(xmlStream, request, responseBuffer, multiParts); } } } catch (Throwable e) { LOG.debug("Handling HTTP-POST request took: " + (System.currentTimeMillis() - entryTime) + " ms before sending exception."); LOG.debug(e.getMessage(), e); OWSException ex = new OWSException(e.getLocalizedMessage(), "InvalidRequest"); OWS ows = null; try { ows = determineOWSByPath(request); } catch (OWSException e2) { sendException(ows, e2, responseBuffer, null); return; } sendException(ows, ex, responseBuffer, null); } LOG.debug("Handling HTTP-POST request with status 'success' took: " + (System.currentTimeMillis() - entryTime) + " ms."); } finally { instance.CONTEXT.remove(); responseBuffer.flushBuffer(); if (mainConfig.isValidateResponses() != null && mainConfig.isValidateResponses()) { validateResponse(responseBuffer); } } }
From source file:org.drools.guvnor.server.files.RepositoryBackupServlet.java
private boolean isFileZipped(FileItem file) throws IOException { String mimeType = file.getContentType().toLowerCase(); return zipMimeTypes.contains(mimeType); }
From source file:org.eclipse.che.api.factory.FactoryService.java
/** * Save factory to storage and return stored data. Field 'factoryUrl' should contains factory url information. * Fields with images should be named 'image'. Acceptable image size 100x100 pixels. * If vcs is not set in factory URL it will be set with "git" value. * * @param formData/* w w w . j av a 2s .c o m*/ * - http request form data * @param uriInfo * - url context * @return - stored data * @throws org.eclipse.che.api.core.ApiException * - {@link org.eclipse.che.api.core.ConflictException} when factory url json is not found * - {@link org.eclipse.che.api.core.ConflictException} when vcs is unsupported * - {@link org.eclipse.che.api.core.ConflictException} when image content can't be read * - {@link org.eclipse.che.api.core.ConflictException} when image media type is unsupported * - {@link org.eclipse.che.api.core.ConflictException} when image height or length isn't equal to 100 pixels * - {@link org.eclipse.che.api.core.ConflictException} when if image is too big * - {@link org.eclipse.che.api.core.ServerException} when internal server error occurs */ @ApiOperation(value = "Create a Factory and return data", notes = "Save factory to storage and return stored data. Field 'factoryUrl' should contains factory url information.", response = Factory.class, position = 1) @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 409, message = "Conflict error. Some parameter is missing"), @ApiResponse(code = 500, message = "Unable to identify user from context") }) @RolesAllowed("user") @POST @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.APPLICATION_JSON }) public Factory saveFactory(Iterator<FileItem> formData, @Context UriInfo uriInfo) throws ApiException { try { EnvironmentContext context = EnvironmentContext.getCurrent(); if (context.getUser() == null || context.getUser().getName() == null || context.getUser().getId() == null) { throw new ServerException("Unable to identify user from context"); } Set<FactoryImage> images = new HashSet<>(); Factory factory = null; while (formData.hasNext()) { FileItem item = formData.next(); String fieldName = item.getFieldName(); if (fieldName.equals("factoryUrl")) { try { factory = factoryBuilder.buildEncoded(item.getInputStream()); } catch (JsonSyntaxException e) { throw new ConflictException("You have provided an invalid JSON. For more information, " + "please visit http://docs.codenvy.com/user/creating-factories/factory-parameter-reference/"); } } else if (fieldName.equals("image")) { try (InputStream inputStream = item.getInputStream()) { FactoryImage factoryImage = FactoryImage.createImage(inputStream, item.getContentType(), NameGenerator.generate(null, 16)); if (factoryImage.hasContent()) { images.add(factoryImage); } } } } if (factory == null) { LOG.warn("No factory URL information found in 'factoryUrl' section of multipart form-data."); throw new ConflictException( "No factory URL information found in 'factoryUrl' section of multipart/form-data."); } processDefaults(factory); createValidator.validateOnCreate(factory); String factoryId = factoryStore.saveFactory(factory, images); factory = factoryStore.getFactory(factoryId); factory = factory.withLinks(linksHelper.createLinks(factory, images, uriInfo)); LOG.info( "EVENT#factory-created# WS#{}# USER#{}# PROJECT#{}# TYPE#{}# REPO-URL#{}# FACTORY-URL#{}# AFFILIATE-ID#{}# ORG-ID#{}#", "", context.getUser().getName(), "", nullToEmpty(factory.getProject() != null ? factory.getProject().getType() : null), factory.getSource().getProject().getLocation(), linksHelper.getLinkByRelation(factory.getLinks(), "create-project").iterator().next().getHref(), "", nullToEmpty(factory.getCreator().getAccountId())); return factory; } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new ServerException(e.getLocalizedMessage(), e); } }