List of usage examples for org.apache.commons.fileupload FileUploadBase isMultipartContent
public static final boolean isMultipartContent(HttpServletRequest req)
From source file:org.sonatype.nexus.repository.httpbridge.internal.HttpPartIteratorAdapter.java
/** * Determine if given request is multipart. *//*from ww w . j a v a 2s .co m*/ public static boolean isMultipart(final HttpServletRequest httpRequest) { // We're circumventing ServletFileUpload.isMultipartContent as some clients (nuget) use PUT for multipart uploads return FileUploadBase.isMultipartContent(new ServletRequestContext(httpRequest)); }
From source file:org.sonatype.nexus.repository.httpbridge.internal.HttpRequestAdapter.java
public HttpRequestAdapter(final HttpServletRequest httpServletRequest, final String path) { checkNotNull(httpServletRequest);/* ww w . j ava 2s. c o m*/ this.action = httpServletRequest.getMethod(); this.requestUrl = httpServletRequest.getRequestURL().toString(); this.path = checkNotNull(path); this.parameters = new HttpParametersAdapter(httpServletRequest); this.headers = new HttpHeadersAdapter(httpServletRequest); // copy http-servlet-request attributes Enumeration<String> attributes = httpServletRequest.getAttributeNames(); while (attributes.hasMoreElements()) { String name = attributes.nextElement(); getAttributes().set(name, httpServletRequest.getAttribute(name)); } this.payload = new HttpRequestPayloadAdapter(httpServletRequest); // We're circumventing ServletFileUpload.isMultipartContent as some clients (nuget) use PUT for multipart uploads this.multipart = FileUploadBase.isMultipartContent(new ServletRequestContext(httpServletRequest)); if (multipart) { this.multiPayloads = new HttpPartIteratorAdapter(httpServletRequest); } }
From source file:org.talend.mdm.webapp.browserecords.server.servlet.UploadData.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ response.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ if (!FileUploadBase.isMultipartContent(request)) { throw new ServletException(MESSAGES.getMessage("error_upload")); //$NON-NLS-1$ }/* w w w . j av a 2s .c om*/ // Create a new file upload handler DiskFileUpload upload = new DiskFileUpload(); // Set upload parameters upload.setSizeThreshold(0); upload.setSizeMax(-1); PrintWriter writer = response.getWriter(); try { String concept = null; String seperator = null; String textDelimiter = "\""; //$NON-NLS-1$ String language = "en"; //$NON-NLS-1$ Locale locale = null; String encoding = "utf-8";//$NON-NLS-1$ Map<String, Boolean> headerVisibleMap = new LinkedHashMap<String, Boolean>(); String headerString = null; String mandatoryField = null; List<String> inheritanceNodePathList = null; boolean headersOnFirstLine = false; boolean isPartialUpdate = false; String multipleValueSeparator = null; String fileType = null; File file = null; // Parse the request List<FileItem> items = upload.parseRequest(request); // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { // FIXME: should handle more than files in parts e.g. text passed as parameter FileItem item = iter.next(); if (item.isFormField()) { // we are not expecting any field just (one) file(s) String name = item.getFieldName(); LOG.debug("doPost() Field: '" + name + "' - value:'" + item.getString() + "'"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (name.equals("concept")) { //$NON-NLS-1$ concept = item.getString(); } else if (name.equals("sep")) { //$NON-NLS-1$ seperator = item.getString(); } else if (name.equals("delimiter")) { //$NON-NLS-1$ textDelimiter = item.getString(); } else if (name.equals("language")) { //$NON-NLS-1$ locale = new Locale(item.getString()); } else if (name.equals("encodings")) { //$NON-NLS-1$ encoding = item.getString(); } else if (name.equals("header")) { //$NON-NLS-1$ headerString = item.getString(); List<String> headerItemList = org.talend.mdm.webapp.base.shared.util.CommonUtil .convertStrigToList(headerString, Constants.FILE_EXPORT_IMPORT_SEPARATOR); if (headerItemList != null) { for (String headerItem : headerItemList) { String[] headerItemArray = headerItem.split(Constants.HEADER_VISIBILITY_SEPARATOR); headerVisibleMap.put(headerItemArray[0], Boolean.valueOf(headerItemArray[1])); } } } else if (name.equals("mandatoryField")) { //$NON-NLS-1$ mandatoryField = item.getString(); } else if (name.equals("inheritanceNodePath")) { //$NON-NLS-1$ inheritanceNodePathList = org.talend.mdm.webapp.base.shared.util.CommonUtil .convertStrigToList(item.getString(), Constants.FILE_EXPORT_IMPORT_SEPARATOR); } else if (name.equals("headersOnFirstLine")) { //$NON-NLS-1$ headersOnFirstLine = "on".equals(item.getString()); //$NON-NLS-1$ } else if (name.equals("multipleValueSeparator")) { //$NON-NLS-1$ multipleValueSeparator = item.getString(); } else if (name.equals("isPartialUpdate")) { //$NON-NLS-1$ isPartialUpdate = "on".equals(item.getString()); //$NON-NLS-1$ } } else { fileType = FileUtil.getFileType(item.getName()); file = File.createTempFile("upload", "tmp");//$NON-NLS-1$ //$NON-NLS-2$ LOG.debug("doPost() data uploaded in " + file.getAbsolutePath()); //$NON-NLS-1$ file.deleteOnExit(); item.write(file); } // if field } // while item if (!UploadUtil.isViewableXpathValid(headerVisibleMap.keySet(), concept)) { throw new UploadException(MESSAGES.getMessage(locale, "error_invaild_field", concept)); //$NON-NLS-1$ } Set<String> mandatorySet = UploadUtil.chechMandatoryField( org.talend.mdm.webapp.base.shared.util.CommonUtil.unescape(mandatoryField), headerVisibleMap.keySet()); if (mandatorySet.size() > 0) { throw new UploadException(MESSAGES.getMessage(locale, "error_missing_mandatory_field")); //$NON-NLS-1$ } UploadService service = generateUploadService(concept, fileType, isPartialUpdate, headersOnFirstLine, headerVisibleMap, inheritanceNodePathList, multipleValueSeparator, seperator, encoding, textDelimiter.charAt(0), language); List<WSPutItemWithReport> wsPutItemWithReportList = service.readUploadFile(file); putDocument(new WSPutItemWithReportArray( wsPutItemWithReportList.toArray(new WSPutItemWithReport[wsPutItemWithReportList.size()])), concept); writer.print(Constants.IMPORT_SUCCESS); } catch (Exception exception) { LOG.error(exception.getMessage(), exception); writer.print(extractErrorMessage(exception.getMessage())); } finally { writer.close(); } }
From source file:psiprobe.controllers.deploy.CopySingleFileController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { List<Context> apps; try {//from w ww .j a va2 s.com apps = getContainerWrapper().getTomcatContainer().findContexts(); } catch (NullPointerException ex) { throw new IllegalStateException( "No container found for your server: " + getServletContext().getServerInfo(), ex); } List<Map<String, String>> applications = new ArrayList<>(); for (Context appContext : apps) { // check if this is not the ROOT webapp if (appContext.getName() != null && appContext.getName().trim().length() > 0) { Map<String, String> app = new HashMap<>(); app.put("value", appContext.getName()); app.put("label", appContext.getName()); applications.add(app); } } request.setAttribute("apps", applications); if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { File tmpFile = null; String contextName = null; String where = null; boolean reload = false; boolean discard = false; // parse multipart request and extract the file FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); try { List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fi : fileItems) { if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpFile = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpFile); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("where".equals(fi.getFieldName())) { where = fi.getString(); } else if ("reload".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { reload = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.error("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.file.uploadfailure", new Object[] { e.getMessage() })); if (tmpFile != null && tmpFile.exists() && !tmpFile.delete()) { logger.error("Unable to delete temp upload file"); } tmpFile = null; } String errMsg = null; if (tmpFile != null) { try { if (tmpFile.getName() != null && tmpFile.getName().trim().length() > 0) { contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); // Check if context is already deployed if (getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { File destFile = new File(getContainerWrapper().getTomcatContainer().getAppBase(), contextName + where); // Checks if the destination path exists if (destFile.exists()) { if (!destFile.getAbsolutePath().contains("..")) { // Copy the file overwriting it if it // already exists FileUtils.copyFileToDirectory(tmpFile, destFile); request.setAttribute("successFile", Boolean.TRUE); // Logging action Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); // get username // logger logger.info(getMessageSourceAccessor().getMessage("probe.src.log.copyfile"), name, contextName); Context context = getContainerWrapper().getTomcatContainer() .findContext(contextName); // Checks if DISCARD "work" directory is // selected if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(context); logger.info( getMessageSourceAccessor().getMessage("probe.src.log.discardwork"), name, contextName); } // Checks if RELOAD option is selected if (reload) { if (context != null) { context.reload(); request.setAttribute("reloadContext", Boolean.TRUE); logger.info( getMessageSourceAccessor().getMessage("probe.src.log.reload"), name, contextName); } } } else { errMsg = getMessageSourceAccessor() .getMessage("probe.src.deploy.file.pathNotValid"); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notPath"); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.notFile.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.file.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } if (!tmpFile.delete()) { logger.error("Unable to delete temp upload file"); } } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:psiprobe.controllers.deploy.UploadWarController.java
@Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { if (FileUploadBase.isMultipartContent(new ServletRequestContext(request))) { File tmpWar = null;/*from w ww .j a va 2 s .c o m*/ String contextName = null; boolean update = false; boolean compile = false; boolean discard = false; // parse multipart request and extract the file FileItemFactory factory = new DiskFileItemFactory(1048000, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(-1); upload.setHeaderEncoding(StandardCharsets.UTF_8.name()); try { List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fi : fileItems) { if (!fi.isFormField()) { if (fi.getName() != null && fi.getName().length() > 0) { tmpWar = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(fi.getName())); fi.write(tmpWar); } } else if ("context".equals(fi.getFieldName())) { contextName = fi.getString(); } else if ("update".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { update = true; } else if ("compile".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { compile = true; } else if ("discard".equals(fi.getFieldName()) && "yes".equals(fi.getString())) { discard = true; } } } catch (Exception e) { logger.error("Could not process file upload", e); request.setAttribute("errorMessage", getMessageSourceAccessor() .getMessage("probe.src.deploy.war.uploadfailure", new Object[] { e.getMessage() })); if (tmpWar != null && tmpWar.exists() && !tmpWar.delete()) { logger.error("Unable to delete temp war file"); } tmpWar = null; } String errMsg = null; if (tmpWar != null) { try { if (tmpWar.getName().endsWith(".war")) { if (contextName == null || contextName.length() == 0) { String warFileName = tmpWar.getName().replaceAll("\\.war$", ""); contextName = "/" + warFileName; } contextName = getContainerWrapper().getTomcatContainer().formatContextName(contextName); /* * pass the name of the newly deployed context to the presentation layer using this name * the presentation layer can render a url to view compilation details */ String visibleContextName = "".equals(contextName) ? "/" : contextName; request.setAttribute("contextName", visibleContextName); if (update && getContainerWrapper().getTomcatContainer().findContext(contextName) != null) { logger.debug("updating {}: removing the old copy", contextName); getContainerWrapper().getTomcatContainer().remove(contextName); } if (getContainerWrapper().getTomcatContainer().findContext(contextName) == null) { // move the .war to tomcat application base dir String destWarFilename = getContainerWrapper().getTomcatContainer() .formatContextFilename(contextName); File destWar = new File(getContainerWrapper().getTomcatContainer().getAppBase(), destWarFilename + ".war"); FileUtils.moveFile(tmpWar, destWar); // let Tomcat know that the file is there getContainerWrapper().getTomcatContainer().installWar(contextName, new URL("jar:" + destWar.toURI().toURL().toString() + "!/")); Context ctx = getContainerWrapper().getTomcatContainer().findContext(contextName); if (ctx == null) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notinstalled", new Object[] { visibleContextName }); } else { request.setAttribute("success", Boolean.TRUE); // Logging action Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String name = auth.getName(); // get username logger logger.info(getMessageSourceAccessor().getMessage("probe.src.log.deploywar"), name, contextName); if (discard) { getContainerWrapper().getTomcatContainer().discardWorkDir(ctx); logger.info(getMessageSourceAccessor().getMessage("probe.src.log.discardwork"), name, contextName); } if (compile) { Summary summary = new Summary(); summary.setName(ctx.getName()); getContainerWrapper().getTomcatContainer().listContextJsps(ctx, summary, true); request.getSession(false).setAttribute(DisplayJspController.SUMMARY_ATTRIBUTE, summary); request.setAttribute("compileSuccess", Boolean.TRUE); } } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.alreadyExists", new Object[] { visibleContextName }); } } else { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.notWar.failure"); } } catch (Exception e) { errMsg = getMessageSourceAccessor().getMessage("probe.src.deploy.war.failure", new Object[] { e.getMessage() }); logger.error("Tomcat throw an exception when trying to deploy", e); } finally { if (errMsg != null) { request.setAttribute("errorMessage", errMsg); } if (tmpWar.exists() && !tmpWar.delete()) { logger.error("Unable to delete temp war file"); } } } } return new ModelAndView(new InternalResourceView(getViewName())); }
From source file:sif.servlet.Request.java
Request(Servlet srv, HttpServletRequest req, HttpServletResponse resp) { servlet = srv;/* w ww .j a v a2 s.c om*/ request = req; response = resp; session = getSessionState(null).sessionPrincipal(); bnd = Servlet.getOutputChannelBound(this); this.isMultipart = FileUploadBase.isMultipartContent(req); if (!isMultipart) { parameterMap = req.getParameterMap(); } else { parameterMap = new HashMap<String, String>(); fileMap = new HashMap<String, FileItem>(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // set the maximum upload size to 100 kB upload.setSizeMax(100 * 1024); // Parse the request try { List<FileItem> items = upload.parseRequest(request); for (FileItem element : items) { FileItem item = element; if (item.isFormField()) { parameterMap.put(item.getFieldName(), item.getString()); } else { // put the item into the fileMap fileMap.put(item.getFieldName(), item); } } } catch (FileUploadException e) { e.printStackTrace(); } } }
From source file:uk.ac.ed.epcc.webapp.servlet.MultiPartServletService.java
@SuppressWarnings("deprecation") @Override//from w w w . j a v a2 s. com public Map<String, Object> makeParams(HttpServletRequest req) { Map<String, Object> h = super.makeParams(req); if (FileUploadBase.isMultipartContent(req)) { FileItemFactory factory = new DiskFileItemFactory(); Logger log = conn.getService(LoggerService.class).getLogger(getClass()); log.debug("Processing multipart form"); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items; try { items = upload.parseRequest(req); String characterEncoding = req.getCharacterEncoding(); for (Iterator it = items.iterator(); it.hasNext();) { FileItem i = (FileItem) it.next(); String name = i.getFieldName(); if (i.isFormField()) { log.debug("add parameter <" + name + ":" + i.getString() + ">"); try { if (characterEncoding == null) { h.put(name, i.getString()); } else { h.put(name, i.getString(characterEncoding)); } } catch (UnsupportedEncodingException e) { h.put(name, i.getString()); } } else { if (i.getSize() > 0) { log.debug("add file " + name + ":" + i.getName() + " length:" + i.getSize() + " type:" + i.getContentType()); h.put(name, new FileItemStreamData(conn, i)); } } } } catch (FileUploadException e) { throw new ConsistencyError("Error parsing multipart form", e); } } return h; }